diff --git a/Cargo.lock b/Cargo.lock index 42e16a7..4776873 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9124,6 +9124,7 @@ dependencies = [ "base64 0.22.1", "clap", "futures", + "futures-util", "rand 0.10.3", "rusqlite", "serde", @@ -9135,6 +9136,7 @@ dependencies = [ "toml", "tracing", "tracing-subscriber", + "tsproto-types", "voelin-gateway-proto", "voelin-model", "voelin-observer", @@ -9146,11 +9148,14 @@ name = "voelin-gateway-proto" version = "0.1.0" dependencies = [ "base64 0.22.1", + "futures-util", "serde", "serde_json", "sha-1", "sha2 0.10.9", "thiserror 2.0.21", + "tokio", + "tokio-tungstenite 0.30.0", "tsproto", "tsproto-types", "voelin-model", diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 0bbceb3..5b507cb 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -32,7 +32,7 @@ tokio-tungstenite = "0.30" toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } -voelin-gateway-proto = { path = "../voelin-gateway-proto" } +voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true } voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index 1b0b74d..fba4406 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -1,11 +1,21 @@ -//! The gateway source: presence and relayed chat through `tsgw`. +//! The gateway source: presence and relayed chat through `tsgw`, and the +//! typed client for everything else a gateway offers (pins, reactions, +//! topics, events, the stream directory, the activity feed, +//! administration). +//! +//! [`GatewayClient`] (from `voelin-gateway-proto`, feature `client`) has one +//! async method per request and delivers pushes as [`Push`]; +//! [`GatewayClient::capabilities`] says which features the gateway and user +//! have, so the UI can hide the rest. The data types (`HistoryQuery`, +//! `PinInfo`, `EventSpec`, `StreamEntry`, …) are in `voelin_gateway_proto`. +//! [`connect`] logs in with the user's TeamSpeak identity. The engine uses +//! [`run`] for presence and chat. -use futures::{SinkExt, StreamExt}; use tokio::sync::mpsc; -use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tracing::info; -use voelin_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge}; +use voelin_gateway_proto::client::Login; +pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push}; +use voelin_gateway_proto::{ClientMsg, ErrorCode}; use voelin_model::{ChatMessage, ChatTarget, Presence}; pub(crate) enum GatewayCmd { @@ -23,6 +33,16 @@ pub(crate) enum GatewayEvent { Disconnected(Option), } +/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a +/// TeamSpeak identity. +pub async fn connect( + url: &str, + identity: &tsclientlib::Identity, +) -> Result<(GatewayClient, mpsc::UnboundedReceiver), ClientError> { + let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() }; + voelin_gateway_proto::client::connect(url, login).await +} + pub(crate) async fn run( url: String, identity: tsclientlib::Identity, @@ -40,82 +60,53 @@ async fn run_inner( commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { - let mut request = url.into_client_request()?; - request - .headers_mut() - .insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse()?); - let (mut ws, _) = tokio_tungstenite::connect_async(request).await?; - let mut next_id = 1u64; + let (client, mut pushes) = match connect(url, identity).await { + Ok(connected) => connected, + Err(ClientError::Gateway { code, message }) => { + let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); + anyhow::bail!("gateway refused login: {message}"); + } + Err(e) => return Err(e.into()), + }; + info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected"); + let _ = events.send(GatewayEvent::Connected); + client.subscribe_presence()?; let mut presence = Presence::default(); - macro_rules! send { - ($msg:expr) => {{ - next_id += 1; - let env = Envelope::with_id(next_id, $msg); - ws.send(Message::Text(serde_json::to_string(&env)?.into())).await?; - }}; - } - loop { tokio::select! { - msg = ws.next() => { - let text = match msg { - Some(Ok(Message::Text(t))) => t, - Some(Ok(Message::Close(_))) | None => return Ok(()), - Some(Ok(_)) => continue, - Some(Err(e)) => return Err(e.into()), - }; - let env: Envelope = serde_json::from_str(text.as_str())?; - match env.msg { - ServerMsg::Hello { gateway_id, server_uid, nonce, server_name, .. } => { - let ts = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH)? - .as_secs() as i64; - let key = identity.key(); - send!(ClientMsg::Auth { - omega: key.to_pub().to_ts(), - key_offset: identity.counter(), - ts, - signature: sign_challenge(key, &gateway_id, &server_uid, &nonce, ts), - nickname: String::new(), - }); - info!(%server_name, "gateway hello"); - } - ServerMsg::AuthOk { .. } => { - let _ = events.send(GatewayEvent::Connected); - send!(ClientMsg::SubscribePresence); - } - ServerMsg::PresenceSnapshot { snapshot, .. } => { - presence = Presence::from_snapshot(snapshot); - let _ = events.send(GatewayEvent::Presence(presence.clone())); - } - ServerMsg::PresenceDelta { delta, .. } => { - presence.apply(&delta); - let _ = events.send(GatewayEvent::Presence(presence.clone())); - } - ServerMsg::ChatEvent { message, .. } => { - let _ = events.send(GatewayEvent::Chat(message)); - } - ServerMsg::Error { code, message } => { - let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); - if matches!( - code, - voelin_gateway_proto::ErrorCode::AuthFailed - | voelin_gateway_proto::ErrorCode::UnknownIdentity - | voelin_gateway_proto::ErrorCode::LevelTooLow - | voelin_gateway_proto::ErrorCode::Banned - ) { - anyhow::bail!("gateway refused login: {message}"); - } - } - _ => {} + push = pushes.recv() => match push { + None | Some(Push::Disconnected(None)) => return Ok(()), + Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason), + Some(Push::PresenceSnapshot(snapshot)) => { + presence = Presence::from_snapshot(snapshot); + let _ = events.send(GatewayEvent::Presence(presence.clone())); } - } + Some(Push::PresenceDelta(delta)) => { + presence.apply(&delta); + let _ = events.send(GatewayEvent::Presence(presence.clone())); + } + Some(Push::Chat { message, .. }) => { + let _ = events.send(GatewayEvent::Chat(message)); + } + Some(Push::Message(entry)) => { + let _ = events.send(GatewayEvent::Chat(entry.message)); + } + Some(Push::Error { code, message }) => { + let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); + if code == ErrorCode::NotAuthenticated { + anyhow::bail!("gateway session lost: {message}"); + } + } + Some(_) => {} + }, cmd = commands.recv() => match cmd { None | Some(GatewayCmd::Stop) => return Ok(()), - Some(GatewayCmd::OpenChat(target)) => send!(ClientMsg::OpenChat { target }), - Some(GatewayCmd::CloseChat(target)) => send!(ClientMsg::CloseChat { target }), - Some(GatewayCmd::SendChat(target, text)) => send!(ClientMsg::SendChat { target, text }), + Some(GatewayCmd::OpenChat(target)) => client.send(ClientMsg::OpenChat { target })?, + Some(GatewayCmd::CloseChat(target)) => client.send(ClientMsg::CloseChat { target })?, + Some(GatewayCmd::SendChat(target, text)) => { + client.send(ClientMsg::SendChat { target, text })?; + } }, } } diff --git a/crates/voelin-gateway-proto/Cargo.toml b/crates/voelin-gateway-proto/Cargo.toml index 32e96e7..64ad14b 100644 --- a/crates/voelin-gateway-proto/Cargo.toml +++ b/crates/voelin-gateway-proto/Cargo.toml @@ -8,13 +8,20 @@ license.workspace = true repository.workspace = true publish.workspace = true +[features] +# A typed WebSocket client (`voelin_gateway_proto::client`). +client = ["dep:futures-util", "dep:tokio", "dep:tokio-tungstenite"] + [dependencies] base64 = "0.22" +futures-util = { version = "0.3.34", features = ["sink"], optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" sha1 = { package = "sha-1", version = "0.10" } sha2 = "0.10" thiserror = "2" +tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true } +tokio-tungstenite = { version = "0.30", optional = true } voelin-model = { path = "../voelin-model" } tsproto-types = { path = "../proto/tsproto-types" } diff --git a/crates/voelin-gateway-proto/src/client.rs b/crates/voelin-gateway-proto/src/client.rs new file mode 100644 index 0000000..48b6c7c --- /dev/null +++ b/crates/voelin-gateway-proto/src/client.rs @@ -0,0 +1,734 @@ +//! A typed client (feature `client`): log in, send requests and await their +//! answers, receive pushes. +//! +//! [`GatewayClient`] is a cheap handle to a task that owns the WebSocket. +//! Requests get an envelope id; the answer with the same id completes the +//! request. Everything else (pushes, answers to requests sent with +//! [`GatewayClient::send`]) arrives on the [`Push`] receiver. +//! +//! ```no_run +//! # async fn demo(key: tsproto_types::crypto::EccKeyPrivP256) -> Result<(), voelin_gateway_proto::client::ClientError> { +//! use voelin_gateway_proto::client::{Login, connect}; +//! use voelin_model::ChatTarget; +//! let login = Login::Identity { key, key_offset: 0 }; +//! let (client, mut pushes) = connect("ws://127.0.0.1:7788/v1", login).await?; +//! if client.has(voelin_gateway_proto::feature::PINS) { +//! let pins = client.pins(ChatTarget::Channel(1)).await?; +//! } +//! while let Some(push) = pushes.recv().await { /* ... */ } +//! # Ok(()) } +//! ``` + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, RwLock}; + +use futures_util::{Sink, SinkExt, Stream, StreamExt}; +use tokio::sync::{mpsc, oneshot}; +use tokio_tungstenite::tungstenite::{self, Message}; +use tsproto_types::crypto::EccKeyPrivP256; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; + +use crate::messages::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg}; +use crate::types::*; + +/// How to log in. +pub enum Login { + /// Sign the challenge with a TeamSpeak identity. + Identity { + key: EccKeyPrivP256, + /// Hash-cash counter of the identity. + key_offset: u64, + }, + /// A token from an earlier login ([`GatewayClient::token`]). + Token(String), +} + +#[derive(Debug, thiserror::Error)] +pub enum ClientError { + /// The gateway answered with an error. + #[error("{code:?}: {message}")] + Gateway { code: ErrorCode, message: String }, + /// The gateway answered with a message that does not fit the request. + #[error("unexpected answer: {0}")] + Unexpected(String), + #[error("connection closed")] + Closed, + #[error("websocket: {0}")] + WebSocket(#[from] tungstenite::Error), + #[error("invalid message: {0}")] + Json(#[from] serde_json::Error), +} + +impl ClientError { + /// The gateway's error code, if the gateway refused the request. + pub fn code(&self) -> Option { + match self { + ClientError::Gateway { code, .. } => Some(*code), + _ => None, + } + } + + fn unexpected(msg: ServerMsg) -> Self { + ClientError::Unexpected(format!("{msg:?}")) + } +} + +/// Messages the gateway sends on its own, or answers to requests nobody +/// waits for. +#[derive(Clone, Debug, PartialEq)] +pub enum Push { + PresenceSnapshot(PresenceSnapshot), + PresenceDelta(PresenceDelta), + /// A message in an open chat (sessions without [`GatewayClient::enable`]). + Chat { + id: i64, + message: ChatMessage, + }, + /// A message in an open chat, with its gateway metadata. + Message(HistoryEntry), + Pinned { + target: ChatTarget, + pin: PinInfo, + }, + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + TopicUpdated(TopicInfo), + EventUpdated(EventInfo), + EventDeleted(i64), + EventReminder { + event: EventInfo, + starts_in_ms: i64, + }, + StreamStarted(StreamEntry), + StreamUpdated(StreamEntry), + StreamEnded { + id: String, + reason: String, + }, + ActivityAdded(ActivityEntry), + /// The features available to this user changed; also in + /// [`GatewayClient::capabilities`]. + Capabilities(Vec), + /// A request sent with [`GatewayClient::send`] failed. + Error { + code: ErrorCode, + message: String, + }, + /// Anything else, e.g. `ok` answers to [`GatewayClient::send`]. + Other(ServerMsg), + /// The connection ended; the last push. + Disconnected(Option), +} + +impl From for Push { + fn from(msg: ServerMsg) -> Self { + match msg { + ServerMsg::PresenceSnapshot { snapshot, .. } => Push::PresenceSnapshot(snapshot), + ServerMsg::PresenceDelta { delta, .. } => Push::PresenceDelta(delta), + ServerMsg::ChatEvent { id, message } => Push::Chat { id, message }, + ServerMsg::Message { entry } => Push::Message(entry), + ServerMsg::Pinned { target, pin } => Push::Pinned { target, pin }, + ServerMsg::Unpinned { target, message_id, by } => { + Push::Unpinned { target, message_id, by } + } + ServerMsg::Reaction { target, message_id, emoji, user, added, count } => { + Push::Reaction { target, message_id, emoji, user, added, count } + } + ServerMsg::TopicUpdated { topic } => Push::TopicUpdated(topic), + ServerMsg::EventUpdated { event } => Push::EventUpdated(event), + ServerMsg::EventDeleted { id } => Push::EventDeleted(id), + ServerMsg::EventReminder { event, starts_in_ms } => { + Push::EventReminder { event, starts_in_ms } + } + ServerMsg::StreamStarted { stream } => Push::StreamStarted(stream), + ServerMsg::StreamUpdated { stream } => Push::StreamUpdated(stream), + ServerMsg::StreamEnded { id, reason } => Push::StreamEnded { id, reason }, + ServerMsg::ActivityAdded { entry } => Push::ActivityAdded(entry), + ServerMsg::Capabilities { capabilities } => Push::Capabilities(capabilities), + ServerMsg::Error { code, message } => Push::Error { code, message }, + other => Push::Other(other), + } + } +} + +/// What the gateway said about itself and the user at login. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SessionInfo { + pub gateway_id: String, + pub server_uid: String, + pub server_name: String, + /// The user's unique id on the server. + pub uid: String, + pub token: String, + /// Unix seconds. + pub token_expires: i64, +} + +struct Outgoing { + id: u64, + msg: ClientMsg, + reply: Option>, +} + +/// Handle to a logged-in gateway connection. Clones share the connection; +/// it closes when the last handle is dropped. +#[derive(Clone)] +pub struct GatewayClient { + out: mpsc::UnboundedSender, + info: Arc, + capabilities: Arc>>, + next_id: Arc, +} + +/// Connect to `url` (e.g. `ws://127.0.0.1:7788/v1`) and log in. +pub async fn connect( + url: &str, + login: Login, +) -> Result<(GatewayClient, mpsc::UnboundedReceiver), ClientError> { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let mut request = url.into_client_request()?; + request.headers_mut().insert( + "Sec-WebSocket-Protocol", + tungstenite::http::HeaderValue::from_static(crate::SUBPROTOCOL), + ); + let (ws, _) = tokio_tungstenite::connect_async(request).await?; + GatewayClient::start(ws, login).await +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or_default() +} + +async fn recv(ws: &mut S) -> Result, ClientError> +where + S: Stream> + Unpin, +{ + loop { + match ws.next().await { + Some(Ok(Message::Text(text))) => return Ok(serde_json::from_str(text.as_str())?), + Some(Ok(Message::Close(_))) | None => return Err(ClientError::Closed), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(e.into()), + } + } +} + +async fn send_frame(ws: &mut S, id: u64, msg: ClientMsg) -> Result<(), ClientError> +where + S: Sink + Unpin, +{ + let text = serde_json::to_string(&Envelope::with_id(id, msg))?; + ws.send(Message::Text(text.into())).await?; + Ok(()) +} + +impl GatewayClient { + /// Log in over an open WebSocket (subprotocol [`crate::SUBPROTOCOL`]) and + /// start the connection task. + pub async fn start( + mut ws: S, + login: Login, + ) -> Result<(Self, mpsc::UnboundedReceiver), ClientError> + where + S: Stream> + + Sink + + Unpin + + Send + + 'static, + { + let (gateway_id, server_uid, server_name, nonce) = match recv(&mut ws).await?.msg { + ServerMsg::Hello { gateway_id, server_uid, server_name, nonce, .. } => { + (gateway_id, server_uid, server_name, nonce) + } + other => return Err(ClientError::unexpected(other)), + }; + let msg = match login { + Login::Identity { key, key_offset } => { + let ts = now_secs(); + ClientMsg::Auth { + omega: key.to_pub().to_ts(), + key_offset, + ts, + signature: crate::sign_challenge(&key, &gateway_id, &server_uid, &nonce, ts), + nickname: String::new(), + } + } + Login::Token(token) => ClientMsg::Resume { token, nickname: String::new() }, + }; + send_frame(&mut ws, 1, msg).await?; + let (uid, token, token_expires, capabilities) = match recv(&mut ws).await?.msg { + ServerMsg::AuthOk { uid, token, token_expires, capabilities } => { + (uid, token, token_expires, capabilities) + } + ServerMsg::Error { code, message } => { + return Err(ClientError::Gateway { code, message }); + } + other => return Err(ClientError::unexpected(other)), + }; + let info = Arc::new(SessionInfo { + gateway_id, + server_uid, + server_name, + uid, + token, + token_expires, + }); + let capabilities = Arc::new(RwLock::new(capabilities)); + let (out, out_rx) = mpsc::unbounded_channel(); + let (push_tx, pushes) = mpsc::unbounded_channel(); + tokio::spawn(run(ws, out_rx, push_tx, capabilities.clone())); + Ok((Self { out, info, capabilities, next_id: Arc::new(AtomicU64::new(2)) }, pushes)) + } + + pub fn info(&self) -> &SessionInfo { + &self.info + } + + /// The user's unique id on the server. + pub fn uid(&self) -> &str { + &self.info.uid + } + + /// Log in again with this instead of a signature ([`Login::Token`]). + pub fn token(&self) -> &str { + &self.info.token + } + + /// Features available to this user (see [`crate::feature`]); kept up to + /// date while connected. Hide what is missing. + pub fn capabilities(&self) -> Vec { + self.capabilities.read().unwrap().clone() + } + + pub fn has(&self, feature: &str) -> bool { + self.capabilities.read().unwrap().iter().any(|c| c == feature) + } + + pub fn is_connected(&self) -> bool { + !self.out.is_closed() + } + + /// Send without waiting; the answer arrives as a [`Push`]. + pub fn send(&self, msg: ClientMsg) -> Result<(), ClientError> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + self.out.send(Outgoing { id, msg, reply: None }).map_err(|_| ClientError::Closed) + } + + /// Send and wait for the answer. An `error` answer is returned as + /// [`ClientError::Gateway`]. + pub async fn request(&self, msg: ClientMsg) -> Result { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let (reply, rx) = oneshot::channel(); + self.out.send(Outgoing { id, msg, reply: Some(reply) }).map_err(|_| ClientError::Closed)?; + match rx.await.map_err(|_| ClientError::Closed)? { + ServerMsg::Error { code, message } => Err(ClientError::Gateway { code, message }), + msg => Ok(msg), + } + } + + async fn ok(&self, msg: ClientMsg) -> Result<(), ClientError> { + match self.request(msg).await? { + ServerMsg::Ok => Ok(()), + other => Err(ClientError::unexpected(other)), + } + } +} + +/// Typed requests. Chat and presence pushes need the matching +/// open/subscribe request; extension pushes for open chats need +/// [`GatewayClient::enable`]. +impl GatewayClient { + /// Start the presence stream; the snapshot arrives as a push. + pub fn subscribe_presence(&self) -> Result<(), ClientError> { + self.send(ClientMsg::SubscribePresence) + } + + pub async fn unsubscribe_presence(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribePresence).await + } + + pub async fn open_chat(&self, target: ChatTarget) -> Result<(), ClientError> { + self.ok(ClientMsg::OpenChat { target }).await + } + + pub async fn close_chat(&self, target: ChatTarget) -> Result<(), ClientError> { + self.ok(ClientMsg::CloseChat { target }).await + } + + pub async fn send_chat(&self, target: ChatTarget, text: String) -> Result<(), ClientError> { + self.ok(ClientMsg::SendChat { target, text }).await + } + + pub async fn ping(&self) -> Result<(), ClientError> { + match self.request(ClientMsg::Ping).await? { + ServerMsg::Pong => Ok(()), + other => Err(ClientError::unexpected(other)), + } + } + + /// Receive the extension pushes for open chats; returns the features enabled. + pub async fn enable(&self, features: Vec) -> Result, ClientError> { + match self.request(ClientMsg::Enable { features }).await? { + ServerMsg::Enabled { features } => Ok(features), + other => Err(ClientError::unexpected(other)), + } + } + + /// What the user may do, server-wide or in `channel`. + pub async fn permissions( + &self, + channel: Option, + ) -> Result, ClientError> { + match self.request(ClientMsg::Permissions { channel }).await? { + ServerMsg::Permissions { actions, .. } => Ok(actions), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn history(&self, query: HistoryQuery) -> Result { + match self.request(ClientMsg::QueryHistory(query)).await? { + ServerMsg::HistoryPage(page) => Ok(page), + other => Err(ClientError::unexpected(other)), + } + } + + /// New and changed messages since `since_rev`; returns them with the + /// revision to pass next time and whether more are waiting. + pub async fn sync( + &self, + target: ChatTarget, + since_rev: i64, + limit: Option, + ) -> Result<(Vec, i64, bool), ClientError> { + match self.request(ClientMsg::Sync { target, since_rev, limit }).await? { + ServerMsg::SyncPage { messages, rev, has_more, .. } => Ok((messages, rev, has_more)), + other => Err(ClientError::unexpected(other)), + } + } + + /// Post, optionally into a topic; returns the stored message. + pub async fn post( + &self, + target: ChatTarget, + text: String, + topic: Option, + ) -> Result { + match self.request(ClientMsg::Post { target, text, topic }).await? { + ServerMsg::Posted { entry } => Ok(entry), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn pin(&self, message_id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::Pin { message_id }).await + } + + pub async fn unpin(&self, message_id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::Unpin { message_id }).await + } + + pub async fn pins(&self, target: ChatTarget) -> Result, ClientError> { + match self.request(ClientMsg::ListPins { target }).await? { + ServerMsg::Pins { pins, .. } => Ok(pins), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn react(&self, message_id: i64, emoji: String) -> Result<(), ClientError> { + self.ok(ClientMsg::React { message_id, emoji }).await + } + + pub async fn unreact(&self, message_id: i64, emoji: String) -> Result<(), ClientError> { + self.ok(ClientMsg::Unreact { message_id, emoji }).await + } + + pub async fn reactors( + &self, + message_id: i64, + emoji: String, + ) -> Result, ClientError> { + match self.request(ClientMsg::Reactors { message_id, emoji }).await? { + ServerMsg::Reactors { users, .. } => Ok(users), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn create_topic( + &self, + target: ChatTarget, + title: String, + message_id: Option, + ) -> Result { + self.topic(ClientMsg::CreateTopic { target, title, message_id }).await + } + + pub async fn update_topic( + &self, + topic_id: i64, + title: Option, + archived: Option, + ) -> Result { + self.topic(ClientMsg::UpdateTopic { topic_id, title, archived }).await + } + + async fn topic(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Topic { topic } => Ok(topic), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn topics( + &self, + target: ChatTarget, + include_archived: bool, + ) -> Result, ClientError> { + match self.request(ClientMsg::ListTopics { target, include_archived }).await? { + ServerMsg::Topics { topics, .. } => Ok(topics), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn create_event(&self, event: EventSpec) -> Result { + self.event_reply(ClientMsg::CreateEvent { event }).await + } + + pub async fn update_event(&self, id: i64, event: EventSpec) -> Result { + self.event_reply(ClientMsg::UpdateEvent { id, event }).await + } + + pub async fn delete_event(&self, id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::DeleteEvent { id }).await + } + + /// One event with its attendees. + pub async fn event(&self, id: i64) -> Result { + self.event_reply(ClientMsg::GetEvent { id }).await + } + + pub async fn events(&self, query: EventQuery) -> Result, ClientError> { + match self.request(ClientMsg::ListEvents(query)).await? { + ServerMsg::Events { events } => Ok(events), + other => Err(ClientError::unexpected(other)), + } + } + + /// Answer an event; `None` withdraws the answer. + pub async fn rsvp( + &self, + event_id: i64, + status: Option, + ) -> Result { + self.event_reply(ClientMsg::Rsvp { event_id, status }).await + } + + async fn event_reply(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Event { event } => Ok(event), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn subscribe_events(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::SubscribeEvents).await + } + + pub async fn unsubscribe_events(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeEvents).await + } + + pub async fn register_stream(&self, stream: StreamSpec) -> Result { + self.stream_reply(ClientMsg::RegisterStream(stream)).await + } + + pub async fn update_stream( + &self, + stream_id: String, + title: Option, + viewers: Option, + ) -> Result { + self.stream_reply(ClientMsg::UpdateStream { stream_id, title, viewers }).await + } + + async fn stream_reply(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Stream { stream } => Ok(stream), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn unregister_stream(&self, stream_id: String) -> Result<(), ClientError> { + self.ok(ClientMsg::UnregisterStream { stream_id }).await + } + + pub async fn streams(&self) -> Result, ClientError> { + self.streams_reply(ClientMsg::ListStreams).await + } + + /// Returns the directory; changes follow as pushes. + pub async fn subscribe_streams(&self) -> Result, ClientError> { + self.streams_reply(ClientMsg::SubscribeStreams).await + } + + async fn streams_reply(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::Streams { streams } => Ok(streams), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn unsubscribe_streams(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeStreams).await + } + + /// Newest first; returns the entries and whether older ones exist. + pub async fn activity( + &self, + before: Option, + limit: Option, + ) -> Result<(Vec, bool), ClientError> { + match self.request(ClientMsg::ListActivity { before, limit }).await? { + ServerMsg::Activity { entries, has_more } => Ok((entries, has_more)), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn subscribe_activity(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::SubscribeActivity).await + } + + pub async fn unsubscribe_activity(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeActivity).await + } + + pub async fn config_list(&self) -> Result, ClientError> { + self.config_entries(ClientMsg::ConfigList).await + } + + /// Read the gateway's file again; returns the resulting configuration. + pub async fn config_reload(&self) -> Result, ClientError> { + self.config_entries(ClientMsg::ConfigReload).await + } + + async fn config_entries(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::Config { entries } => Ok(entries), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn config_get(&self, key: String) -> Result { + self.config_value(ClientMsg::ConfigGet { key }).await + } + + pub async fn config_set( + &self, + key: String, + value: serde_json::Value, + ) -> Result { + self.config_value(ClientMsg::ConfigSet { key, value }).await + } + + pub async fn config_reset(&self, key: String) -> Result { + self.config_value(ClientMsg::ConfigReset { key }).await + } + + async fn config_value(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::ConfigValue { entry } => Ok(entry), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn perm_list(&self) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermList).await + } + + pub async fn perm_set( + &self, + action: Action, + rule: PermRule, + ) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermSet { action, rule }).await + } + + pub async fn perm_reset(&self, action: Action) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermReset { action }).await + } + + async fn perm_rules(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::PermRules { rules } => Ok(rules), + other => Err(ClientError::unexpected(other)), + } + } +} + +/// The connection task: frames out, answers to their requests, pushes to +/// the receiver. +async fn run( + mut ws: S, + mut out: mpsc::UnboundedReceiver, + pushes: mpsc::UnboundedSender, + capabilities: Arc>>, +) where + S: Stream> + + Sink + + Unpin + + Send + + 'static, +{ + let mut pending: HashMap> = HashMap::new(); + let reason = loop { + tokio::select! { + frame = recv(&mut ws) => { + let env = match frame { + Ok(env) => env, + // A push of a type this version does not know. + Err(ClientError::Json(_)) => continue, + Err(ClientError::Closed) => break None, + Err(e) => break Some(e.to_string()), + }; + if let ServerMsg::Capabilities { capabilities: caps } = &env.msg { + *capabilities.write().unwrap() = caps.clone(); + } + match env.id.and_then(|id| pending.remove(&id)) { + Some(waiter) => { + let _ = waiter.send(env.msg); + } + None => { + let _ = pushes.send(env.msg.into()); + } + } + } + msg = out.recv() => { + let Some(Outgoing { id, msg, reply }) = msg else { + let _ = ws.close().await; + break None; + }; + if let Some(reply) = reply { + pending.insert(id, reply); + } + if let Err(e) = send_frame(&mut ws, id, msg).await { + break Some(e.to_string()); + } + } + } + }; + let _ = pushes.send(Push::Disconnected(reason)); +} diff --git a/crates/voelin-gateway-proto/src/lib.rs b/crates/voelin-gateway-proto/src/lib.rs index 3062125..6e5cf0c 100644 --- a/crates/voelin-gateway-proto/src/lib.rs +++ b/crates/voelin-gateway-proto/src/lib.rs @@ -3,22 +3,34 @@ //! //! Transport: WebSocket, subprotocol [`SUBPROTOCOL`], one JSON [`Envelope`] //! per text frame. Within version 1 changes are additive only: new message -//! types and optional fields. Unknown fields must be ignored. +//! types and optional fields. Unknown fields must be ignored. The gateway +//! answers message types it does not know with [`ErrorCode::UnknownType`] +//! and keeps the connection; it only pushes newer message types to clients +//! that asked for them. //! //! Authentication proves ownership of a TeamSpeak identity: the gateway sends //! a nonce in [`ServerMsg::Hello`], the client answers with //! [`ClientMsg::Auth`], an ECDSA P-256 signature over [`challenge`] made with //! the identity's private key. The unique id is derived from the public key, //! exactly as the TeamSpeak server does. +//! +//! Besides presence and chat, gateways can offer pins, reactions, topics, +//! scheduled events, a directory of running streams, an activity feed and +//! runtime administration; [`ServerMsg::Hello`] lists what is enabled +//! ([`feature`]). The `client` feature adds a typed client ([`client`]). mod auth; +#[cfg(feature = "client")] +pub mod client; mod messages; +mod types; pub use auth::{ AuthError, MAX_CLOCK_SKEW_SECS, UniqueIds, challenge, identity_level, sign_challenge, verify_auth, }; pub use messages::*; +pub use types::*; /// WebSocket subprotocol. pub const SUBPROTOCOL: &str = "tsgw.v1+json"; diff --git a/crates/voelin-gateway-proto/src/messages.rs b/crates/voelin-gateway-proto/src/messages.rs index 9b8c8f0..2f47a4a 100644 --- a/crates/voelin-gateway-proto/src/messages.rs +++ b/crates/voelin-gateway-proto/src/messages.rs @@ -1,7 +1,14 @@ //! Messages in both directions. +//! +//! The first block of each enum is the original protocol; everything after +//! it was added later. A client only receives the newer pushes after it sent +//! [`ClientMsg::Enable`] (chat extensions) or the matching subscribe request, +//! so older clients never see a message type they do not know. use serde::{Deserialize, Serialize}; -use voelin_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; + +use crate::types::*; /// Every frame: `{"v":1,"id":7,"type":"send_chat","data":{...}}`. /// @@ -62,6 +69,7 @@ pub enum ClientMsg { text: String, }, /// Up to `limit` messages before message id `before` (latest when absent). + /// [`ClientMsg::QueryHistory`] has more ways to page. History { target: ChatTarget, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -69,6 +77,173 @@ pub enum ClientMsg { limit: u32, }, Ping, + + // Extensions. Gateways without them answer `error` with `unknown_type`; + // the capabilities in `hello` and `auth_ok` say what is there. + /// Receive the extension pushes for open chats: [`ServerMsg::Message`] + /// instead of [`ServerMsg::ChatEvent`], and pins, reactions and topics of + /// the listed features (empty: all). Answer: [`ServerMsg::Enabled`]. + Enable { + #[serde(default)] + features: Vec, + }, + /// What this user may do, server-wide or in a channel. Answer: + /// [`ServerMsg::Permissions`]. + Permissions { + #[serde(default, skip_serializing_if = "Option::is_none")] + channel: Option, + }, + /// Page through stored messages. Answer: [`ServerMsg::HistoryPage`]. + QueryHistory(HistoryQuery), + /// Messages of a chat that are new or changed (pins, reactions, topic) + /// since revision `since_rev`, by revision. Answer: [`ServerMsg::SyncPage`]. + Sync { + target: ChatTarget, + #[serde(default)] + since_rev: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, + }, + /// Like [`ClientMsg::SendChat`], optionally into a topic; answered with + /// the stored message ([`ServerMsg::Posted`]). + Post { + target: ChatTarget, + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + topic: Option, + }, + Pin { + message_id: i64, + }, + Unpin { + message_id: i64, + }, + /// Answer: [`ServerMsg::Pins`]. + ListPins { + target: ChatTarget, + }, + React { + message_id: i64, + emoji: String, + }, + Unreact { + message_id: i64, + emoji: String, + }, + /// Who reacted with `emoji`. Answer: [`ServerMsg::Reactors`]. + Reactors { + message_id: i64, + emoji: String, + }, + /// Start a topic, from a message or standalone. Answer: [`ServerMsg::Topic`]. + CreateTopic { + target: ChatTarget, + title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + message_id: Option, + }, + /// Rename or (un)archive a topic. Answer: [`ServerMsg::Topic`]. + UpdateTopic { + topic_id: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + archived: Option, + }, + /// Answer: [`ServerMsg::Topics`], most recently active first. + ListTopics { + target: ChatTarget, + #[serde(default)] + include_archived: bool, + }, + /// Answer: [`ServerMsg::Event`]. + CreateEvent { + event: EventSpec, + }, + /// Answer: [`ServerMsg::Event`]. + UpdateEvent { + id: i64, + event: EventSpec, + }, + DeleteEvent { + id: i64, + }, + /// One event with its attendees. Answer: [`ServerMsg::Event`]. + GetEvent { + id: i64, + }, + /// Answer: [`ServerMsg::Events`], by start time. + ListEvents(EventQuery), + /// Answer an invitation; `None` withdraws the answer. Answer: [`ServerMsg::Event`]. + Rsvp { + event_id: i64, + #[serde(default)] + status: Option, + }, + /// Receive [`ServerMsg::EventUpdated`], [`ServerMsg::EventDeleted`] and + /// [`ServerMsg::EventReminder`]. + SubscribeEvents, + UnsubscribeEvents, + /// Add the user's running stream to the directory. Answer: [`ServerMsg::Stream`]. + RegisterStream(StreamSpec), + /// Answer: [`ServerMsg::Stream`]. + UpdateStream { + stream_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + viewers: Option, + }, + UnregisterStream { + stream_id: String, + }, + /// Answer: [`ServerMsg::Streams`]. + ListStreams, + /// Answered with [`ServerMsg::Streams`], then [`ServerMsg::StreamStarted`], + /// [`ServerMsg::StreamUpdated`] and [`ServerMsg::StreamEnded`] as they happen. + SubscribeStreams, + UnsubscribeStreams, + /// Newest first, entries with an id below `before`. Answer: [`ServerMsg::Activity`]. + ListActivity { + #[serde(default, skip_serializing_if = "Option::is_none")] + before: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, + }, + /// Receive [`ServerMsg::ActivityAdded`]. + SubscribeActivity, + UnsubscribeActivity, + /// Administration (needs the `admin` capability). Answer: [`ServerMsg::Config`]. + ConfigList, + /// Answer: [`ServerMsg::ConfigValue`]. + ConfigGet { + key: String, + }, + /// Store a value in the gateway's database; it wins over the command + /// line, environment and file and applies at once. Answer: + /// [`ServerMsg::ConfigValue`]. + ConfigSet { + key: String, + value: serde_json::Value, + }, + /// Drop the stored value (back to command line, environment, file or + /// default). Answer: [`ServerMsg::ConfigValue`]. + ConfigReset { + key: String, + }, + /// Read the file again (like `SIGHUP`). Answer: [`ServerMsg::Config`]. + ConfigReload, + /// Answer: [`ServerMsg::PermRules`]. + PermList, + /// Set the rule of an action. Answer: [`ServerMsg::PermRules`]. + PermSet { + action: Action, + rule: PermRule, + }, + /// Back to the file's rule or the built-in default. Answer: [`ServerMsg::PermRules`]. + PermReset { + action: Action, + }, } /// Gateway to client. @@ -81,7 +256,7 @@ pub enum ServerMsg { server_uid: String, server_name: String, nonce: String, - /// Optional features, e.g. `history`. + /// Enabled features, see [`crate::feature`]. #[serde(default)] capabilities: Vec, }, @@ -91,6 +266,10 @@ pub enum ServerMsg { token: String, /// Unix time in seconds. token_expires: i64, + /// Features for this user: those of `hello`, plus `admin` if the user + /// may administer the gateway. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + capabilities: Vec, }, /// Presence restricted to what this user may see. `seq` restarts at 0 with /// each snapshot and increases by one per delta. @@ -117,12 +296,171 @@ pub enum ServerMsg { message: String, }, Pong, + + // Extensions: answers to the new requests, and pushes (without `id`) for + // sessions that asked for them. + Enabled { + features: Vec, + }, + /// Push: the features available to this user changed. + Capabilities { + capabilities: Vec, + }, + Permissions { + #[serde(default, skip_serializing_if = "Option::is_none")] + channel: Option, + actions: Vec, + }, + HistoryPage(HistoryPage), + SyncPage { + target: ChatTarget, + /// By revision. + messages: Vec, + /// Pass as `since_rev` next time. + rev: i64, + #[serde(default)] + has_more: bool, + }, + /// Push: a message in an open chat, for sessions that sent [`ClientMsg::Enable`]. + Message { + entry: HistoryEntry, + }, + Posted { + entry: HistoryEntry, + }, + /// Push to sessions with the chat open. + Pinned { + target: ChatTarget, + pin: PinInfo, + }, + /// Push to sessions with the chat open. + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + Pins { + target: ChatTarget, + pins: Vec, + }, + /// Push to sessions with the chat open: `user` added or removed `emoji`; + /// `count` is the new total for that emoji. + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + Reactors { + message_id: i64, + emoji: String, + users: Vec, + }, + Topic { + topic: TopicInfo, + }, + /// Push to sessions with the chat open: created, renamed, archived or + /// new activity. + TopicUpdated { + topic: TopicInfo, + }, + Topics { + target: ChatTarget, + topics: Vec, + }, + Event { + event: EventInfo, + }, + Events { + events: Vec, + }, + /// Push: created or changed (including RSVP counts and going live). + EventUpdated { + event: EventInfo, + }, + /// Push. + EventDeleted { + id: i64, + }, + /// Push at the configured times before an event starts (0: it starts). + EventReminder { + event: EventInfo, + starts_in_ms: i64, + }, + Stream { + stream: StreamEntry, + }, + Streams { + streams: Vec, + }, + /// Push. + StreamStarted { + stream: StreamEntry, + }, + /// Push. + StreamUpdated { + stream: StreamEntry, + }, + /// Push. + StreamEnded { + id: String, + reason: String, + }, + /// Newest first. + Activity { + entries: Vec, + #[serde(default)] + has_more: bool, + }, + /// Push. + ActivityAdded { + entry: ActivityEntry, + }, + Config { + entries: Vec, + }, + ConfigValue { + entry: ConfigEntry, + }, + PermRules { + rules: Vec, + }, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +/// A stored message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HistoryEntry { + /// Stable gateway id; orders the messages of a chat. pub id: i64, pub message: ChatMessage, + /// The topic the message was posted in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic_id: Option, + /// In order of the first reaction. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub reactions: Vec, + #[serde(default, skip_serializing_if = "is_false")] + pub pinned: bool, + /// Revision of the last change (post, pin, reaction, topic), for + /// [`ClientMsg::Sync`]. + #[serde(default, skip_serializing_if = "is_zero")] + pub rev: i64, +} + +impl HistoryEntry { + pub fn new(id: i64, message: ChatMessage) -> Self { + Self { id, message, topic_id: None, reactions: Vec::new(), pinned: false, rev: 0 } + } +} + +fn is_false(b: &bool) -> bool { + !*b +} + +fn is_zero(n: &i64) -> bool { + *n == 0 } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -145,41 +483,20 @@ pub enum ErrorCode { /// Temporary problem talking to the TeamSpeak server. Unavailable, Internal, + /// The message type is not known to this gateway. + UnknownType, + /// The message, topic, event, stream or key does not exist (any more). + NotFound, + /// A quota set by the gateway's admin is reached. + QuotaExceeded, + /// Too many requests; try again later. + RateLimited, + /// The feature is turned off on this gateway. + FeatureDisabled, + /// Sent by a newer gateway. + #[serde(other)] + Unknown, } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn envelope_json_shape() { - let env = Envelope::with_id( - 7, - ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() }, - ); - let json = serde_json::to_string(&env).unwrap(); - assert_eq!( - json, - r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"# - ); - let back: Envelope = serde_json::from_str(&json).unwrap(); - assert_eq!(back, env); - - let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap(); - assert_eq!(ping, r#"{"v":1,"type":"ping"}"#); - assert_eq!( - serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(), - r#"{"v":1,"type":"ok"}"# - ); - } - - #[test] - fn ignores_unknown_fields() { - let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#; - let env: Envelope = serde_json::from_str(json).unwrap(); - assert_eq!( - env.msg, - ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 } - ); - } -} +mod tests; diff --git a/crates/voelin-gateway-proto/src/messages/tests.rs b/crates/voelin-gateway-proto/src/messages/tests.rs new file mode 100644 index 0000000..abcb46e --- /dev/null +++ b/crates/voelin-gateway-proto/src/messages/tests.rs @@ -0,0 +1,435 @@ +use serde_json::json; +use voelin_model::ClientInfo; + +use super::*; + +fn chat(text: &str) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(5), + author_name: "Alice".into(), + author_uid: Some("uid-a".into()), + author_id: None, + text: text.into(), + ts_ms: 1_700_000_000_123, + via_relay: true, + } +} + +fn entry() -> HistoryEntry { + HistoryEntry { + id: 42, + message: chat("hi"), + topic_id: Some(3), + reactions: vec![ReactionCount { emoji: "👍".into(), count: 2, me: true }], + pinned: true, + rev: 1_700_000_000_123_001, + } +} + +fn user() -> UserRef { + UserRef { uid: "uid-a".into(), name: "Alice".into() } +} + +fn topic() -> TopicInfo { + TopicInfo { + id: 3, + target: ChatTarget::Channel(5), + title: "Raid".into(), + creator: user(), + created_ms: 1, + root_message_id: Some(42), + last_activity_ms: 2, + message_count: 7, + archived: false, + } +} + +fn event() -> EventInfo { + EventInfo { + id: 9, + spec: EventSpec { + title: "Movie night".into(), + description: "bring snacks".into(), + start_ms: 1000, + end_ms: Some(2000), + channel: Some(5), + kind: EventKind::Stream, + stream_title: Some("Film".into()), + stream_game: None, + host_uid: None, + }, + creator: user(), + created_ms: 1, + updated_ms: 2, + going: 3, + maybe: 1, + not_going: 0, + my_rsvp: Some(RsvpStatus::Going), + attendees: vec![Attendee { user: user(), status: RsvpStatus::Going, ts_ms: 5 }], + live_stream: Some("s-1".into()), + } +} + +fn stream() -> StreamEntry { + StreamEntry { + id: "s-1".into(), + stream_id: Some("s-1".into()), + streamer: user(), + client_id: Some(7), + channel: Some(5), + title: "Coding".into(), + kind: "screen".into(), + started_ms: 10, + viewers: Some(2), + source: StreamSource::Registered, + event_id: Some(9), + } +} + +fn activity() -> ActivityEntry { + ActivityEntry { + id: 1, + ts_ms: 10, + kind: activity_kind::STREAM_STARTED.into(), + actor: Some(user()), + channel: Some(5), + ref_id: Some("s-1".into()), + text: "Alice started streaming".into(), + data: json!({"title": "Coding"}), + } +} + +fn config_entry() -> ConfigEntry { + ConfigEntry { + key: "history.retention_days".into(), + value: json!(0), + source: ConfigSource::Db, + default: json!(0), + value_type: "int".into(), + description: "days".into(), + bootstrap: false, + } +} + +fn rule() -> PermRule { + PermRule { everyone: false, server_groups: vec![6], channel_groups: vec![5] } +} + +fn roundtrip(msg: M) +where + M: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug + Clone, +{ + let env = Envelope::with_id(3, msg); + let json = serde_json::to_string(&env).unwrap(); + let back: Envelope = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{json}: {e}")); + assert_eq!(back, env, "{json}"); +} + +#[test] +fn envelope_json_shape() { + let env = Envelope::with_id( + 7, + ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() }, + ); + let json = serde_json::to_string(&env).unwrap(); + assert_eq!( + json, + r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"# + ); + let back: Envelope = serde_json::from_str(&json).unwrap(); + assert_eq!(back, env); + + let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap(); + assert_eq!(ping, r#"{"v":1,"type":"ping"}"#); + assert_eq!( + serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(), + r#"{"v":1,"type":"ok"}"# + ); +} + +#[test] +fn ignores_unknown_fields() { + let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#; + let env: Envelope = serde_json::from_str(json).unwrap(); + assert_eq!(env.msg, ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 }); +} + +#[test] +fn every_client_message_roundtrips() { + let target = ChatTarget::Channel(5); + let msgs = vec![ + ClientMsg::Auth { + omega: "o".into(), + key_offset: 1, + ts: 2, + signature: "s".into(), + nickname: "n".into(), + }, + ClientMsg::Resume { token: "t".into(), nickname: "n".into() }, + ClientMsg::SubscribePresence, + ClientMsg::UnsubscribePresence, + ClientMsg::OpenChat { target: target.clone() }, + ClientMsg::CloseChat { target: ChatTarget::Server }, + ClientMsg::SendChat { target: target.clone(), text: "x".into() }, + ClientMsg::History { target: target.clone(), before: Some(3), limit: 10 }, + ClientMsg::Ping, + ClientMsg::Enable { features: vec![feature::PINS.into()] }, + ClientMsg::Permissions { channel: Some(5) }, + ClientMsg::QueryHistory(HistoryQuery { + target: target.clone(), + before: Some(100), + after: Some(10), + before_ms: Some(5), + after_ms: Some(1), + limit: Some(500), + topic: Some(3), + exclude_topics: true, + }), + ClientMsg::QueryHistory(HistoryQuery::latest(ChatTarget::Server, None)), + ClientMsg::Sync { target: target.clone(), since_rev: 77, limit: None }, + ClientMsg::Post { target: target.clone(), text: "t".into(), topic: Some(3) }, + ClientMsg::Pin { message_id: 1 }, + ClientMsg::Unpin { message_id: 1 }, + ClientMsg::ListPins { target: target.clone() }, + ClientMsg::React { message_id: 1, emoji: "🏳️‍🌈".into() }, + ClientMsg::Unreact { message_id: 1, emoji: "👍🏽".into() }, + ClientMsg::Reactors { message_id: 1, emoji: "👍".into() }, + ClientMsg::CreateTopic { target: target.clone(), title: "t".into(), message_id: Some(1) }, + ClientMsg::UpdateTopic { topic_id: 3, title: None, archived: Some(true) }, + ClientMsg::ListTopics { target: target.clone(), include_archived: true }, + ClientMsg::CreateEvent { event: event().spec }, + ClientMsg::UpdateEvent { id: 9, event: EventSpec::default() }, + ClientMsg::DeleteEvent { id: 9 }, + ClientMsg::GetEvent { id: 9 }, + ClientMsg::ListEvents(EventQuery { + from_ms: Some(1), + to_ms: None, + channel: Some(5), + limit: None, + }), + ClientMsg::Rsvp { event_id: 9, status: Some(RsvpStatus::Maybe) }, + ClientMsg::Rsvp { event_id: 9, status: None }, + ClientMsg::SubscribeEvents, + ClientMsg::UnsubscribeEvents, + ClientMsg::RegisterStream(StreamSpec { + stream_id: "s-1".into(), + client_id: Some(7), + channel: Some(5), + title: "t".into(), + kind: "screen".into(), + viewers: None, + }), + ClientMsg::UpdateStream { + stream_id: "s-1".into(), + title: Some("u".into()), + viewers: Some(4), + }, + ClientMsg::UnregisterStream { stream_id: "s-1".into() }, + ClientMsg::ListStreams, + ClientMsg::SubscribeStreams, + ClientMsg::UnsubscribeStreams, + ClientMsg::ListActivity { before: Some(10), limit: Some(20) }, + ClientMsg::SubscribeActivity, + ClientMsg::UnsubscribeActivity, + ClientMsg::ConfigList, + ClientMsg::ConfigGet { key: "a.b".into() }, + ClientMsg::ConfigSet { key: "a.b".into(), value: json!([1, 2]) }, + ClientMsg::ConfigReset { key: "a.b".into() }, + ClientMsg::ConfigReload, + ClientMsg::PermList, + ClientMsg::PermSet { action: Action::Pin, rule: rule() }, + ClientMsg::PermReset { action: Action::Admin }, + ]; + for msg in msgs { + roundtrip(msg); + } +} + +#[test] +fn every_server_message_roundtrips() { + let target = ChatTarget::Channel(5); + let msgs = vec![ + ServerMsg::Hello { + gateway_id: "g".into(), + server_uid: "s".into(), + server_name: "n".into(), + nonce: "x".into(), + capabilities: vec![feature::PINS.into()], + }, + ServerMsg::AuthOk { + uid: "u".into(), + token: "t".into(), + token_expires: 5, + capabilities: vec![feature::ADMIN.into()], + }, + ServerMsg::PresenceSnapshot { + seq: 0, + snapshot: PresenceSnapshot { + server_name: "s".into(), + channels: vec![], + clients: vec![ClientInfo { id: 1, nickname: "a".into(), ..Default::default() }], + }, + }, + ServerMsg::PresenceDelta { seq: 1, delta: PresenceDelta::ClientLeft { id: 1 } }, + ServerMsg::ChatEvent { id: 1, message: chat("x") }, + ServerMsg::History { messages: vec![entry(), HistoryEntry::new(1, chat("y"))] }, + ServerMsg::Ok, + ServerMsg::Error { code: ErrorCode::QuotaExceeded, message: "m".into() }, + ServerMsg::Pong, + ServerMsg::Enabled { features: vec!["pins".into()] }, + ServerMsg::Capabilities { capabilities: vec!["events".into()] }, + ServerMsg::Permissions { channel: None, actions: vec![Action::React, Action::Moderate] }, + ServerMsg::HistoryPage(HistoryPage { + target: target.clone(), + topic: Some(3), + messages: vec![entry()], + has_more: true, + }), + ServerMsg::SyncPage { + target: target.clone(), + messages: vec![entry()], + rev: 9, + has_more: false, + }, + ServerMsg::Message { entry: entry() }, + ServerMsg::Posted { entry: entry() }, + ServerMsg::Pinned { + target: target.clone(), + pin: PinInfo { entry: entry(), by: user(), ts_ms: 4 }, + }, + ServerMsg::Unpinned { target: target.clone(), message_id: 42, by: user() }, + ServerMsg::Pins { + target: target.clone(), + pins: vec![PinInfo { entry: entry(), by: user(), ts_ms: 4 }], + }, + ServerMsg::Reaction { + target: target.clone(), + message_id: 42, + emoji: "🎉".into(), + user: user(), + added: true, + count: 3, + }, + ServerMsg::Reactors { message_id: 42, emoji: "🎉".into(), users: vec![user()] }, + ServerMsg::Topic { topic: topic() }, + ServerMsg::TopicUpdated { topic: topic() }, + ServerMsg::Topics { target: target.clone(), topics: vec![topic()] }, + ServerMsg::Event { event: event() }, + ServerMsg::Events { events: vec![event()] }, + ServerMsg::EventUpdated { event: event() }, + ServerMsg::EventDeleted { id: 9 }, + ServerMsg::EventReminder { event: event(), starts_in_ms: 900_000 }, + ServerMsg::Stream { stream: stream() }, + ServerMsg::Streams { streams: vec![stream()] }, + ServerMsg::StreamStarted { stream: stream() }, + ServerMsg::StreamUpdated { stream: stream() }, + ServerMsg::StreamEnded { id: "s-1".into(), reason: "left".into() }, + ServerMsg::Activity { entries: vec![activity()], has_more: true }, + ServerMsg::ActivityAdded { entry: activity() }, + ServerMsg::Config { entries: vec![config_entry()] }, + ServerMsg::ConfigValue { entry: config_entry() }, + ServerMsg::PermRules { + rules: vec![ + PermRuleInfo { + action: Action::Pin, + rule: Some(rule()), + source: ConfigSource::Db, + default: "moderators".into(), + }, + PermRuleInfo { + action: Action::React, + rule: None, + source: ConfigSource::Default, + default: "everyone".into(), + }, + ], + }, + ]; + for msg in msgs { + roundtrip(msg); + } +} + +#[test] +fn new_json_shapes() { + let json = serde_json::to_value(Envelope::with_id( + 4, + ClientMsg::QueryHistory(HistoryQuery { + after: Some(10), + limit: Some(2), + ..HistoryQuery::latest(ChatTarget::Channel(1), None) + }), + )) + .unwrap(); + assert_eq!( + json, + json!({"v":1,"id":4,"type":"query_history","data":{"target":{"kind":"channel","id":1},"after":10,"limit":2}}) + ); + // The event spec is flattened into the event. + let json = serde_json::to_value(event()).unwrap(); + assert_eq!(json["title"], "Movie night"); + assert_eq!(json["kind"], "stream"); + assert_eq!(json["my_rsvp"], "going"); + let json = + serde_json::to_value(ClientMsg::PermSet { action: Action::CreateTopic, rule: rule() }) + .unwrap(); + assert_eq!( + json, + json!({"type":"perm_set","data":{"action":"create_topic","rule":{"server_groups":[6],"channel_groups":[5]}}}) + ); + // Plain entries stay as small as before. + let json = serde_json::to_value(HistoryEntry::new(1, chat("x"))).unwrap(); + assert_eq!(json.as_object().unwrap().keys().collect::>(), ["id", "message"]); +} + +#[test] +fn old_clients_read_extended_replies() { + // What a client built against the first protocol version sees. + #[derive(Deserialize)] + #[serde(tag = "type", content = "data", rename_all = "snake_case")] + enum OldServerMsg { + AuthOk { uid: String }, + History { messages: Vec }, + } + #[derive(Deserialize)] + struct OldEntry { + id: i64, + } + let auth = serde_json::to_string(&ServerMsg::AuthOk { + uid: "u".into(), + token: "t".into(), + token_expires: 1, + capabilities: vec!["admin".into()], + }) + .unwrap(); + assert!( + matches!(serde_json::from_str(&auth).unwrap(), OldServerMsg::AuthOk { uid } if uid == "u") + ); + let history = serde_json::to_string(&ServerMsg::History { messages: vec![entry()] }).unwrap(); + match serde_json::from_str(&history).unwrap() { + OldServerMsg::History { messages } => assert_eq!(messages[0].id, 42), + _ => panic!(), + } +} + +#[test] +fn newer_enum_values_do_not_break_parsing() { + let msg: ServerMsg = + serde_json::from_str(r#"{"type":"error","data":{"code":"from_the_future","message":"m"}}"#) + .unwrap(); + assert_eq!(msg, ServerMsg::Error { code: ErrorCode::Unknown, message: "m".into() }); + let spec: EventSpec = + serde_json::from_str(r#"{"title":"t","start_ms":1,"kind":"tournament"}"#).unwrap(); + assert_eq!(spec.kind, EventKind::Unknown); + let a: Vec = serde_json::from_str(r#"["pin","launch_rockets"]"#).unwrap(); + assert_eq!(a, [Action::Pin, Action::Unknown]); + assert_eq!(Action::parse("create_event"), Some(Action::CreateEvent)); + assert_eq!(Action::parse("unknown"), None); + for a in Action::ALL { + assert_eq!(serde_json::to_value(a).unwrap(), a.as_str()); + } + for s in [RsvpStatus::Going, RsvpStatus::Maybe, RsvpStatus::NotGoing] { + assert_eq!(RsvpStatus::parse(s.as_str()), s); + assert_eq!(serde_json::to_value(s).unwrap(), s.as_str()); + } +} diff --git a/crates/voelin-gateway-proto/src/types.rs b/crates/voelin-gateway-proto/src/types.rs new file mode 100644 index 0000000..0c89332 --- /dev/null +++ b/crates/voelin-gateway-proto/src/types.rs @@ -0,0 +1,466 @@ +//! Data carried by the extension messages: pins, reactions, topics, events, +//! the stream directory, the activity feed and administration. +//! +//! Enums that a newer gateway may extend have an `Unknown` fallback, so an +//! older client can still read the message. Kinds that are expected to grow +//! (activity) are plain strings. + +use serde::{Deserialize, Serialize}; +use voelin_model::{ChannelId, ChatTarget, ClientId}; + +use crate::messages::HistoryEntry; + +/// Feature names in [`crate::ServerMsg::Hello`] and [`crate::ServerMsg::AuthOk`]. +pub mod feature { + /// Presence stream ([`crate::ClientMsg::SubscribePresence`]). + pub const PRESENCE: &str = "presence"; + /// Channel and server chat through relays. + pub const RELAY: &str = "relay"; + /// Stored chat history, [`crate::ClientMsg::QueryHistory`] and [`crate::ClientMsg::Sync`]. + pub const HISTORY: &str = "history"; + pub const PINS: &str = "pins"; + pub const REACTIONS: &str = "reactions"; + pub const TOPICS: &str = "topics"; + pub const EVENTS: &str = "events"; + pub const STREAMS: &str = "streams"; + pub const ACTIVITY: &str = "activity"; + /// Only in [`crate::ServerMsg::AuthOk`]: the user may change the gateway's + /// configuration and permission rules. + pub const ADMIN: &str = "admin"; +} + +/// Activity kinds in [`ActivityEntry::kind`]. Clients show unknown kinds by +/// their [`ActivityEntry::text`]. +pub mod activity_kind { + pub const STREAM_STARTED: &str = "stream_started"; + pub const STREAM_ENDED: &str = "stream_ended"; + pub const EVENT_CREATED: &str = "event_created"; + pub const EVENT_CANCELLED: &str = "event_cancelled"; + pub const EVENT_STARTING: &str = "event_starting"; + pub const TOPIC_CREATED: &str = "topic_created"; + pub const PINNED: &str = "pinned"; +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// A user as the gateway knows them: unique id and last nickname. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserRef { + pub uid: String, + pub name: String, +} + +/// One emoji on a message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReactionCount { + /// Any Unicode string, usually one emoji. + pub emoji: String, + pub count: u32, + /// The requesting user reacted with this emoji. + #[serde(default, skip_serializing_if = "is_false")] + pub me: bool, +} + +/// Parameters of [`crate::ClientMsg::QueryHistory`]. +/// +/// Without cursors the latest `limit` messages are returned. With `before` +/// (or `before_ms`) only, the `limit` messages right before it. With `after` +/// (or `after_ms`), the `limit` messages right after it, oldest first, up to +/// `before` if given. Pages are always ordered oldest first. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryQuery { + pub target: ChatTarget, + /// Messages with a smaller id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before: Option, + /// Messages with a larger id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after: Option, + /// Messages sent before this time (Unix milliseconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before_ms: Option, + /// Messages sent after this time (Unix milliseconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after_ms: Option, + /// Page size. Absent: everything in range, unless the gateway's admin set + /// a maximum page size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Only the messages of this topic. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic: Option, + /// Only messages outside topics. + #[serde(default, skip_serializing_if = "is_false")] + pub exclude_topics: bool, +} + +impl HistoryQuery { + /// The latest messages of `target`. + pub fn latest(target: ChatTarget, limit: Option) -> Self { + Self { + target, + before: None, + after: None, + before_ms: None, + after_ms: None, + limit, + topic: None, + exclude_topics: false, + } + } +} + +/// Answer to [`crate::ClientMsg::QueryHistory`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryPage { + pub target: ChatTarget, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic: Option, + /// Oldest first. + pub messages: Vec, + /// More messages exist beyond this page in the paging direction (older + /// without `after`, newer with it). + #[serde(default)] + pub has_more: bool, +} + +/// A pinned message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PinInfo { + pub entry: HistoryEntry, + pub by: UserRef, + pub ts_ms: i64, +} + +/// A topic (thread) in a chat. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicInfo { + pub id: i64, + pub target: ChatTarget, + pub title: String, + pub creator: UserRef, + pub created_ms: i64, + /// The message the topic was started from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_message_id: Option, + pub last_activity_ms: i64, + pub message_count: u64, + #[serde(default, skip_serializing_if = "is_false")] + pub archived: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EventKind { + #[default] + General, + /// A scheduled stream; linked to the stream directory once live. + Stream, + /// Sent by a newer gateway. + #[serde(other)] + Unknown, +} + +/// What the creator of an event sets. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventSpec { + pub title: String, + #[serde(default)] + pub description: String, + /// Unix milliseconds. + pub start_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_ms: Option, + /// Server-wide when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub kind: EventKind, + /// For streams: the expected stream title. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_title: Option, + /// For streams: the game or subject. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_game: Option, + /// Whose stream links to the event; the creator when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_uid: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RsvpStatus { + Going, + Maybe, + NotGoing, + #[serde(other)] + Unknown, +} + +impl RsvpStatus { + pub fn as_str(self) -> &'static str { + match self { + RsvpStatus::Going => "going", + RsvpStatus::Maybe => "maybe", + RsvpStatus::NotGoing => "not_going", + RsvpStatus::Unknown => "unknown", + } + } + + pub fn parse(s: &str) -> Self { + match s { + "going" => RsvpStatus::Going, + "maybe" => RsvpStatus::Maybe, + "not_going" => RsvpStatus::NotGoing, + _ => RsvpStatus::Unknown, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attendee { + pub user: UserRef, + pub status: RsvpStatus, + pub ts_ms: i64, +} + +/// A scheduled event. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventInfo { + pub id: i64, + #[serde(flatten)] + pub spec: EventSpec, + pub creator: UserRef, + pub created_ms: i64, + pub updated_ms: i64, + #[serde(default)] + pub going: u32, + #[serde(default)] + pub maybe: u32, + #[serde(default)] + pub not_going: u32, + /// The requesting user's answer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub my_rsvp: Option, + /// Everyone who answered; only in [`crate::ClientMsg::GetEvent`] replies. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub attendees: Vec, + /// Directory id of the stream while the host is live. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub live_stream: Option, +} + +/// Parameters of [`crate::ClientMsg::ListEvents`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventQuery { + /// Events that end (or, without an end, start) at or after this time. + /// Default: now. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + /// Events that start before this time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + /// Only events in this channel. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// What a streamer registers. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StreamSpec { + /// The TeamSpeak 6 stream id (from `notifystreamstarted`). + pub stream_id: String, + /// The streamer's voice client id, so the gateway can drop the entry + /// when the client leaves or stops streaming. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub title: String, + /// Free form, e.g. `screen`, `window`, `camera`, `game`. + #[serde(default)] + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub viewers: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StreamSource { + /// Registered by the streamer's app; has a stream id. + Registered, + /// Seen by the gateway (`client_is_streaming`) without a registration; + /// the stream id is unknown. + Detected, + #[serde(other)] + Unknown, +} + +/// An entry in the stream directory. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StreamEntry { + /// Directory id: the stream id when known, otherwise `client/`. + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_id: Option, + pub streamer: UserRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub title: String, + #[serde(default)] + pub kind: String, + pub started_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub viewers: Option, + pub source: StreamSource, + /// The scheduled event this stream belongs to. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub event_id: Option, +} + +/// An entry in the server's activity feed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ActivityEntry { + pub id: i64, + pub ts_ms: i64, + /// One of [`activity_kind`], or something newer. + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + /// Id of what the entry is about (message, topic, event or stream id). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ref_id: Option, + /// Human-readable summary, for kinds the client does not know. + pub text: String, + /// Kind-specific details. + #[serde(default, skip_serializing_if = "serde_json::Value::is_null")] + pub data: serde_json::Value, +} + +/// Where a configuration value comes from, highest precedence first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConfigSource { + /// Set at runtime ([`crate::ClientMsg::ConfigSet`]), stored in the gateway's database. + Db, + /// `tsgw --set key=value`. + Cli, + /// `TSGW_` environment variable. + Env, + /// `tsgw.toml`. + File, + Default, + #[serde(other)] + Unknown, +} + +/// One configuration key. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConfigEntry { + /// Dotted key, e.g. `history.retention_days`. + pub key: String, + /// Effective value (secrets are masked). + pub value: serde_json::Value, + pub source: ConfigSource, + pub default: serde_json::Value, + /// `bool`, `int`, `string`, `int_list`, `string_list` or `rule`. + #[serde(rename = "type")] + pub value_type: String, + pub description: String, + /// Only read from the file, environment or command line at start; + /// cannot be set at runtime. + #[serde(default, skip_serializing_if = "is_false")] + pub bootstrap: bool, +} + +/// Something a permission rule can allow. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Action { + /// React to messages. + React, + /// Pin and unpin messages. + Pin, + /// Start topics. + CreateTopic, + /// Schedule events. + CreateEvent, + /// Answer event invitations. + Rsvp, + /// Register streams in the directory. + Stream, + /// Edit and delete other users' topics, events and pins. + Moderate, + /// Change the gateway's configuration and permission rules. + Admin, + #[serde(other)] + Unknown, +} + +impl Action { + /// Every action that rules can be set for. + pub const ALL: [Action; 8] = [ + Action::React, + Action::Pin, + Action::CreateTopic, + Action::CreateEvent, + Action::Rsvp, + Action::Stream, + Action::Moderate, + Action::Admin, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Action::React => "react", + Action::Pin => "pin", + Action::CreateTopic => "create_topic", + Action::CreateEvent => "create_event", + Action::Rsvp => "rsvp", + Action::Stream => "stream", + Action::Moderate => "moderate", + Action::Admin => "admin", + Action::Unknown => "unknown", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|a| a.as_str() == s) + } +} + +/// Who may do an action: members of any of the listed TeamSpeak server +/// groups, or of any listed channel group in the channel concerned, or +/// everyone. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PermRule { + #[serde(default, skip_serializing_if = "is_false")] + pub everyone: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub server_groups: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub channel_groups: Vec, +} + +/// The rule for one action. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PermRuleInfo { + pub action: Action, + /// The configured rule; `None` when the built-in default applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule: Option, + /// Where the rule comes from. + pub source: ConfigSource, + /// What the built-in default allows. + pub default: String, +} diff --git a/crates/voelin-gateway/Cargo.toml b/crates/voelin-gateway/Cargo.toml index 0fe726c..3492e4b 100644 --- a/crates/voelin-gateway/Cargo.toml +++ b/crates/voelin-gateway/Cargo.toml @@ -37,4 +37,8 @@ voelin-query = { path = "../voelin-query" } workspace = true [dev-dependencies] +futures-util = "0.3.34" tokio-tungstenite = "0.30.0" +tsproto-types = { path = "../proto/tsproto-types" } +# The typed client drives the in-process and live tests. +voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } diff --git a/crates/voelin-gateway/src/config.rs b/crates/voelin-gateway/src/config.rs index 739f98b..ad95174 100644 --- a/crates/voelin-gateway/src/config.rs +++ b/crates/voelin-gateway/src/config.rs @@ -1,214 +1,539 @@ -//! `tsgw.toml`. +//! Configuration keys and where their values come from. +//! +//! Every setting is a dotted key (`history.retention_days`), described in +//! [`KEYS`]. Its value is the first one found in: the database (set at +//! runtime, see `settings.rs`), `--set key=value` on the command line, the +//! environment (`TSGW_HISTORY_RETENTION_DAYS`), `tsgw.toml`, the built-in +//! default. +//! +//! Bootstrap keys (query login, addresses, database path) are needed before +//! the database opens; they only come from the command line, environment and +//! file, and apply at start. +use std::collections::BTreeMap; use std::net::SocketAddr; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result, anyhow, bail}; use serde::Deserialize; +use serde_json::Value; +use voelin_gateway_proto::{Action, PermRule}; use voelin_query::Transport; -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Config { - /// Identifies this gateway in signed challenges. Defaults to `public_url` - /// or the query address. - #[serde(default)] - pub gateway_id: Option, - pub server: ServerConfig, - pub query: QueryConfig, - #[serde(default)] - pub listen: ListenConfig, - #[serde(default)] - pub auth: AuthConfig, - #[serde(default)] - pub relay: RelayConfig, - #[serde(default)] - pub history: HistoryConfig, +/// Value type of a key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Bool, + /// Non-negative integer. + Int, + Str, + /// A string or unset (`null`). + OptStr, + IntList, + StrList, + /// A [`PermRule`] or unset (`null`: the action's default). + Rule, } -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ServerConfig { - /// Voice port of the virtual server to serve. - #[serde(default = "default_voice_port")] - pub voice_port: u16, -} - -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct QueryConfig { - /// `raw` (TeamSpeak 3) or `ssh`. HTTP has no events and cannot relay chat. - pub transport: Transport, - /// host:port of the query interface. - pub addr: String, - #[serde(default = "default_user")] - pub user: String, - /// Password; prefer `password_file` or the `TSGW_QUERY_PASSWORD` variable. - #[serde(default)] - pub password: Option, - #[serde(default)] - pub password_file: Option, - /// The gateway's IP is on the server's query allowlist, so the client-side - /// flood limit (10 commands per 3 s) is not needed. - #[serde(default)] - pub allowlisted: bool, -} - -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ListenConfig { - #[serde(default = "default_bind")] - pub bind: SocketAddr, - /// URL clients use, e.g. `wss://gw.example.org/v1`. - #[serde(default)] - pub public_url: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct AuthConfig { - /// If not empty, users need one of these server groups. - #[serde(default)] - pub require_server_groups: Vec, - /// Unique ids that may never use the gateway. - #[serde(default)] - pub deny_uids: Vec, - /// Minimum identity level, on top of the server's own requirement. - #[serde(default)] - pub min_security_level: u8, - #[serde(default = "default_token_ttl_hours")] - pub token_ttl_hours: u64, -} - -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RelayConfig { - #[serde(default = "default_relay_nickname")] - pub nickname: String, - /// How posts appear in the channel; `{nick}` and `{text}` are replaced. - #[serde(default = "default_relay_format")] - pub format: String, - /// Close a relay this long after its last reader left (unless pinned). - #[serde(default = "default_idle_teardown")] - pub idle_teardown_secs: u64, - /// Upper bound on concurrent relays (each is one query connection). - #[serde(default = "default_max_relays")] - pub max_channel_relays: usize, - /// Always relayed, so their history is complete. - #[serde(default)] - pub pinned_channels: Vec, -} - -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct HistoryConfig { - #[serde(default = "default_true")] - pub enabled: bool, - #[serde(default = "default_db_path")] - pub path: PathBuf, - #[serde(default = "default_retention_days")] - pub retention_days: u64, -} - -fn default_voice_port() -> u16 { - 9987 -} -fn default_user() -> String { - "serveradmin".into() -} -fn default_bind() -> SocketAddr { - "0.0.0.0:7788".parse().unwrap() -} -fn default_token_ttl_hours() -> u64 { - 24 * 30 -} -fn default_relay_nickname() -> String { - "Chat Relay".into() -} -fn default_relay_format() -> String { - "[{nick}] {text}".into() -} -fn default_idle_teardown() -> u64 { - 120 -} -fn default_max_relays() -> usize { - 6 -} -fn default_true() -> bool { - true -} -fn default_db_path() -> PathBuf { - "tsgw.db".into() -} -fn default_retention_days() -> u64 { - 30 -} - -impl Default for ListenConfig { - fn default() -> Self { - Self { bind: default_bind(), public_url: None } - } -} - -impl Default for RelayConfig { - fn default() -> Self { - Self { - nickname: default_relay_nickname(), - format: default_relay_format(), - idle_teardown_secs: default_idle_teardown(), - max_channel_relays: default_max_relays(), - pinned_channels: Vec::new(), +impl Kind { + pub fn name(self) -> &'static str { + match self { + Kind::Bool => "bool", + Kind::Int => "int", + Kind::Str | Kind::OptStr => "string", + Kind::IntList => "int_list", + Kind::StrList => "string_list", + Kind::Rule => "rule", } } } -impl Default for HistoryConfig { - fn default() -> Self { - Self { enabled: true, path: default_db_path(), retention_days: default_retention_days() } +/// One configuration key. +#[derive(Debug)] +pub struct KeyDef { + pub key: &'static str, + pub kind: Kind, + /// Default as JSON. + pub default: &'static str, + pub description: &'static str, + /// Read at start only, never from the database. + pub bootstrap: bool, + /// Masked in listings. + pub secret: bool, +} + +impl KeyDef { + pub fn default_value(&self) -> Value { + serde_json::from_str(self.default).expect("valid default") + } + + /// Environment variable for this key. + pub fn env_name(&self) -> String { + format!("TSGW_{}", self.key.to_uppercase().replace('.', "_")) } } -impl Config { - pub fn load(path: &Path) -> Result { +const fn boot( + key: &'static str, + kind: Kind, + default: &'static str, + description: &'static str, +) -> KeyDef { + KeyDef { key, kind, default, description, bootstrap: true, secret: false } +} + +const fn key( + key: &'static str, + kind: Kind, + default: &'static str, + description: &'static str, +) -> KeyDef { + KeyDef { key, kind, default, description, bootstrap: false, secret: false } +} + +/// Every key. Quotas and limits are off (0) or generous unless an admin sets them. +pub static KEYS: &[KeyDef] = &[ + boot( + "gateway_id", + Kind::OptStr, + "null", + "Identifies this gateway in signed login challenges; default: listen.public_url or tsgw@", + ), + boot("server.voice_port", Kind::Int, "9987", "Voice port of the virtual server to serve"), + boot( + "query.transport", + Kind::OptStr, + "null", + "\"ssh\" (TeamSpeak 3 and 6) or \"raw\" (TeamSpeak 3)", + ), + boot("query.addr", Kind::OptStr, "null", "host:port of the ServerQuery interface"), + boot("query.user", Kind::Str, "\"serveradmin\"", "ServerQuery login name"), + KeyDef { + key: "query.password", + kind: Kind::OptStr, + default: "null", + description: "ServerQuery password; prefer query.password_file or TSGW_QUERY_PASSWORD", + bootstrap: true, + secret: true, + }, + boot("query.password_file", Kind::OptStr, "null", "File holding the ServerQuery password"), + boot( + "query.allowlisted", + Kind::Bool, + "false", + "The gateway's IP is on the server's query allowlist (no client-side flood limit)", + ), + boot("listen.bind", Kind::Str, "\"0.0.0.0:7788\"", "Address the WebSocket server listens on"), + boot( + "listen.public_url", + Kind::OptStr, + "null", + "URL clients use, e.g. wss://gw.example.org/v1", + ), + boot( + "history.path", + Kind::Str, + "\"tsgw.db\"", + "SQLite database (history, tokens, runtime settings)", + ), + key( + "auth.require_server_groups", + Kind::IntList, + "[]", + "If not empty, users need one of these server groups", + ), + key("auth.deny_uids", Kind::StrList, "[]", "Unique ids that may never use the gateway"), + key( + "auth.min_security_level", + Kind::Int, + "0", + "Minimum identity level, on top of the server's own requirement", + ), + key("auth.token_ttl_hours", Kind::Int, "720", "Lifetime of login tokens"), + key( + "relay.nickname", + Kind::Str, + "\"Chat Relay\"", + "Nickname of relay sessions (the channel id is appended)", + ), + key( + "relay.format", + Kind::Str, + "\"[{nick}] {text}\"", + "How posts appear in TeamSpeak; {nick} and {text} are replaced", + ), + key( + "relay.idle_teardown_secs", + Kind::Int, + "120", + "Close a relay this long after its last reader left (unless pinned)", + ), + key( + "relay.max_channel_relays", + Kind::Int, + "6", + "Concurrent relays, each one query connection; keep below the server's per-IP limit (0: no limit)", + ), + key( + "relay.pinned_channels", + Kind::IntList, + "[]", + "Channels relayed all the time, so their history is complete", + ), + key( + "history.enabled", + Kind::Bool, + "true", + "Store chat messages (needed for pins, reactions and topics)", + ), + key( + "history.retention_days", + Kind::Int, + "0", + "Delete messages older than this (0: keep forever)", + ), + key("features.pins", Kind::Bool, "true", "Pinned messages"), + key("features.reactions", Kind::Bool, "true", "Emoji reactions"), + key("features.topics", Kind::Bool, "true", "Topics (threads) in chats"), + key("features.events", Kind::Bool, "true", "Scheduled events with RSVP"), + key("features.streams", Kind::Bool, "true", "Directory of running streams"), + key("features.activity", Kind::Bool, "true", "Server activity feed"), + key( + "topics.relay_format", + Kind::Str, + "\"[#{topic}] {text}\"", + "How topic posts appear in TeamSpeak; {topic} and {text} are replaced. Messages from TeamSpeak in this format join the topic", + ), + key( + "events.reminder_minutes", + Kind::IntList, + "[15, 0]", + "Remind event subscribers this many minutes before an event starts (0: when it starts)", + ), + key( + "events.stream_link_minutes", + Kind::Int, + "60", + "A stream by the host of a stream event links to it from this long before the start until this long after the end", + ), + key( + "activity.retention_days", + Kind::Int, + "0", + "Delete activity entries older than this (0: keep forever)", + ), + key( + "limits.posts_per_window", + Kind::Int, + "5", + "Chat posts per connection and window (0: no limit)", + ), + key("limits.post_window_secs", Kind::Int, "5", "Window of limits.posts_per_window"), + key( + "limits.actions_per_window", + Kind::Int, + "30", + "Other changes (pins, reactions, topics, events, streams) per connection and window (0: no limit)", + ), + key("limits.action_window_secs", Kind::Int, "10", "Window of limits.actions_per_window"), + key("quota.history_page", Kind::Int, "0", "Most messages per history page (0: no limit)"), + key("quota.pins_per_channel", Kind::Int, "0", "Pinned messages per chat (0: no limit)"), + key("quota.topics_per_channel", Kind::Int, "0", "Open topics per chat (0: no limit)"), + key( + "quota.events_per_user", + Kind::Int, + "0", + "Upcoming events a user may have created (0: no limit)", + ), + key("quota.reactions_per_message", Kind::Int, "0", "Different emoji per message (0: no limit)"), + key("quota.reaction_bytes", Kind::Int, "64", "Longest reaction in bytes (0: no limit)"), + key( + "quota.message_bytes", + Kind::Int, + "0", + "Longest chat post in bytes (0: no limit; TeamSpeak splits long ones)", + ), + key("quota.streams_per_user", Kind::Int, "0", "Directory entries per user (0: no limit)"), + key("perm.react", Kind::Rule, "null", "Who may react; default: everyone who can read the chat"), + key( + "perm.pin", + Kind::Rule, + "null", + "Who may pin; default: moderators (b_channel_modify_name in the channel) and admins", + ), + key( + "perm.create_topic", + Kind::Rule, + "null", + "Who may start topics; default: everyone who can post in the chat", + ), + key( + "perm.create_event", + Kind::Rule, + "null", + "Who may schedule events; default: everyone who can post in the event's channel (server chat for server-wide events)", + ), + key("perm.rsvp", Kind::Rule, "null", "Who may answer events; default: everyone"), + key( + "perm.stream", + Kind::Rule, + "null", + "Who may list streams in the directory; default: everyone", + ), + key( + "perm.moderate", + Kind::Rule, + "null", + "Who may edit or delete others' topics, events and pins; default: b_channel_modify_name in the channel, admins", + ), + key( + "perm.admin", + Kind::Rule, + "null", + "Who may change settings and rules; default: b_virtualserver_modify_name (Server Admin)", + ), +]; + +pub fn key_def(key: &str) -> Option<&'static KeyDef> { + KEYS.iter().find(|k| k.key == key) +} + +/// The config key holding an action's rule. +pub fn perm_key(action: Action) -> String { + format!("perm.{}", action.as_str()) +} + +/// Check a value against a key's type; returns it normalized. +pub fn validate(def: &KeyDef, value: Value) -> Result { + let ok = match def.kind { + Kind::Bool => value.is_boolean(), + Kind::Int => value.is_u64(), + Kind::Str => value.is_string(), + Kind::OptStr => value.is_string() || value.is_null(), + Kind::IntList => value.as_array().is_some_and(|a| a.iter().all(Value::is_u64)), + Kind::StrList => value.as_array().is_some_and(|a| a.iter().all(Value::is_string)), + Kind::Rule => { + if value.is_null() { + true + } else { + serde_json::from_value::(value.clone()) + .map_err(|e| anyhow!("{}: invalid rule: {e}", def.key))?; + value.is_object() + } + } + }; + if !ok { + bail!("{}: expected {}, got {value}", def.key, def.kind.name()); + } + if def.key == "listen.bind" { + value.as_str().unwrap_or_default().parse::().context("listen.bind")?; + } + if def.key == "query.transport" && !value.is_null() { + transport(&value)?; + } + Ok(value) +} + +fn transport(value: &Value) -> Result { + let transport: Transport = serde_json::from_value(value.clone()) + .context("query.transport must be \"ssh\" or \"raw\"")?; + if transport == Transport::Http { + bail!("query.transport = \"http\" has no events; use \"ssh\" or \"raw\""); + } + Ok(transport) +} + +/// Parse a value given as text (environment, command line). +pub fn parse_text(def: &KeyDef, text: &str) -> Result { + let text = text.trim(); + let value = match def.kind { + Kind::Bool => match text.to_ascii_lowercase().as_str() { + "true" | "1" | "yes" | "on" => Value::Bool(true), + "false" | "0" | "no" | "off" => Value::Bool(false), + _ => bail!("{}: expected true or false, got {text:?}", def.key), + }, + Kind::Int => Value::from( + text.parse::().with_context(|| format!("{}: expected a number", def.key))?, + ), + Kind::Str | Kind::OptStr => Value::String(text.to_string()), + Kind::IntList | Kind::StrList if !text.starts_with('[') => Value::Array( + text.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| match def.kind { + Kind::IntList => s + .parse::() + .map(Value::from) + .with_context(|| format!("{}: expected numbers", def.key)), + _ => Ok(Value::String(s.to_string())), + }) + .collect::>()?, + ), + _ => serde_json::from_str(text).with_context(|| format!("{}: invalid JSON", def.key))?, + }; + validate(def, value) +} + +/// Values by key. +pub type Values = BTreeMap; + +/// The values of one source. +pub fn file_values(text: &str) -> Result { + let table: toml::Table = toml::from_str(text)?; + let mut out = Values::new(); + flatten(&table, "", &mut out)?; + Ok(out) +} + +fn flatten(table: &toml::Table, prefix: &str, out: &mut Values) -> Result<()> { + for (k, v) in table { + let path = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }; + if let Some(def) = key_def(&path) { + let json = serde_json::to_value(v).context("value")?; + out.insert(path, validate(def, json)?); + } else if let toml::Value::Table(t) = v { + flatten(t, &path, out)?; + } else { + bail!("unknown setting {path}"); + } + } + Ok(()) +} + +/// Values from `TSGW_` variables. +pub fn env_values(lookup: impl Fn(&str) -> Option) -> Result { + let mut out = Values::new(); + for def in KEYS { + if let Some(text) = lookup(&def.env_name()) { + out.insert(def.key.to_string(), parse_text(def, &text)?); + } + } + Ok(out) +} + +/// Values from `--set key=value`. +pub fn cli_values(sets: &[String]) -> Result { + let mut out = Values::new(); + for set in sets { + let (k, v) = + set.split_once('=').ok_or_else(|| anyhow!("--set needs key=value, got {set:?}"))?; + let def = key_def(k.trim()).ok_or_else(|| anyhow!("unknown setting {k}"))?; + out.insert(def.key.to_string(), parse_text(def, v)?); + } + Ok(out) +} + +/// Where a value came from, lowest precedence last. +pub use voelin_gateway_proto::ConfigSource as Source; + +/// The sources below the database. +#[derive(Clone, Debug, Default)] +pub struct Layers { + /// The configuration file, for reloads. + pub path: Option, + pub cli: Values, + pub env: Values, + pub file: Values, +} + +impl Layers { + /// Read the file, environment and `--set` arguments. + pub fn load(path: &Path, sets: &[String]) -> Result { + Ok(Self { + path: Some(path.to_path_buf()), + cli: cli_values(sets)?, + env: env_values(|name| std::env::var(name).ok())?, + file: Self::read_file(path)?, + }) + } + + pub fn read_file(path: &Path) -> Result { let text = std::fs::read_to_string(path) .with_context(|| format!("failed to read {}", path.display()))?; - let mut config: Config = - toml::from_str(&text).with_context(|| format!("invalid {}", path.display()))?; - config.resolve_password()?; - if config.query.transport == Transport::Http { - bail!("query.transport = \"http\" has no events; use \"ssh\" or \"raw\""); - } - Ok(config) + file_values(&text).with_context(|| format!("invalid {}", path.display())) } - fn resolve_password(&mut self) -> Result<()> { - if let Some(file) = &self.query.password_file { - let pw = std::fs::read_to_string(file) + /// Value and source of a key, ignoring the database. + pub fn resolve(&self, def: &KeyDef) -> (Value, Source) { + for (values, source) in + [(&self.cli, Source::Cli), (&self.env, Source::Env), (&self.file, Source::File)] + { + if let Some(v) = values.get(def.key) { + return (v.clone(), source); + } + } + (def.default_value(), Source::Default) + } + + fn get Deserialize<'de>>(&self, key: &str) -> Result { + let def = key_def(key).expect("known key"); + serde_json::from_value(self.resolve(def).0).with_context(|| key.to_string()) + } + + /// The bootstrap values. + pub fn bootstrap(&self) -> Result { + let transport = self.resolve(key_def("query.transport").unwrap()).0; + if transport.is_null() { + bail!("query.transport is not set"); + } + let mut password: Option = self.get("query.password")?; + if let Some(file) = self.get::>("query.password_file")? { + let pw = std::fs::read_to_string(&file) .with_context(|| format!("failed to read {}", file.display()))?; - self.query.password = Some(pw.trim().to_string()); - } else if let Ok(pw) = std::env::var("TSGW_QUERY_PASSWORD") { - self.query.password = Some(pw); + password = Some(pw.trim().to_string()); } - Ok(()) + Ok(Bootstrap { + gateway_id: self.get("gateway_id")?, + voice_port: self.get("server.voice_port")?, + transport: transport_of(&transport)?, + addr: self.get::>("query.addr")?.context("query.addr is not set")?, + user: self.get("query.user")?, + password, + allowlisted: self.get("query.allowlisted")?, + bind: self.get::("listen.bind")?.parse().context("listen.bind")?, + public_url: self.get("listen.public_url")?, + db_path: self.get("history.path")?, + }) } +} +fn transport_of(value: &Value) -> Result { + transport(value) +} + +/// What the gateway needs before its database opens. +#[derive(Clone, Debug)] +pub struct Bootstrap { + pub gateway_id: Option, + pub voice_port: u16, + pub transport: Transport, + pub addr: String, + pub user: String, + pub password: Option, + pub allowlisted: bool, + pub bind: SocketAddr, + pub public_url: Option, + pub db_path: PathBuf, +} + +impl Bootstrap { pub fn gateway_id(&self) -> String { self.gateway_id .clone() - .or_else(|| self.listen.public_url.clone()) - .unwrap_or_else(|| format!("tsgw@{}", self.query.addr)) + .or_else(|| self.public_url.clone()) + .unwrap_or_else(|| format!("tsgw@{}", self.addr)) } pub fn query_connect(&self) -> voelin_query::Connect { voelin_query::Connect { - transport: self.query.transport, - addr: self.query.addr.clone(), - user: self.query.user.clone(), - secret: self.query.password.clone(), - server_port: Some(self.server.voice_port), + transport: self.transport, + addr: self.addr.clone(), + user: self.user.clone(), + secret: self.password.clone(), + server_port: Some(self.voice_port), server_id: None, line: voelin_query::LineOptions { - rate_limit: if self.query.allowlisted { + rate_limit: if self.allowlisted { None } else { voelin_query::LineOptions::default().rate_limit @@ -219,27 +544,211 @@ impl Config { } } +/// Settings that can change at runtime, as the gateway uses them. +#[derive(Clone, Debug, Deserialize)] +pub struct Runtime { + pub auth: AuthSettings, + pub relay: RelaySettings, + pub history: HistorySettings, + pub features: Features, + pub topics: TopicSettings, + pub events: EventSettings, + pub activity: ActivitySettings, + pub limits: Limits, + pub quota: Quotas, + pub perm: PermRules, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct AuthSettings { + pub require_server_groups: Vec, + pub deny_uids: Vec, + pub min_security_level: u8, + pub token_ttl_hours: u64, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct RelaySettings { + pub nickname: String, + pub format: String, + pub idle_teardown_secs: u64, + pub max_channel_relays: u64, + pub pinned_channels: Vec, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct HistorySettings { + pub enabled: bool, + pub retention_days: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +pub struct Features { + pub pins: bool, + pub reactions: bool, + pub topics: bool, + pub events: bool, + pub streams: bool, + pub activity: bool, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct TopicSettings { + pub relay_format: String, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct EventSettings { + pub reminder_minutes: Vec, + pub stream_link_minutes: u64, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct ActivitySettings { + pub retention_days: u64, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct Limits { + pub posts_per_window: u64, + pub post_window_secs: u64, + pub actions_per_window: u64, + pub action_window_secs: u64, +} + +/// 0 means no limit. +#[derive(Clone, Debug, Deserialize)] +pub struct Quotas { + pub history_page: u64, + pub pins_per_channel: u64, + pub topics_per_channel: u64, + pub events_per_user: u64, + pub reactions_per_message: u64, + pub reaction_bytes: u64, + pub message_bytes: u64, + pub streams_per_user: u64, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct PermRules { + pub react: Option, + pub pin: Option, + pub create_topic: Option, + pub create_event: Option, + pub rsvp: Option, + pub stream: Option, + pub moderate: Option, + pub admin: Option, +} + +impl PermRules { + pub fn get(&self, action: Action) -> Option<&PermRule> { + match action { + Action::React => self.react.as_ref(), + Action::Pin => self.pin.as_ref(), + Action::CreateTopic => self.create_topic.as_ref(), + Action::CreateEvent => self.create_event.as_ref(), + Action::Rsvp => self.rsvp.as_ref(), + Action::Stream => self.stream.as_ref(), + Action::Moderate => self.moderate.as_ref(), + Action::Admin => self.admin.as_ref(), + Action::Unknown => None, + } + } +} + +impl Runtime { + /// Build from effective values of the runtime keys. + pub fn from_values(get: impl Fn(&KeyDef) -> Value) -> Result { + let mut root = serde_json::Map::new(); + for def in KEYS.iter().filter(|d| !d.bootstrap) { + let (section, name) = def.key.split_once('.').expect("runtime keys have a section"); + root.entry(section) + .or_insert_with(|| Value::Object(Default::default())) + .as_object_mut() + .expect("section") + .insert(name.to_string(), get(def)); + } + Ok(serde_json::from_value(Value::Object(root))?) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn defaults_are_valid() { + for def in KEYS { + validate(def, def.default_value()).unwrap(); + assert!(!def.description.is_empty()); + } + let rt = Runtime::from_values(KeyDef::default_value).unwrap(); + assert_eq!(rt.relay.max_channel_relays, 6); + assert_eq!(rt.history.retention_days, 0); + assert!(rt.features.pins && rt.history.enabled); + assert_eq!(rt.events.reminder_minutes, [15, 0]); + assert!(rt.perm.admin.is_none()); + } + #[test] fn parses_example() { - let text = include_str!("../tsgw.example.toml"); - let config: Config = toml::from_str(text).unwrap(); - assert_eq!(config.query.transport, Transport::Ssh); - assert_eq!(config.relay.format, "[{nick}] {text}"); - assert_eq!(config.server.voice_port, 9987); + let values = file_values(include_str!("../tsgw.example.toml")).unwrap(); + let layers = Layers { file: values, ..Default::default() }; + let boot = layers.bootstrap().unwrap(); + assert_eq!(boot.transport, Transport::Ssh); + assert_eq!(boot.voice_port, 9987); + assert_eq!(layers.resolve(key_def("relay.format").unwrap()).0, "[{nick}] {text}"); } #[test] fn minimal_config_uses_defaults() { - let config: Config = - toml::from_str("[server]\n[query]\ntransport = \"raw\"\naddr = \"127.0.0.1:10011\"\n") + let file = + file_values("[server]\n[query]\ntransport = \"raw\"\naddr = \"127.0.0.1:10011\"\n") .unwrap(); - assert_eq!(config.listen.bind.port(), 7788); - assert_eq!(config.relay.max_channel_relays, 6); - assert!(config.history.enabled); - assert_eq!(config.gateway_id(), "tsgw@127.0.0.1:10011"); + let layers = Layers { file, ..Default::default() }; + let boot = layers.bootstrap().unwrap(); + assert_eq!(boot.bind.port(), 7788); + assert_eq!(boot.gateway_id(), "tsgw@127.0.0.1:10011"); + assert_eq!(boot.db_path, PathBuf::from("tsgw.db")); + let (v, source) = layers.resolve(key_def("relay.max_channel_relays").unwrap()); + assert_eq!((v, source), (Value::from(6), Source::Default)); + } + + #[test] + fn rejects_bad_values() { + assert!(file_values("[relay]\nunknown = 1\n").is_err()); + assert!(file_values("[history]\nretention_days = \"x\"\n").is_err()); + assert!(file_values("[query]\ntransport = \"http\"\n").is_err()); + assert!(file_values("[listen]\nbind = \"nope\"\n").is_err()); + assert!(file_values("[perm]\npin = { server_groups = [\"a\"] }\n").is_err()); + let rule = + file_values("[perm]\npin = { server_groups = [6], channel_groups = [5] }\n").unwrap(); + assert_eq!(rule["perm.pin"]["server_groups"][0], 6); + } + + #[test] + fn env_and_cli_text() { + let env = env_values(|name| match name { + "TSGW_HISTORY_RETENTION_DAYS" => Some("7".into()), + "TSGW_RELAY_PINNED_CHANNELS" => Some("1, 2".into()), + "TSGW_FEATURES_PINS" => Some("off".into()), + "TSGW_PERM_ADMIN" => Some(r#"{"server_groups":[6]}"#.into()), + "TSGW_QUERY_PASSWORD" => Some("pw".into()), + _ => None, + }) + .unwrap(); + assert_eq!(env["history.retention_days"], 7); + assert_eq!(env["relay.pinned_channels"], serde_json::json!([1, 2])); + assert_eq!(env["features.pins"], false); + assert_eq!(env["perm.admin"]["server_groups"], serde_json::json!([6])); + assert_eq!(env["query.password"], "pw"); + let cli = + cli_values(&["auth.deny_uids=[\"a\",\"b\"]".into(), "relay.nickname= Bot ".into()]) + .unwrap(); + assert_eq!(cli["auth.deny_uids"], serde_json::json!(["a", "b"])); + assert_eq!(cli["relay.nickname"], "Bot"); + assert!(cli_values(&["nope=1".into()]).is_err()); + assert!(cli_values(&["history.retention_days=-1".into()]).is_err()); } } diff --git a/crates/voelin-gateway/src/db.rs b/crates/voelin-gateway/src/db.rs deleted file mode 100644 index 4712273..0000000 --- a/crates/voelin-gateway/src/db.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! SQLite: login tokens, chat history, audit log. - -use std::path::Path; -use std::sync::Mutex; - -use rusqlite::{Connection, OptionalExtension, params}; -use voelin_model::{ChatMessage, ChatTarget}; - -pub struct Db(Mutex); - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TokenInfo { - pub uid: String, - pub cldbid: u64, - pub expires: i64, -} - -fn target_key(target: &ChatTarget) -> String { - match target { - ChatTarget::Server => "server".into(), - ChatTarget::Channel(cid) => format!("channel/{cid}"), - ChatTarget::Private(uid) => format!("private/{uid}"), - } -} - -impl Db { - pub fn open(path: &Path) -> rusqlite::Result { - Self::init(Connection::open(path)?) - } - - #[cfg(test)] - pub fn in_memory() -> rusqlite::Result { - Self::init(Connection::open_in_memory()?) - } - - fn init(conn: Connection) -> rusqlite::Result { - conn.pragma_update(None, "journal_mode", "WAL")?; - conn.execute_batch( - "CREATE TABLE IF NOT EXISTS tokens ( - hash TEXT PRIMARY KEY, - uid TEXT NOT NULL, - cldbid INTEGER NOT NULL, - expires INTEGER NOT NULL - ); - CREATE TABLE IF NOT EXISTS messages ( - id INTEGER PRIMARY KEY, - target TEXT NOT NULL, - ts_ms INTEGER NOT NULL, - author_uid TEXT, - author_name TEXT NOT NULL, - text TEXT NOT NULL - ); - CREATE INDEX IF NOT EXISTS messages_by_target ON messages (target, id); - CREATE TABLE IF NOT EXISTS audit ( - ts INTEGER NOT NULL, - uid TEXT, - action TEXT NOT NULL, - detail TEXT - );", - )?; - Ok(Self(Mutex::new(conn))) - } - - pub fn add_token(&self, hash: &str, info: &TokenInfo) -> rusqlite::Result<()> { - self.0.lock().unwrap().execute( - "INSERT OR REPLACE INTO tokens (hash, uid, cldbid, expires) VALUES (?1, ?2, ?3, ?4)", - params![hash, info.uid, info.cldbid as i64, info.expires], - )?; - Ok(()) - } - - /// A token that has not expired at `now`. - pub fn token(&self, hash: &str, now: i64) -> rusqlite::Result> { - self.0 - .lock() - .unwrap() - .query_row( - "SELECT uid, cldbid, expires FROM tokens WHERE hash = ?1 AND expires > ?2", - params![hash, now], - |r| { - Ok(TokenInfo { - uid: r.get(0)?, - cldbid: r.get::<_, i64>(1)? as u64, - expires: r.get(2)?, - }) - }, - ) - .optional() - } - - /// Store a message; returns its id. - pub fn add_message(&self, msg: &ChatMessage) -> rusqlite::Result { - let conn = self.0.lock().unwrap(); - conn.execute( - "INSERT INTO messages (target, ts_ms, author_uid, author_name, text) VALUES (?1, ?2, ?3, ?4, ?5)", - params![target_key(&msg.target), msg.ts_ms, msg.author_uid, msg.author_name, msg.text], - )?; - Ok(conn.last_insert_rowid()) - } - - /// Up to `limit` messages before id `before`, oldest first. - pub fn history( - &self, - target: &ChatTarget, - before: Option, - limit: u32, - ) -> rusqlite::Result> { - let conn = self.0.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT id, ts_ms, author_uid, author_name, text FROM messages - WHERE target = ?1 AND id < ?2 ORDER BY id DESC LIMIT ?3", - )?; - let rows = - stmt.query_map(params![target_key(target), before.unwrap_or(i64::MAX), limit], |r| { - Ok(( - r.get::<_, i64>(0)?, - ChatMessage { - target: target.clone(), - ts_ms: r.get(1)?, - author_uid: r.get(2)?, - author_name: r.get(3)?, - author_id: None, - text: r.get(4)?, - via_relay: true, - }, - )) - })?; - let mut out = rows.collect::>>()?; - out.reverse(); - Ok(out) - } - - pub fn prune(&self, now: i64, retention_days: u64) -> rusqlite::Result<()> { - let cutoff_ms = (now - retention_days as i64 * 86_400) * 1000; - let conn = self.0.lock().unwrap(); - conn.execute("DELETE FROM messages WHERE ts_ms < ?1", [cutoff_ms])?; - conn.execute("DELETE FROM tokens WHERE expires < ?1", [now])?; - Ok(()) - } - - pub fn audit(&self, now: i64, uid: Option<&str>, action: &str, detail: &str) { - let result = self.0.lock().unwrap().execute( - "INSERT INTO audit (ts, uid, action, detail) VALUES (?1, ?2, ?3, ?4)", - params![now, uid, action, detail], - ); - if let Err(error) = result { - tracing::warn!(%error, "failed to write audit log"); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn msg(target: ChatTarget, text: &str, ts_ms: i64) -> ChatMessage { - ChatMessage { - target, - author_name: "a".into(), - author_uid: Some("u".into()), - author_id: None, - text: text.into(), - ts_ms, - via_relay: true, - } - } - - #[test] - fn tokens_expire() { - let db = Db::in_memory().unwrap(); - let info = TokenInfo { uid: "u".into(), cldbid: 5, expires: 100 }; - db.add_token("h", &info).unwrap(); - assert_eq!(db.token("h", 50).unwrap(), Some(info)); - assert_eq!(db.token("h", 150).unwrap(), None); - assert_eq!(db.token("x", 50).unwrap(), None); - } - - #[test] - fn history_pages_per_target() { - let db = Db::in_memory().unwrap(); - for i in 0..5 { - db.add_message(&msg(ChatTarget::Channel(1), &format!("c{i}"), i)).unwrap(); - db.add_message(&msg(ChatTarget::Server, &format!("s{i}"), i)).unwrap(); - } - let last = db.history(&ChatTarget::Channel(1), None, 2).unwrap(); - assert_eq!(last.iter().map(|(_, m)| m.text.as_str()).collect::>(), ["c3", "c4"]); - let before = db.history(&ChatTarget::Channel(1), Some(last[0].0), 10).unwrap(); - assert_eq!(before.len(), 3); - assert_eq!(db.history(&ChatTarget::Server, None, 10).unwrap().len(), 5); - db.prune(10, 0).unwrap(); - assert!(db.history(&ChatTarget::Server, None, 10).unwrap().is_empty()); - } -} diff --git a/crates/voelin-gateway/src/db/chat.rs b/crates/voelin-gateway/src/db/chat.rs new file mode 100644 index 0000000..c2ec70e --- /dev/null +++ b/crates/voelin-gateway/src/db/chat.rs @@ -0,0 +1,573 @@ +//! Messages, reactions, pins and topics. + +use std::collections::HashMap; + +use rusqlite::{Connection, OptionalExtension, Row, ToSql, params}; +use voelin_gateway_proto::{HistoryEntry, PinInfo, ReactionCount, TopicInfo, UserRef}; +use voelin_model::{ChatMessage, ChatTarget}; + +use super::{Db, parse_target, target_key, user}; + +/// Columns of a message row, see [`entry_from_row`]. +const MESSAGE_COLUMNS: &str = "m.id, m.target, m.ts_ms, m.author_uid, m.author_name, m.text, \ + m.topic_id, m.rev, p.message_id IS NOT NULL"; +const MESSAGE_FROM: &str = "messages m LEFT JOIN pins p ON p.message_id = m.id"; + +fn entry_from_row(r: &Row) -> rusqlite::Result { + let target: String = r.get(1)?; + Ok(HistoryEntry { + id: r.get(0)?, + message: ChatMessage { + target: parse_target(&target), + ts_ms: r.get(2)?, + author_uid: r.get(3)?, + author_name: r.get(4)?, + author_id: None, + text: r.get(5)?, + via_relay: true, + }, + topic_id: r.get(6)?, + rev: r.get(7)?, + pinned: r.get(8)?, + reactions: Vec::new(), + }) +} + +/// A history request after cursors and quotas were applied. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HistoryOptions { + pub before: Option, + pub after: Option, + pub before_ms: Option, + pub after_ms: Option, + /// `None`: no limit. + pub limit: Option, + pub topic: Option, + pub exclude_topics: bool, +} + +impl HistoryOptions { + /// SQL for this shape of request (bound with named parameters). + pub fn sql(&self) -> String { + let mut conds = vec!["m.target = :target"]; + if self.topic.is_some() { + conds.push("m.topic_id = :topic"); + } else if self.exclude_topics { + conds.push("m.topic_id IS NULL"); + } + if self.before.is_some() { + conds.push("m.id < :before"); + } + if self.after.is_some() { + conds.push("m.id > :after"); + } + let order = if self.after.is_some() { "ASC" } else { "DESC" }; + format!( + "SELECT {MESSAGE_COLUMNS} FROM {MESSAGE_FROM} WHERE {} ORDER BY m.id {order} LIMIT :limit", + conds.join(" AND ") + ) + } +} + +/// Add the reaction summary to entries (one range query). +fn add_reactions( + conn: &Connection, + entries: &mut [HistoryEntry], + me: Option<&str>, +) -> rusqlite::Result<()> { + let (Some(lo), Some(hi)) = + (entries.iter().map(|e| e.id).min(), entries.iter().map(|e| e.id).max()) + else { + return Ok(()); + }; + let index: HashMap = entries.iter().enumerate().map(|(i, e)| (e.id, i)).collect(); + let mut stmt = conn.prepare_cached( + "SELECT message_id, emoji, COUNT(*), MAX(uid = ?3), MIN(ts_ms) AS first FROM reactions + WHERE message_id BETWEEN ?1 AND ?2 GROUP BY message_id, emoji ORDER BY message_id, first", + )?; + let mut rows = stmt.query(params![lo, hi, me.unwrap_or("")])?; + while let Some(r) = rows.next()? { + if let Some(&i) = index.get(&r.get::<_, i64>(0)?) { + entries[i].reactions.push(ReactionCount { + emoji: r.get(1)?, + count: r.get(2)?, + me: r.get(3)?, + }); + } + } + Ok(()) +} + +fn topic_from_row(r: &Row) -> rusqlite::Result { + let target: String = r.get(1)?; + Ok(TopicInfo { + id: r.get(0)?, + target: parse_target(&target), + title: r.get(2)?, + creator: user(r.get(3)?, r.get(4)?), + created_ms: r.get(5)?, + root_message_id: r.get(6)?, + last_activity_ms: r.get(7)?, + message_count: r.get::<_, i64>(8)? as u64, + archived: r.get(9)?, + }) +} + +const TOPIC_COLUMNS: &str = "id, target, title, creator_uid, creator_name, created_ms, \ + root_message_id, last_activity_ms, message_count, archived"; + +impl Db { + /// Store a message; returns it with its id and revision. + pub fn add_message( + &self, + msg: ChatMessage, + topic_id: Option, + ) -> rusqlite::Result { + Ok(self.add_messages(vec![(msg, topic_id)])?.pop().expect("one message")) + } + + /// Store several messages in one transaction. + pub fn add_messages( + &self, + msgs: Vec<(ChatMessage, Option)>, + ) -> rusqlite::Result> { + let mut g = self.lock(); + let now = super::now_ms(); + let revs: Vec = msgs.iter().map(|_| g.next_rev(now)).collect(); + let tx = g.conn.transaction()?; + let mut out = Vec::with_capacity(msgs.len()); + { + let mut insert = tx.prepare_cached( + "INSERT INTO messages (target, ts_ms, author_uid, author_name, text, topic_id, rev) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + )?; + let mut topic = tx.prepare_cached( + "UPDATE topics SET message_count = message_count + 1, + last_activity_ms = MAX(last_activity_ms, ?2) WHERE id = ?1", + )?; + for ((msg, topic_id), rev) in msgs.into_iter().zip(revs) { + insert.execute(params![ + target_key(&msg.target), + msg.ts_ms, + msg.author_uid, + msg.author_name, + msg.text, + topic_id, + rev + ])?; + if let Some(t) = topic_id { + topic.execute(params![t, msg.ts_ms])?; + } + out.push(HistoryEntry { + id: tx.last_insert_rowid(), + message: msg, + topic_id, + reactions: Vec::new(), + pinned: false, + rev, + }); + } + } + tx.commit()?; + Ok(out) + } + + /// One message with its reactions as `me` sees them. + pub fn message(&self, id: i64, me: Option<&str>) -> rusqlite::Result> { + let g = self.lock(); + let entry = g + .conn + .prepare_cached(&format!( + "SELECT {MESSAGE_COLUMNS} FROM {MESSAGE_FROM} WHERE m.id = ?1" + ))? + .query_row([id], entry_from_row) + .optional()?; + let Some(entry) = entry else { return Ok(None) }; + let mut entries = [entry]; + add_reactions(&g.conn, &mut entries, me)?; + let [entry] = entries; + Ok(Some(entry)) + } + + /// A page of history, oldest first, and whether there is more in the + /// paging direction. + pub fn history( + &self, + target: &ChatTarget, + opts: &HistoryOptions, + me: Option<&str>, + ) -> rusqlite::Result<(Vec, bool)> { + let g = self.lock(); + let key = target_key(target); + let mut opts = opts.clone(); + // Time cursors become id cursors (ids follow arrival order). + if let Some(after_ms) = opts.after_ms { + let first: Option = g + .conn + .prepare_cached( + "SELECT id FROM messages WHERE target = ?1 AND ts_ms > ?2 + ORDER BY ts_ms, id LIMIT 1", + )? + .query_row(params![key, after_ms], |r| r.get(0)) + .optional()?; + let Some(first) = first else { return Ok((Vec::new(), false)) }; + opts.after = Some(opts.after.map_or(first - 1, |a| a.max(first - 1))); + } + if let Some(before_ms) = opts.before_ms { + let last: Option = g + .conn + .prepare_cached( + "SELECT id FROM messages WHERE target = ?1 AND ts_ms < ?2 + ORDER BY ts_ms DESC, id DESC LIMIT 1", + )? + .query_row(params![key, before_ms], |r| r.get(0)) + .optional()?; + let Some(last) = last else { return Ok((Vec::new(), false)) }; + opts.before = Some(opts.before.map_or(last + 1, |b| b.min(last + 1))); + } + let limit = opts.limit.map_or(-1, |l| i64::from(l) + 1); + let mut named: Vec<(&str, &dyn ToSql)> = vec![(":target", &key), (":limit", &limit)]; + if let Some(t) = &opts.topic { + named.push((":topic", t)); + } + if let Some(b) = &opts.before { + named.push((":before", b)); + } + if let Some(a) = &opts.after { + named.push((":after", a)); + } + let mut stmt = g.conn.prepare_cached(&opts.sql())?; + let mut entries = stmt + .query_map(named.as_slice(), entry_from_row)? + .collect::>>()?; + let has_more = opts.limit.is_some_and(|l| entries.len() > l as usize); + if has_more { + entries.pop(); + } + if opts.after.is_none() { + entries.reverse(); + } + add_reactions(&g.conn, &mut entries, me)?; + Ok((entries, has_more)) + } + + /// Messages of `target` new or changed after revision `since`, by revision. + pub fn sync( + &self, + target: &ChatTarget, + since: i64, + limit: Option, + me: Option<&str>, + ) -> rusqlite::Result<(Vec, bool)> { + let g = self.lock(); + let limit_sql = limit.map_or(-1, |l| i64::from(l) + 1); + let mut entries = g + .conn + .prepare_cached(&format!( + "SELECT {MESSAGE_COLUMNS} FROM {MESSAGE_FROM} + WHERE m.target = ?1 AND m.rev > ?2 ORDER BY m.rev LIMIT ?3" + ))? + .query_map(params![target_key(target), since, limit_sql], entry_from_row)? + .collect::>>()?; + let has_more = limit.is_some_and(|l| entries.len() > l as usize); + if has_more { + entries.pop(); + } + add_reactions(&g.conn, &mut entries, me)?; + Ok((entries, has_more)) + } + + /// Bump a message's revision (something about it changed). + fn touch(conn: &Connection, id: i64, rev: i64) -> rusqlite::Result<()> { + conn.prepare_cached("UPDATE messages SET rev = ?2 WHERE id = ?1")? + .execute(params![id, rev])?; + Ok(()) + } + + /// Delete messages sent before `cutoff_ms`, with their reactions. Pinned + /// messages are kept. Topics without activity since then go too. + pub fn prune_messages(&self, cutoff_ms: i64) -> rusqlite::Result { + let mut g = self.lock(); + let tx = g.conn.transaction()?; + tx.execute( + "DELETE FROM reactions WHERE message_id IN (SELECT id FROM messages + WHERE ts_ms < ?1 AND id NOT IN (SELECT message_id FROM pins))", + [cutoff_ms], + )?; + let n = tx.execute( + "DELETE FROM messages WHERE ts_ms < ?1 AND id NOT IN (SELECT message_id FROM pins)", + [cutoff_ms], + )?; + tx.execute("DELETE FROM topics WHERE last_activity_ms < ?1", [cutoff_ms])?; + tx.commit()?; + Ok(n) + } + + // Reactions + + /// Add a reaction; returns the new count, or `None` if it was there. + pub fn add_reaction( + &self, + message_id: i64, + emoji: &str, + by: &UserRef, + now_ms: i64, + ) -> rusqlite::Result> { + let mut g = self.lock(); + let rev = g.next_rev(now_ms); + let tx = g.conn.transaction()?; + let added = tx + .prepare_cached( + "INSERT OR IGNORE INTO reactions (message_id, emoji, uid, name, ts_ms) + VALUES (?1, ?2, ?3, ?4, ?5)", + )? + .execute(params![message_id, emoji, by.uid, by.name, now_ms])?; + if added == 0 { + return Ok(None); + } + Self::touch(&tx, message_id, rev)?; + let count = reaction_count(&tx, message_id, emoji)?; + tx.commit()?; + Ok(Some(count)) + } + + /// Remove a reaction; returns the new count, or `None` if there was none. + pub fn remove_reaction( + &self, + message_id: i64, + emoji: &str, + uid: &str, + now_ms: i64, + ) -> rusqlite::Result> { + let mut g = self.lock(); + let rev = g.next_rev(now_ms); + let tx = g.conn.transaction()?; + let removed = tx + .prepare_cached( + "DELETE FROM reactions WHERE message_id = ?1 AND emoji = ?2 AND uid = ?3", + )? + .execute(params![message_id, emoji, uid])?; + if removed == 0 { + return Ok(None); + } + Self::touch(&tx, message_id, rev)?; + let count = reaction_count(&tx, message_id, emoji)?; + tx.commit()?; + Ok(Some(count)) + } + + /// Different emoji on a message. + pub fn reaction_kinds(&self, message_id: i64) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached("SELECT COUNT(DISTINCT emoji) FROM reactions WHERE message_id = ?1")? + .query_row([message_id], |r| r.get::<_, i64>(0)) + .map(|n| n as u64) + } + + /// Whether `uid` reacted with `emoji`. + pub fn has_reaction(&self, message_id: i64, emoji: &str, uid: &str) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached( + "SELECT 1 FROM reactions WHERE message_id = ?1 AND emoji = ?2 AND uid = ?3", + )? + .exists(params![message_id, emoji, uid]) + } + + /// Who reacted with `emoji`, first first. + pub fn reactors(&self, message_id: i64, emoji: &str) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached( + "SELECT uid, name FROM reactions WHERE message_id = ?1 AND emoji = ?2 ORDER BY ts_ms", + )?; + stmt.query_map(params![message_id, emoji], |r| Ok(user(r.get(0)?, r.get(1)?)))?.collect() + } + + // Pins + + /// Pin a message; `false` if it already was. + pub fn pin( + &self, + message_id: i64, + target: &ChatTarget, + by: &UserRef, + now_ms: i64, + ) -> rusqlite::Result { + let mut g = self.lock(); + let rev = g.next_rev(now_ms); + let tx = g.conn.transaction()?; + let added = tx + .prepare_cached( + "INSERT OR IGNORE INTO pins (message_id, target, by_uid, by_name, ts_ms) + VALUES (?1, ?2, ?3, ?4, ?5)", + )? + .execute(params![message_id, target_key(target), by.uid, by.name, now_ms])?; + if added > 0 { + Self::touch(&tx, message_id, rev)?; + } + tx.commit()?; + Ok(added > 0) + } + + /// Unpin a message; returns who had pinned it. + pub fn unpin(&self, message_id: i64, now_ms: i64) -> rusqlite::Result> { + let mut g = self.lock(); + let rev = g.next_rev(now_ms); + let tx = g.conn.transaction()?; + let by = tx + .prepare_cached("DELETE FROM pins WHERE message_id = ?1 RETURNING by_uid, by_name")? + .query_row([message_id], |r| Ok(user(r.get(0)?, r.get(1)?))) + .optional()?; + if by.is_some() { + Self::touch(&tx, message_id, rev)?; + } + tx.commit()?; + Ok(by) + } + + pub fn pin_info(&self, message_id: i64, me: Option<&str>) -> rusqlite::Result> { + let pin = self + .lock() + .conn + .prepare_cached("SELECT by_uid, by_name, ts_ms FROM pins WHERE message_id = ?1")? + .query_row([message_id], |r| Ok((user(r.get(0)?, r.get(1)?), r.get::<_, i64>(2)?))) + .optional()?; + let Some((by, ts_ms)) = pin else { return Ok(None) }; + Ok(self.message(message_id, me)?.map(|entry| PinInfo { entry, by, ts_ms })) + } + + /// Pins of a chat, newest first. + pub fn pins(&self, target: &ChatTarget, me: Option<&str>) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached(&format!( + "SELECT {MESSAGE_COLUMNS}, p.by_uid, p.by_name, p.ts_ms + FROM pins p JOIN messages m ON m.id = p.message_id + WHERE p.target = ?1 ORDER BY p.ts_ms DESC" + ))?; + let rows = stmt.query_map([target_key(target)], |r| { + Ok((entry_from_row(r)?, user(r.get(9)?, r.get(10)?), r.get::<_, i64>(11)?)) + })?; + let rows = rows.collect::>>()?; + let mut entries: Vec = rows.iter().map(|(e, ..)| e.clone()).collect(); + add_reactions(&g.conn, &mut entries, me)?; + Ok(entries + .into_iter() + .zip(rows) + .map(|(entry, (_, by, ts_ms))| PinInfo { entry, by, ts_ms }) + .collect()) + } + + pub fn pin_count(&self, target: &ChatTarget) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached("SELECT COUNT(*) FROM pins WHERE target = ?1")? + .query_row([target_key(target)], |r| r.get::<_, i64>(0)) + .map(|n| n as u64) + } + + // Topics + + pub fn create_topic( + &self, + target: &ChatTarget, + title: &str, + creator: &UserRef, + root_message_id: Option, + now_ms: i64, + ) -> rusqlite::Result { + let g = self.lock(); + g.conn + .prepare_cached( + "INSERT INTO topics (target, title, creator_uid, creator_name, created_ms, + root_message_id, last_activity_ms) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?5)", + )? + .execute(params![ + target_key(target), + title, + creator.uid, + creator.name, + now_ms, + root_message_id + ])?; + Ok(TopicInfo { + id: g.conn.last_insert_rowid(), + target: target.clone(), + title: title.to_string(), + creator: creator.clone(), + created_ms: now_ms, + root_message_id, + last_activity_ms: now_ms, + message_count: 0, + archived: false, + }) + } + + pub fn topic(&self, id: i64) -> rusqlite::Result> { + self.lock() + .conn + .prepare_cached(&format!("SELECT {TOPIC_COLUMNS} FROM topics WHERE id = ?1"))? + .query_row([id], topic_from_row) + .optional() + } + + pub fn update_topic( + &self, + id: i64, + title: Option<&str>, + archived: Option, + ) -> rusqlite::Result> { + self.lock() + .conn + .prepare_cached( + "UPDATE topics SET title = COALESCE(?2, title), archived = COALESCE(?3, archived) + WHERE id = ?1", + )? + .execute(params![id, title, archived])?; + self.topic(id) + } + + /// Most recently active first. + pub fn topics( + &self, + target: &ChatTarget, + include_archived: bool, + ) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached(&format!( + "SELECT {TOPIC_COLUMNS} FROM topics WHERE target = ?1 AND (?2 OR archived = 0) + ORDER BY last_activity_ms DESC" + ))?; + stmt.query_map(params![target_key(target), include_archived], topic_from_row)?.collect() + } + + /// Open topics in a chat. + pub fn open_topic_count(&self, target: &ChatTarget) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached("SELECT COUNT(*) FROM topics WHERE target = ?1 AND archived = 0")? + .query_row([target_key(target)], |r| r.get::<_, i64>(0)) + .map(|n| n as u64) + } + + /// The most recently active open topic with this title. + pub fn topic_by_title( + &self, + target: &ChatTarget, + title: &str, + ) -> rusqlite::Result> { + self.lock() + .conn + .prepare_cached(&format!( + "SELECT {TOPIC_COLUMNS} FROM topics WHERE target = ?1 AND title = ?2 AND archived = 0 + ORDER BY last_activity_ms DESC LIMIT 1" + ))? + .query_row(params![target_key(target), title], topic_from_row) + .optional() + } +} + +fn reaction_count(conn: &Connection, message_id: i64, emoji: &str) -> rusqlite::Result { + conn.prepare_cached("SELECT COUNT(*) FROM reactions WHERE message_id = ?1 AND emoji = ?2")? + .query_row(params![message_id, emoji], |r| r.get(0)) +} diff --git a/crates/voelin-gateway/src/db/events.rs b/crates/voelin-gateway/src/db/events.rs new file mode 100644 index 0000000..b0e1156 --- /dev/null +++ b/crates/voelin-gateway/src/db/events.rs @@ -0,0 +1,317 @@ +//! Scheduled events and RSVPs. + +use rusqlite::{OptionalExtension, Row, ToSql, params}; +use voelin_gateway_proto::{Attendee, EventInfo, EventKind, EventSpec, RsvpStatus, UserRef}; + +use super::{Db, user}; + +const EVENT_COLUMNS: &str = "e.id, e.title, e.description, e.start_ms, e.end_ms, e.channel, \ + e.kind, e.stream_title, e.stream_game, e.host_uid, e.creator_uid, e.creator_name, \ + e.created_ms, e.updated_ms, e.live_stream, \ + (SELECT COUNT(*) FROM rsvps r WHERE r.event_id = e.id AND r.status = 'going'), \ + (SELECT COUNT(*) FROM rsvps r WHERE r.event_id = e.id AND r.status = 'maybe'), \ + (SELECT COUNT(*) FROM rsvps r WHERE r.event_id = e.id AND r.status = 'not_going'), \ + (SELECT status FROM rsvps r WHERE r.event_id = e.id AND r.uid = :me)"; + +fn kind_str(kind: EventKind) -> &'static str { + match kind { + EventKind::Stream => "stream", + EventKind::General | EventKind::Unknown => "general", + } +} + +fn event_from_row(r: &Row) -> rusqlite::Result { + let kind: String = r.get(6)?; + let my: Option = r.get(18)?; + Ok(EventInfo { + id: r.get(0)?, + spec: EventSpec { + title: r.get(1)?, + description: r.get(2)?, + start_ms: r.get(3)?, + end_ms: r.get(4)?, + channel: r.get::<_, Option>(5)?.map(|c| c as u64), + kind: if kind == "stream" { EventKind::Stream } else { EventKind::General }, + stream_title: r.get(7)?, + stream_game: r.get(8)?, + host_uid: Some(r.get(9)?), + }, + creator: user(r.get(10)?, r.get(11)?), + created_ms: r.get(12)?, + updated_ms: r.get(13)?, + live_stream: r.get(14)?, + going: r.get(15)?, + maybe: r.get(16)?, + not_going: r.get(17)?, + my_rsvp: my.as_deref().map(RsvpStatus::parse), + attendees: Vec::new(), + }) +} + +/// Which events [`Db::events`] returns. +#[derive(Clone, Debug, Default)] +pub struct EventFilter { + /// Events that end (or start, without an end) at or after this. + pub from_ms: i64, + pub to_ms: Option, + pub channel: Option, + pub limit: Option, +} + +impl EventFilter { + pub fn sql(&self) -> String { + let mut conds = vec!["COALESCE(e.end_ms, e.start_ms) >= :from"]; + if self.to_ms.is_some() { + conds.push("e.start_ms < :to"); + } + if self.channel.is_some() { + conds.push("e.channel = :channel"); + } + format!( + "SELECT {EVENT_COLUMNS} FROM events e WHERE {} ORDER BY +e.start_ms, e.id LIMIT :limit", + conds.join(" AND ") + ) + } +} + +impl Db { + pub fn create_event( + &self, + spec: &EventSpec, + creator: &UserRef, + now_ms: i64, + ) -> rusqlite::Result { + let id = { + let g = self.lock(); + g.conn + .prepare_cached( + "INSERT INTO events (title, description, start_ms, end_ms, channel, kind, + stream_title, stream_game, host_uid, creator_uid, creator_name, + created_ms, updated_ms) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?12)", + )? + .execute(params![ + spec.title, + spec.description, + spec.start_ms, + spec.end_ms, + spec.channel.map(|c| c as i64), + kind_str(spec.kind), + spec.stream_title, + spec.stream_game, + spec.host_uid.as_deref().unwrap_or(&creator.uid), + creator.uid, + creator.name, + now_ms + ])?; + g.conn.last_insert_rowid() + }; + Ok(self.event(id, Some(&creator.uid), false)?.expect("just inserted")) + } + + /// Replace what the creator set; `None` if there is no such event. + pub fn update_event( + &self, + id: i64, + spec: &EventSpec, + now_ms: i64, + ) -> rusqlite::Result> { + let changed = self + .lock() + .conn + .prepare_cached( + "UPDATE events SET title = ?2, description = ?3, start_ms = ?4, end_ms = ?5, + channel = ?6, kind = ?7, stream_title = ?8, stream_game = ?9, + host_uid = COALESCE(?10, host_uid), updated_ms = ?11 + WHERE id = ?1", + )? + .execute(params![ + id, + spec.title, + spec.description, + spec.start_ms, + spec.end_ms, + spec.channel.map(|c| c as i64), + kind_str(spec.kind), + spec.stream_title, + spec.stream_game, + spec.host_uid, + now_ms + ])?; + if changed == 0 { + return Ok(None); + } + // Reminders follow the new start time. + self.lock() + .conn + .prepare_cached("DELETE FROM event_notices WHERE event_id = ?1")? + .execute([id])?; + self.event(id, None, false) + } + + pub fn delete_event(&self, id: i64) -> rusqlite::Result { + let mut g = self.lock(); + let tx = g.conn.transaction()?; + let n = tx.prepare_cached("DELETE FROM events WHERE id = ?1")?.execute([id])?; + tx.prepare_cached("DELETE FROM rsvps WHERE event_id = ?1")?.execute([id])?; + tx.prepare_cached("DELETE FROM event_notices WHERE event_id = ?1")?.execute([id])?; + tx.commit()?; + Ok(n > 0) + } + + /// One event with RSVP counts, `me`'s answer and optionally all attendees. + pub fn event( + &self, + id: i64, + me: Option<&str>, + attendees: bool, + ) -> rusqlite::Result> { + let g = self.lock(); + let event = g + .conn + .prepare_cached(&format!("SELECT {EVENT_COLUMNS} FROM events e WHERE e.id = :id"))? + .query_row(&[(":id", &id as &dyn ToSql), (":me", &me)], event_from_row) + .optional()?; + let Some(mut event) = event else { return Ok(None) }; + if attendees { + let mut stmt = g.conn.prepare_cached( + "SELECT uid, name, status, ts_ms FROM rsvps WHERE event_id = ?1 ORDER BY ts_ms", + )?; + event.attendees = stmt + .query_map([id], |r| { + Ok(Attendee { + user: user(r.get(0)?, r.get(1)?), + status: RsvpStatus::parse(&r.get::<_, String>(2)?), + ts_ms: r.get(3)?, + }) + })? + .collect::>()?; + } + Ok(Some(event)) + } + + /// Events by start time. + pub fn events( + &self, + filter: &EventFilter, + me: Option<&str>, + ) -> rusqlite::Result> { + let g = self.lock(); + let limit = filter.limit.map_or(-1, i64::from); + let channel = filter.channel.map(|c| c as i64); + let mut named: Vec<(&str, &dyn ToSql)> = + vec![(":from", &filter.from_ms), (":limit", &limit), (":me", &me)]; + if let Some(to) = &filter.to_ms { + named.push((":to", to)); + } + if let Some(c) = &channel { + named.push((":channel", c)); + } + let mut stmt = g.conn.prepare_cached(&filter.sql())?; + stmt.query_map(named.as_slice(), event_from_row)?.collect() + } + + /// Events starting in `(after_ms, until_ms]`. + pub fn events_starting( + &self, + after_ms: i64, + until_ms: i64, + ) -> rusqlite::Result> { + let g = self.lock(); + let me: Option<&str> = None; + let mut stmt = g.conn.prepare_cached(&format!( + "SELECT {EVENT_COLUMNS} FROM events e WHERE e.start_ms > :after AND e.start_ms <= :until + ORDER BY e.start_ms" + ))?; + stmt.query_map( + &[(":after", &after_ms as &dyn ToSql), (":until", &until_ms), (":me", &me)], + event_from_row, + )? + .collect() + } + + /// Upcoming events created by `uid`. + pub fn upcoming_events_by(&self, uid: &str, now_ms: i64) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached( + "SELECT COUNT(*) FROM events WHERE creator_uid = ?1 AND start_ms >= ?2", + )? + .query_row(params![uid, now_ms], |r| r.get::<_, i64>(0)) + .map(|n| n as u64) + } + + /// Set (`Some`) or withdraw an answer. + pub fn rsvp( + &self, + event_id: i64, + by: &UserRef, + status: Option, + now_ms: i64, + ) -> rusqlite::Result<()> { + let g = self.lock(); + match status { + Some(status) => g + .conn + .prepare_cached( + "INSERT INTO rsvps (event_id, uid, name, status, ts_ms) VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT (event_id, uid) DO UPDATE SET name = excluded.name, + status = excluded.status, ts_ms = excluded.ts_ms", + )? + .execute(params![event_id, by.uid, by.name, status.as_str(), now_ms])?, + None => g + .conn + .prepare_cached("DELETE FROM rsvps WHERE event_id = ?1 AND uid = ?2")? + .execute(params![event_id, by.uid])?, + }; + Ok(()) + } + + /// Record that a reminder was sent; `false` if it already was. + pub fn mark_notice(&self, event_id: i64, offset_min: i64) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached( + "INSERT OR IGNORE INTO event_notices (event_id, offset_min) VALUES (?1, ?2)", + )? + .execute(params![event_id, offset_min]) + .map(|n| n > 0) + } + + /// Stream events of `host_uid` that are not live and whose window + /// (`start - window` to `end + window`) contains `now_ms`. + pub fn linkable_events( + &self, + host_uid: &str, + now_ms: i64, + window_ms: i64, + ) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached( + "SELECT id FROM events WHERE host_uid = ?1 AND start_ms <= ?2 + ?3 + AND COALESCE(end_ms, start_ms) + ?3 >= ?2 AND kind = 'stream' + AND live_stream IS NULL ORDER BY start_ms", + )?; + stmt.query_map(params![host_uid, now_ms, window_ms], |r| r.get(0))?.collect() + } + + /// Events currently linked to a stream. + pub fn events_with_stream(&self, stream: &str) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached("SELECT id FROM events WHERE live_stream = ?1")?; + stmt.query_map([stream], |r| r.get(0))?.collect() + } + + pub fn set_live_stream( + &self, + event_id: i64, + stream: Option<&str>, + now_ms: i64, + ) -> rusqlite::Result<()> { + self.lock() + .conn + .prepare_cached("UPDATE events SET live_stream = ?2, updated_ms = ?3 WHERE id = ?1")? + .execute(params![event_id, stream, now_ms])?; + Ok(()) + } +} diff --git a/crates/voelin-gateway/src/db/feed.rs b/crates/voelin-gateway/src/db/feed.rs new file mode 100644 index 0000000..0e9794c --- /dev/null +++ b/crates/voelin-gateway/src/db/feed.rs @@ -0,0 +1,116 @@ +//! The stream directory and the activity feed. + +use rusqlite::params; +use serde_json::Value; +use voelin_gateway_proto::{ActivityEntry, StreamEntry, UserRef}; +use voelin_model::ChannelId; + +use super::{Db, user}; + +/// An activity entry before it is stored. +#[derive(Clone, Debug, Default)] +pub struct NewActivity<'a> { + pub kind: &'a str, + pub actor: Option<&'a UserRef>, + pub channel: Option, + pub ref_id: Option, + pub text: String, + pub data: Value, +} + +impl Db { + pub fn save_stream(&self, entry: &StreamEntry) -> rusqlite::Result<()> { + let data = serde_json::to_string(entry).expect("serializable"); + self.lock() + .conn + .prepare_cached("INSERT OR REPLACE INTO streams (id, data) VALUES (?1, ?2)")? + .execute(params![entry.id, data])?; + Ok(()) + } + + pub fn delete_stream(&self, id: &str) -> rusqlite::Result<()> { + self.lock().conn.prepare_cached("DELETE FROM streams WHERE id = ?1")?.execute([id])?; + Ok(()) + } + + /// The stored directory (entries that no longer parse are skipped). + pub fn streams(&self) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached("SELECT data FROM streams")?; + let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; + Ok(rows.filter_map(|r| r.ok()).filter_map(|d| serde_json::from_str(&d).ok()).collect()) + } + + pub fn add_activity(&self, a: NewActivity<'_>, ts_ms: i64) -> rusqlite::Result { + let g = self.lock(); + let data = (!a.data.is_null()).then(|| a.data.to_string()); + g.conn + .prepare_cached( + "INSERT INTO activity (ts_ms, kind, actor_uid, actor_name, channel, ref_id, text, data) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + )? + .execute(params![ + ts_ms, + a.kind, + a.actor.map(|u| &u.uid), + a.actor.map(|u| &u.name), + a.channel.map(|c| c as i64), + a.ref_id, + a.text, + data + ])?; + Ok(ActivityEntry { + id: g.conn.last_insert_rowid(), + ts_ms, + kind: a.kind.to_string(), + actor: a.actor.cloned(), + channel: a.channel, + ref_id: a.ref_id, + text: a.text, + data: a.data, + }) + } + + /// Newest first, below id `before`; and whether older entries exist. + pub fn activity( + &self, + before: Option, + limit: Option, + ) -> rusqlite::Result<(Vec, bool)> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached( + "SELECT id, ts_ms, kind, actor_uid, actor_name, channel, ref_id, text, data + FROM activity WHERE id < ?1 ORDER BY id DESC LIMIT ?2", + )?; + let limit_sql = limit.map_or(-1, |l| i64::from(l) + 1); + let mut entries = stmt + .query_map(params![before.unwrap_or(i64::MAX), limit_sql], |r| { + let actor_uid: Option = r.get(3)?; + let actor_name: Option = r.get(4)?; + let data: Option = r.get(8)?; + Ok(ActivityEntry { + id: r.get(0)?, + ts_ms: r.get(1)?, + kind: r.get(2)?, + actor: actor_uid.map(|uid| user(uid, actor_name.unwrap_or_default())), + channel: r.get::<_, Option>(5)?.map(|c| c as u64), + ref_id: r.get(6)?, + text: r.get(7)?, + data: data.and_then(|d| serde_json::from_str(&d).ok()).unwrap_or(Value::Null), + }) + })? + .collect::>>()?; + let has_more = limit.is_some_and(|l| entries.len() > l as usize); + if has_more { + entries.pop(); + } + Ok((entries, has_more)) + } + + pub fn prune_activity(&self, cutoff_ms: i64) -> rusqlite::Result { + self.lock() + .conn + .prepare_cached("DELETE FROM activity WHERE ts_ms < ?1")? + .execute([cutoff_ms]) + } +} diff --git a/crates/voelin-gateway/src/db/mod.rs b/crates/voelin-gateway/src/db/mod.rs new file mode 100644 index 0000000..4191140 --- /dev/null +++ b/crates/voelin-gateway/src/db/mod.rs @@ -0,0 +1,369 @@ +//! SQLite: login tokens, chat history with pins, reactions and topics, +//! events, the stream directory, the activity feed, runtime settings and +//! the audit log. +//! +//! The schema is versioned (`PRAGMA user_version`) and migrated in place on +//! open, keeping existing data. WAL journal, statement cache, one +//! transaction per logical change. + +mod chat; +mod events; +mod feed; + +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use rusqlite::{Connection, OptionalExtension, params}; +use serde_json::Value; +use voelin_gateway_proto::UserRef; +use voelin_model::ChatTarget; + +pub use chat::HistoryOptions; +pub use events::EventFilter; +pub use feed::NewActivity; + +pub struct Db(Mutex); + +struct Inner { + conn: Connection, + /// Last revision handed out; see [`Inner::next_rev`]. + rev: i64, +} + +impl Inner { + /// Revisions order changes to messages across restarts: at least the + /// current time in microseconds, and always increasing. + fn next_rev(&mut self, now_ms: i64) -> i64 { + self.rev = (self.rev + 1).max(now_ms.saturating_mul(1000)); + self.rev + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TokenInfo { + pub uid: String, + pub cldbid: u64, + pub expires: i64, +} + +pub fn target_key(target: &ChatTarget) -> String { + match target { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel/{cid}"), + ChatTarget::Private(uid) => format!("private/{uid}"), + } +} + +pub fn parse_target(key: &str) -> ChatTarget { + match key.split_once('/') { + Some(("channel", cid)) => ChatTarget::Channel(cid.parse().unwrap_or_default()), + Some(("private", uid)) => ChatTarget::Private(uid.to_string()), + _ => ChatTarget::Server, + } +} + +fn user(uid: String, name: String) -> UserRef { + UserRef { uid, name } +} + +/// The original schema (before versioning), kept so a new database and an +/// old one migrate the same way. +const SCHEMA_0: &str = " +CREATE TABLE IF NOT EXISTS tokens ( + hash TEXT PRIMARY KEY, + uid TEXT NOT NULL, + cldbid INTEGER NOT NULL, + expires INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY, + target TEXT NOT NULL, + ts_ms INTEGER NOT NULL, + author_uid TEXT, + author_name TEXT NOT NULL, + text TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS messages_by_target ON messages (target, id); +CREATE TABLE IF NOT EXISTS audit ( + ts INTEGER NOT NULL, + uid TEXT, + action TEXT NOT NULL, + detail TEXT +);"; + +/// `MIGRATIONS[n]` takes the schema from version `n` to `n + 1`. +const MIGRATIONS: &[&str] = &[" +-- Messages: ids that are never reused (AUTOINCREMENT), topics, revisions. +CREATE TABLE messages_v1 ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + target TEXT NOT NULL, + ts_ms INTEGER NOT NULL, + author_uid TEXT, + author_name TEXT NOT NULL, + text TEXT NOT NULL, + topic_id INTEGER, + rev INTEGER NOT NULL +); +INSERT INTO messages_v1 (id, target, ts_ms, author_uid, author_name, text, rev) + SELECT id, target, ts_ms, author_uid, author_name, text, id FROM messages; +DROP TABLE messages; +ALTER TABLE messages_v1 RENAME TO messages; +CREATE INDEX messages_by_target ON messages (target, id); +CREATE INDEX messages_main ON messages (target, id) WHERE topic_id IS NULL; +CREATE INDEX messages_by_topic ON messages (topic_id, id) WHERE topic_id IS NOT NULL; +CREATE INDEX messages_by_time ON messages (target, ts_ms); +CREATE INDEX messages_by_rev ON messages (target, rev); +CREATE INDEX messages_ts ON messages (ts_ms); + +CREATE TABLE reactions ( + message_id INTEGER NOT NULL, + emoji TEXT NOT NULL, + uid TEXT NOT NULL, + name TEXT NOT NULL, + ts_ms INTEGER NOT NULL, + PRIMARY KEY (message_id, emoji, uid) +) WITHOUT ROWID; + +CREATE TABLE pins ( + message_id INTEGER PRIMARY KEY, + target TEXT NOT NULL, + by_uid TEXT NOT NULL, + by_name TEXT NOT NULL, + ts_ms INTEGER NOT NULL +); +CREATE INDEX pins_by_target ON pins (target, ts_ms); + +CREATE TABLE topics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + target TEXT NOT NULL, + title TEXT NOT NULL, + creator_uid TEXT NOT NULL, + creator_name TEXT NOT NULL, + created_ms INTEGER NOT NULL, + root_message_id INTEGER, + last_activity_ms INTEGER NOT NULL, + message_count INTEGER NOT NULL DEFAULT 0, + archived INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX topics_by_target ON topics (target, last_activity_ms); +CREATE INDEX topics_by_title ON topics (target, title); +CREATE INDEX topics_by_activity ON topics (last_activity_ms); + +CREATE TABLE events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + description TEXT NOT NULL, + start_ms INTEGER NOT NULL, + end_ms INTEGER, + channel INTEGER, + kind TEXT NOT NULL, + stream_title TEXT, + stream_game TEXT, + host_uid TEXT NOT NULL, + creator_uid TEXT NOT NULL, + creator_name TEXT NOT NULL, + created_ms INTEGER NOT NULL, + updated_ms INTEGER NOT NULL, + live_stream TEXT +); +CREATE INDEX events_by_start ON events (start_ms); +CREATE INDEX events_by_end ON events (COALESCE(end_ms, start_ms)); +CREATE INDEX events_by_channel ON events (channel, start_ms); +CREATE INDEX events_by_creator ON events (creator_uid, start_ms); +CREATE INDEX events_by_host ON events (host_uid, start_ms); +CREATE INDEX events_by_stream ON events (live_stream) WHERE live_stream IS NOT NULL; + +CREATE TABLE rsvps ( + event_id INTEGER NOT NULL, + uid TEXT NOT NULL, + name TEXT NOT NULL, + status TEXT NOT NULL, + ts_ms INTEGER NOT NULL, + PRIMARY KEY (event_id, uid) +) WITHOUT ROWID; + +-- Reminders already sent: (event, minutes before the start). +CREATE TABLE event_notices ( + event_id INTEGER NOT NULL, + offset_min INTEGER NOT NULL, + PRIMARY KEY (event_id, offset_min) +) WITHOUT ROWID; + +-- The stream directory, so it survives a restart (JSON of StreamEntry). +CREATE TABLE streams ( + id TEXT PRIMARY KEY, + data TEXT NOT NULL +) WITHOUT ROWID; + +CREATE TABLE activity ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts_ms INTEGER NOT NULL, + kind TEXT NOT NULL, + actor_uid TEXT, + actor_name TEXT, + channel INTEGER, + ref_id TEXT, + text TEXT NOT NULL, + data TEXT +); +CREATE INDEX activity_by_time ON activity (ts_ms); + +-- Settings changed at runtime (JSON values); they win over the file. +CREATE TABLE config ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_ms INTEGER NOT NULL, + updated_by TEXT +) WITHOUT ROWID; + +CREATE INDEX tokens_by_expiry ON tokens (expires); +CREATE INDEX audit_by_time ON audit (ts); +"]; + +/// Current schema version. +pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64; + +fn now_ms() -> i64 { + crate::hub::now_ms() +} + +impl Db { + pub fn open(path: &Path) -> rusqlite::Result { + Self::init(Connection::open(path)?) + } + + #[cfg(test)] + pub fn in_memory() -> rusqlite::Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(mut conn: Connection) -> rusqlite::Result { + conn.pragma_update(None, "journal_mode", "WAL")?; + // Safe with WAL: a crash loses at most the last transactions, never + // consistency. + conn.pragma_update(None, "synchronous", "NORMAL")?; + conn.set_prepared_statement_cache_capacity(128); + migrate(&mut conn)?; + let rev: i64 = + conn.query_row("SELECT COALESCE(MAX(rev), 0) FROM messages", [], |r| r.get(0))?; + Ok(Self(Mutex::new(Inner { conn, rev }))) + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.0.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn schema_version(&self) -> rusqlite::Result { + self.lock().conn.pragma_query_value(None, "user_version", |r| r.get(0)) + } + + pub fn add_token(&self, hash: &str, info: &TokenInfo) -> rusqlite::Result<()> { + self.lock() + .conn + .prepare_cached( + "INSERT OR REPLACE INTO tokens (hash, uid, cldbid, expires) VALUES (?1, ?2, ?3, ?4)", + )? + .execute(params![hash, info.uid, info.cldbid as i64, info.expires])?; + Ok(()) + } + + /// A token that has not expired at `now`. + pub fn token(&self, hash: &str, now: i64) -> rusqlite::Result> { + self.lock() + .conn + .prepare_cached( + "SELECT uid, cldbid, expires FROM tokens WHERE hash = ?1 AND expires > ?2", + )? + .query_row(params![hash, now], |r| { + Ok(TokenInfo { + uid: r.get(0)?, + cldbid: r.get::<_, i64>(1)? as u64, + expires: r.get(2)?, + }) + }) + .optional() + } + + /// Drop expired tokens. + pub fn prune_tokens(&self, now: i64) -> rusqlite::Result { + self.lock().conn.prepare_cached("DELETE FROM tokens WHERE expires < ?1")?.execute([now]) + } + + pub fn audit(&self, now: i64, uid: Option<&str>, action: &str, detail: &str) { + let result = self + .lock() + .conn + .prepare_cached("INSERT INTO audit (ts, uid, action, detail) VALUES (?1, ?2, ?3, ?4)") + .and_then(|mut s| s.execute(params![now, uid, action, detail])); + if let Err(error) = result { + tracing::warn!(%error, "failed to write audit log"); + } + } + + /// Settings stored at runtime. + pub fn config_values(&self) -> rusqlite::Result> { + let g = self.lock(); + let mut stmt = g.conn.prepare_cached("SELECT key, value FROM config ORDER BY key")?; + let rows = stmt.query_map([], |r| { + let text: String = r.get(1)?; + Ok((r.get(0)?, serde_json::from_str(&text).unwrap_or(Value::Null))) + })?; + rows.collect() + } + + pub fn set_config(&self, key: &str, value: &Value, by: Option<&str>) -> rusqlite::Result<()> { + self.lock() + .conn + .prepare_cached( + "INSERT INTO config (key, value, updated_ms, updated_by) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT (key) DO UPDATE SET value = excluded.value, + updated_ms = excluded.updated_ms, updated_by = excluded.updated_by", + )? + .execute(params![key, value.to_string(), now_ms(), by])?; + Ok(()) + } + + pub fn delete_config(&self, key: &str) -> rusqlite::Result<()> { + self.lock().conn.prepare_cached("DELETE FROM config WHERE key = ?1")?.execute([key])?; + Ok(()) + } + + /// `EXPLAIN QUERY PLAN` details, for tests of index use. + #[cfg(test)] + pub fn query_plan(&self, sql: &str) -> Vec { + let g = self.lock(); + let mut stmt = g.conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap(); + // Unbound parameters are fine for a plan. + let mut rows = stmt.raw_query(); + let mut out = Vec::new(); + while let Some(r) = rows.next().unwrap() { + out.push(r.get::<_, String>(3).unwrap()); + } + out + } + + #[cfg(test)] + fn with_conn(&self, f: impl FnOnce(&Connection) -> T) -> T { + f(&self.lock().conn) + } +} + +fn migrate(conn: &mut Connection) -> rusqlite::Result<()> { + let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?; + if version >= SCHEMA_VERSION { + return Ok(()); + } + let tx = conn.transaction()?; + if version == 0 { + tx.execute_batch(SCHEMA_0)?; + } + for (i, step) in MIGRATIONS.iter().enumerate().skip(version as usize) { + tx.execute_batch(step)?; + tx.pragma_update(None, "user_version", i as i64 + 1)?; + tracing::info!(from = i, to = i + 1, "migrated database"); + } + tx.commit() +} + +#[cfg(test)] +mod tests; diff --git a/crates/voelin-gateway/src/db/tests.rs b/crates/voelin-gateway/src/db/tests.rs new file mode 100644 index 0000000..7cc643f --- /dev/null +++ b/crates/voelin-gateway/src/db/tests.rs @@ -0,0 +1,449 @@ +use std::time::Instant; + +use serde_json::json; +use voelin_gateway_proto::{EventKind, EventSpec, RsvpStatus, StreamEntry, StreamSource, UserRef}; +use voelin_model::{ChatMessage, ChatTarget}; + +use super::*; + +fn msg(target: ChatTarget, text: &str, ts_ms: i64) -> ChatMessage { + ChatMessage { + target, + author_name: "a".into(), + author_uid: Some("u".into()), + author_id: None, + text: text.into(), + ts_ms, + via_relay: true, + } +} + +fn alice() -> UserRef { + UserRef { uid: "alice".into(), name: "Alice".into() } +} + +fn bob() -> UserRef { + UserRef { uid: "bob".into(), name: "Bob".into() } +} + +fn texts(entries: &[voelin_gateway_proto::HistoryEntry]) -> Vec<&str> { + entries.iter().map(|e| e.message.text.as_str()).collect() +} + +const CH1: ChatTarget = ChatTarget::Channel(1); + +#[test] +fn tokens_expire() { + let db = Db::in_memory().unwrap(); + let info = TokenInfo { uid: "u".into(), cldbid: 5, expires: 100 }; + db.add_token("h", &info).unwrap(); + assert_eq!(db.token("h", 50).unwrap(), Some(info)); + assert_eq!(db.token("h", 150).unwrap(), None); + assert_eq!(db.token("x", 50).unwrap(), None); + assert_eq!(db.prune_tokens(150).unwrap(), 1); +} + +#[test] +fn migrates_the_original_schema() { + // A database as the first gateway version left it. + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE tokens (hash TEXT PRIMARY KEY, uid TEXT NOT NULL, cldbid INTEGER NOT NULL, + expires INTEGER NOT NULL); + CREATE TABLE messages (id INTEGER PRIMARY KEY, target TEXT NOT NULL, ts_ms INTEGER NOT NULL, + author_uid TEXT, author_name TEXT NOT NULL, text TEXT NOT NULL); + CREATE INDEX messages_by_target ON messages (target, id); + CREATE TABLE audit (ts INTEGER NOT NULL, uid TEXT, action TEXT NOT NULL, detail TEXT); + INSERT INTO tokens VALUES ('h', 'u', 5, 9999999999); + INSERT INTO messages VALUES (7, 'channel/1', 1000, 'u', 'Alice', 'old one'); + INSERT INTO messages VALUES (9, 'server', 2000, NULL, 'Bob', 'old two'); + INSERT INTO audit VALUES (1, 'u', 'login', 'signature');", + ) + .unwrap(); + let db = Db::init(conn).unwrap(); + assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION); + assert_eq!(db.token("h", 0).unwrap().unwrap().cldbid, 5); + let (page, _) = db.history(&CH1, &HistoryOptions::default(), None).unwrap(); + assert_eq!(page.len(), 1); + assert_eq!((page[0].id, page[0].message.text.as_str(), page[0].rev), (7, "old one", 7)); + assert_eq!(page[0].message.author_name, "Alice"); + let server = db.message(9, None).unwrap().unwrap(); + assert_eq!((server.message.target, server.message.author_uid), (ChatTarget::Server, None)); + assert_eq!( + db.with_conn(|c| c.query_row("SELECT COUNT(*) FROM audit", [], |r| r.get::<_, i64>(0))) + .unwrap(), + 1 + ); + // New messages continue after the old ids, with larger revisions. + let new = db.add_message(msg(CH1, "new", 3000), None).unwrap(); + assert!(new.id > 9 && new.rev > 9); + // Opening again is a no-op. + let conn = db.0.into_inner().unwrap().conn; + let db = Db::init(conn).unwrap(); + assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION); + assert_eq!(db.history(&CH1, &HistoryOptions::default(), None).unwrap().0.len(), 2); +} + +#[test] +fn ids_are_never_reused() { + let db = Db::in_memory().unwrap(); + let first = db.add_message(msg(CH1, "a", 1), None).unwrap(); + assert_eq!(db.prune_messages(10).unwrap(), 1); + let second = db.add_message(msg(CH1, "b", 20), None).unwrap(); + assert!(second.id > first.id); + assert!(second.rev > first.rev); +} + +#[test] +fn history_pages_per_target() { + let db = Db::in_memory().unwrap(); + for i in 0..5 { + db.add_message(msg(CH1, &format!("c{i}"), i), None).unwrap(); + db.add_message(msg(ChatTarget::Server, &format!("s{i}"), i), None).unwrap(); + } + let opts = |limit| HistoryOptions { limit: Some(limit), ..Default::default() }; + let (last, more) = db.history(&CH1, &opts(2), None).unwrap(); + assert_eq!(texts(&last), ["c3", "c4"]); + assert!(more); + let before = HistoryOptions { before: Some(last[0].id), ..opts(10) }; + let (older, more) = db.history(&CH1, &before, None).unwrap(); + assert_eq!(texts(&older), ["c0", "c1", "c2"]); + assert!(!more); + let after = HistoryOptions { after: Some(older[0].id), ..opts(2) }; + let (newer, more) = db.history(&CH1, &after, None).unwrap(); + assert_eq!(texts(&newer), ["c1", "c2"]); + assert!(more); + let both = HistoryOptions { + after: Some(older[0].id), + before: Some(last[1].id), + limit: None, + ..Default::default() + }; + assert_eq!(texts(&db.history(&CH1, &both, None).unwrap().0), ["c1", "c2", "c3"]); + // Time cursors. + let since = HistoryOptions { after_ms: Some(2), ..Default::default() }; + assert_eq!(texts(&db.history(&CH1, &since, None).unwrap().0), ["c3", "c4"]); + let until = HistoryOptions { before_ms: Some(2), ..Default::default() }; + assert_eq!(texts(&db.history(&CH1, &until, None).unwrap().0), ["c0", "c1"]); + let none = HistoryOptions { after_ms: Some(99), ..Default::default() }; + assert!(db.history(&CH1, &none, None).unwrap().0.is_empty()); + assert_eq!(db.history(&ChatTarget::Server, &opts(10), None).unwrap().0.len(), 5); + db.prune_messages(10).unwrap(); + assert!(db.history(&ChatTarget::Server, &opts(10), None).unwrap().0.is_empty()); +} + +/// More than 10k messages: no cap on page size, cursors in both directions, +/// topics, and every query path on an index. +#[test] +fn large_history_without_caps() { + let db = Db::in_memory().unwrap(); + let topic = db.create_topic(&CH1, "big", &alice(), None, 0).unwrap(); + let n = 12_000; + let start = Instant::now(); + let batch: Vec<_> = (0..n) + .map(|i| { + let target = if i % 3 == 2 { ChatTarget::Server } else { CH1 }; + let topic_id = (i % 5 == 0 && target == CH1).then_some(topic.id); + (msg(target, &format!("m{i}"), i as i64), topic_id) + }) + .collect(); + db.add_messages(batch).unwrap(); + let inserted = start.elapsed(); + let ch1 = (0..n).filter(|i| i % 3 != 2).count(); + let in_topic = (0..n).filter(|i| i % 3 != 2 && i % 5 == 0).count(); + + let start = Instant::now(); + let (all, more) = db.history(&CH1, &HistoryOptions::default(), None).unwrap(); + assert_eq!(all.len(), ch1); + assert!(!more); + assert!(all.windows(2).all(|w| w[0].id < w[1].id)); + + // Walk backwards and forwards in pages of 1000. + let mut seen = 0; + let mut before = None; + loop { + let opts = HistoryOptions { before, limit: Some(1000), ..Default::default() }; + let (page, more) = db.history(&CH1, &opts, None).unwrap(); + seen += page.len(); + before = page.first().map(|e| e.id); + if !more { + break; + } + } + assert_eq!(seen, ch1); + let mut seen = 0; + let mut after = Some(0); + loop { + let opts = HistoryOptions { after, limit: Some(1000), ..Default::default() }; + let (page, more) = db.history(&CH1, &opts, None).unwrap(); + seen += page.len(); + after = page.last().map(|e| e.id); + if !more { + break; + } + } + assert_eq!(seen, ch1); + + let topic_opts = HistoryOptions { topic: Some(topic.id), ..Default::default() }; + let (topic_page, _) = db.history(&CH1, &topic_opts, None).unwrap(); + assert_eq!(topic_page.len(), in_topic); + assert!(topic_page.iter().all(|e| e.topic_id == Some(topic.id))); + let main = HistoryOptions { exclude_topics: true, ..Default::default() }; + assert_eq!(db.history(&CH1, &main, None).unwrap().0.len(), ch1 - in_topic); + let t = db.topic(topic.id).unwrap().unwrap(); + assert_eq!(t.message_count as usize, in_topic); + let (since, _) = db.sync(&CH1, all[ch1 - 10].rev, None, None).unwrap(); + assert_eq!(since.len(), 9); + let queried = start.elapsed(); + eprintln!("{n} messages: insert {inserted:?}, queries {queried:?}"); + + // Every shape of history query runs on an index. + let shapes = [ + HistoryOptions::default(), + HistoryOptions { before: Some(1), ..Default::default() }, + HistoryOptions { after: Some(1), ..Default::default() }, + HistoryOptions { before: Some(1), after: Some(1), ..Default::default() }, + HistoryOptions { topic: Some(1), ..Default::default() }, + HistoryOptions { topic: Some(1), after: Some(1), ..Default::default() }, + HistoryOptions { exclude_topics: true, before: Some(1), ..Default::default() }, + ]; + for shape in shapes { + assert_indexed(&db, &shape.sql()); + } + for sql in [ + "SELECT id FROM messages WHERE target = ?1 AND ts_ms > ?2 ORDER BY ts_ms, id LIMIT 1", + "SELECT id FROM messages WHERE target = ?1 AND ts_ms < ?2 ORDER BY ts_ms DESC, id DESC LIMIT 1", + "SELECT m.id FROM messages m WHERE m.target = ?1 AND m.rev > ?2 ORDER BY m.rev", + "SELECT message_id, emoji, COUNT(*), MIN(ts_ms) AS first FROM reactions + WHERE message_id BETWEEN ?1 AND ?2 GROUP BY message_id, emoji", + "SELECT message_id FROM pins WHERE target = ?1 ORDER BY ts_ms DESC", + "DELETE FROM messages WHERE ts_ms < ?1", + "SELECT id FROM topics WHERE target = ?1 AND archived = 0 ORDER BY last_activity_ms DESC", + "SELECT id FROM topics WHERE target = ?1 AND title = ?2", + "SELECT id FROM activity WHERE id < ?1 ORDER BY id DESC", + "DELETE FROM activity WHERE ts_ms < ?1", + "SELECT id FROM events WHERE start_ms > ?1 AND start_ms <= ?2", + "SELECT id FROM events WHERE host_uid = ?1 AND start_ms <= ?2", + "SELECT id FROM events WHERE live_stream = ?1", + "SELECT COUNT(*) FROM events WHERE creator_uid = ?1 AND start_ms >= ?2", + "SELECT uid FROM rsvps WHERE event_id = ?1", + ] { + assert_indexed(&db, sql); + } + for filter in [ + EventFilter { from_ms: 0, ..Default::default() }, + EventFilter { from_ms: 0, channel: Some(1), to_ms: Some(5), ..Default::default() }, + ] { + assert_indexed(&db, &filter.sql()); + } +} + +fn assert_indexed(db: &Db, sql: &str) { + let plan = db.query_plan(sql); + for line in &plan { + let full_scan = line.starts_with("SCAN"); + assert!(!full_scan, "{sql}\n{plan:?}"); + } +} + +#[test] +fn reactions_and_revisions() { + let db = Db::in_memory().unwrap(); + let m = db.add_message(msg(CH1, "hi", 1), None).unwrap(); + let other = db.add_message(msg(CH1, "other", 2), None).unwrap(); + assert_eq!(db.add_reaction(m.id, "👍", &alice(), 10).unwrap(), Some(1)); + assert_eq!(db.add_reaction(m.id, "👍", &alice(), 11).unwrap(), None); + assert_eq!(db.add_reaction(m.id, "👍", &bob(), 12).unwrap(), Some(2)); + assert_eq!(db.add_reaction(m.id, "🏳️‍🌈", &bob(), 13).unwrap(), Some(1)); + assert_eq!(db.reaction_kinds(m.id).unwrap(), 2); + let entry = db.message(m.id, Some("alice")).unwrap().unwrap(); + assert_eq!(entry.reactions.len(), 2); + assert_eq!( + (entry.reactions[0].emoji.as_str(), entry.reactions[0].count, entry.reactions[0].me), + ("👍", 2, true) + ); + assert!(!entry.reactions[1].me); + assert!(entry.rev > other.rev, "reacting bumps the revision"); + let (changed, _) = db.sync(&CH1, other.rev, None, None).unwrap(); + assert_eq!(texts(&changed), ["hi"]); + assert_eq!(db.reactors(m.id, "👍").unwrap(), [alice(), bob()]); + assert!(db.has_reaction(m.id, "👍", "bob").unwrap()); + assert_eq!(db.remove_reaction(m.id, "👍", "alice", 20).unwrap(), Some(1)); + assert_eq!(db.remove_reaction(m.id, "👍", "alice", 21).unwrap(), None); + // A page carries the reactions of its messages only. + let (page, _) = db.history(&CH1, &HistoryOptions::default(), Some("bob")).unwrap(); + assert_eq!(page[0].reactions.len(), 2); + assert!(page[0].reactions.iter().all(|r| r.me)); + assert!(page[1].reactions.is_empty()); +} + +#[test] +fn pins_survive_retention() { + let db = Db::in_memory().unwrap(); + let old = db.add_message(msg(CH1, "old pinned", 1), None).unwrap(); + let gone = db.add_message(msg(CH1, "old", 2), None).unwrap(); + db.add_reaction(gone.id, "x", &alice(), 3).unwrap(); + assert!(db.pin(old.id, &CH1, &alice(), 5).unwrap()); + assert!(!db.pin(old.id, &CH1, &bob(), 6).unwrap()); + assert_eq!(db.pin_count(&CH1).unwrap(), 1); + let pins = db.pins(&CH1, None).unwrap(); + assert_eq!( + (pins[0].entry.id, pins[0].by.clone(), pins[0].entry.pinned), + (old.id, alice(), true) + ); + assert_eq!(db.prune_messages(100).unwrap(), 1); + assert!(db.message(gone.id, None).unwrap().is_none()); + assert!(db.reactors(gone.id, "x").unwrap().is_empty()); + assert!(db.message(old.id, None).unwrap().unwrap().pinned); + assert_eq!(db.unpin(old.id, 7).unwrap(), Some(alice())); + assert_eq!(db.unpin(old.id, 8).unwrap(), None); + assert!(db.pins(&CH1, None).unwrap().is_empty()); +} + +#[test] +fn topics() { + let db = Db::in_memory().unwrap(); + let root = db.add_message(msg(CH1, "let's raid", 1), None).unwrap(); + let t = db.create_topic(&CH1, "Raid", &alice(), Some(root.id), 10).unwrap(); + let other = db.create_topic(&CH1, "Other", &bob(), None, 20).unwrap(); + db.add_message(msg(CH1, "in topic", 30), Some(t.id)).unwrap(); + let list = db.topics(&CH1, false).unwrap(); + assert_eq!(list.iter().map(|t| t.title.as_str()).collect::>(), ["Raid", "Other"]); + assert_eq!( + (list[0].message_count, list[0].last_activity_ms, list[0].root_message_id), + (1, 30, Some(root.id)) + ); + assert_eq!(db.topic_by_title(&CH1, "Raid").unwrap().unwrap().id, t.id); + let archived = db.update_topic(other.id, Some("Renamed"), Some(true)).unwrap().unwrap(); + assert!(archived.archived && archived.title == "Renamed"); + assert_eq!(db.topics(&CH1, false).unwrap().len(), 1); + assert_eq!(db.topics(&CH1, true).unwrap().len(), 2); + assert_eq!(db.open_topic_count(&CH1).unwrap(), 1); + assert!(db.topic_by_title(&CH1, "Renamed").unwrap().is_none()); + assert!(db.update_topic(999, Some("x"), None).unwrap().is_none()); +} + +#[test] +fn events_and_rsvps() { + let db = Db::in_memory().unwrap(); + let spec = EventSpec { + title: "Stream night".into(), + start_ms: 10_000, + end_ms: Some(20_000), + channel: Some(1), + kind: EventKind::Stream, + ..Default::default() + }; + let e = db.create_event(&spec, &alice(), 1).unwrap(); + assert_eq!(e.spec.host_uid.as_deref(), Some("alice")); + let general = db + .create_event( + &EventSpec { title: "Later".into(), start_ms: 50_000, ..Default::default() }, + &bob(), + 1, + ) + .unwrap(); + db.rsvp(e.id, &bob(), Some(RsvpStatus::Going), 2).unwrap(); + db.rsvp(e.id, &alice(), Some(RsvpStatus::Maybe), 3).unwrap(); + db.rsvp(e.id, &alice(), Some(RsvpStatus::Going), 4).unwrap(); + let got = db.event(e.id, Some("bob"), true).unwrap().unwrap(); + assert_eq!((got.going, got.maybe, got.my_rsvp), (2, 0, Some(RsvpStatus::Going))); + assert_eq!(got.attendees.len(), 2); + db.rsvp(e.id, &bob(), None, 5).unwrap(); + assert_eq!(db.event(e.id, Some("bob"), false).unwrap().unwrap().my_rsvp, None); + + let all = db.events(&EventFilter { from_ms: 0, ..Default::default() }, None).unwrap(); + assert_eq!(all.iter().map(|e| e.id).collect::>(), [e.id, general.id]); + // Ended events are not listed from later on; running ones are. + let from = |from_ms| EventFilter { from_ms, ..Default::default() }; + assert_eq!(db.events(&from(15_000), None).unwrap().len(), 2); + assert_eq!(db.events(&from(25_000), None).unwrap().len(), 1); + let ch = EventFilter { from_ms: 0, channel: Some(1), ..Default::default() }; + assert_eq!(db.events(&ch, None).unwrap().len(), 1); + assert_eq!(db.upcoming_events_by("bob", 5).unwrap(), 1); + assert_eq!(db.events_starting(9_000, 10_000).unwrap().len(), 1); + assert!(db.events_starting(10_000, 11_000).unwrap().is_empty()); + assert!(db.mark_notice(e.id, 15).unwrap()); + assert!(!db.mark_notice(e.id, 15).unwrap()); + + // The host's stream links within the window. + assert_eq!(db.linkable_events("alice", 9_000, 5_000).unwrap(), [e.id]); + assert!(db.linkable_events("alice", 30_000, 5_000).unwrap().is_empty()); + assert!(db.linkable_events("bob", 9_000, 5_000).unwrap().is_empty()); + db.set_live_stream(e.id, Some("s1"), 6).unwrap(); + assert_eq!(db.events_with_stream("s1").unwrap(), [e.id]); + assert!(db.linkable_events("alice", 9_000, 5_000).unwrap().is_empty()); + + let moved = db + .update_event(e.id, &EventSpec { start_ms: 12_000, host_uid: None, ..spec.clone() }, 7) + .unwrap() + .unwrap(); + assert_eq!((moved.spec.start_ms, moved.spec.host_uid.as_deref()), (12_000, Some("alice"))); + assert!(db.mark_notice(e.id, 15).unwrap(), "a moved event is reminded again"); + assert!(db.update_event(999, &spec, 8).unwrap().is_none()); + assert!(db.delete_event(e.id).unwrap()); + assert!(!db.delete_event(e.id).unwrap()); + assert!(db.event(e.id, None, true).unwrap().is_none()); +} + +#[test] +fn streams_and_activity() { + let db = Db::in_memory().unwrap(); + let entry = StreamEntry { + id: "s1".into(), + stream_id: Some("s1".into()), + streamer: alice(), + client_id: Some(3), + channel: Some(1), + title: "t".into(), + kind: "screen".into(), + started_ms: 1, + viewers: None, + source: StreamSource::Registered, + event_id: None, + }; + db.save_stream(&entry).unwrap(); + db.save_stream(&StreamEntry { title: "u".into(), ..entry.clone() }).unwrap(); + assert_eq!(db.streams().unwrap()[0].title, "u"); + db.delete_stream("s1").unwrap(); + assert!(db.streams().unwrap().is_empty()); + + for i in 0..5 { + db.add_activity( + NewActivity { + kind: "pinned", + actor: Some(&alice()), + channel: Some(1), + ref_id: Some(i.to_string()), + text: format!("a{i}"), + data: if i == 0 { Value::Null } else { json!({ "i": i }) }, + }, + i, + ) + .unwrap(); + } + let (page, more) = db.activity(None, Some(2)).unwrap(); + assert_eq!(page.iter().map(|a| a.text.as_str()).collect::>(), ["a4", "a3"]); + assert!(more); + assert_eq!(page[0].data["i"], 4); + let (rest, more) = db.activity(Some(page[1].id), None).unwrap(); + assert_eq!(rest.len(), 3); + assert!(!more); + assert_eq!(rest[2].data, Value::Null); + assert_eq!(db.prune_activity(3).unwrap(), 3); + assert_eq!(db.activity(None, None).unwrap().0.len(), 2); +} + +#[test] +fn config_table() { + let db = Db::in_memory().unwrap(); + db.set_config("a.b", &json!([1, 2]), Some("alice")).unwrap(); + db.set_config("a.b", &json!([3]), None).unwrap(); + db.set_config("c", &json!(null), None).unwrap(); + assert_eq!( + db.config_values().unwrap(), + [("a.b".to_string(), json!([3])), ("c".to_string(), json!(null))] + ); + db.delete_config("a.b").unwrap(); + assert_eq!(db.config_values().unwrap().len(), 1); +} diff --git a/crates/voelin-gateway/src/features.rs b/crates/voelin-gateway/src/features.rs new file mode 100644 index 0000000..d8c6cad --- /dev/null +++ b/crates/voelin-gateway/src/features.rs @@ -0,0 +1,571 @@ +//! Requests beyond presence and plain chat: history paging, pins, +//! reactions, topics, events, the activity feed, permissions and +//! administration. Each checks the feature switch, the user's access to the +//! chat or channel, the action's permission rule and quotas. + +use serde_json::{Value, json}; +use tracing::warn; +use voelin_gateway_proto::{ + Action, ActivityEntry, ConfigEntry, ErrorCode, EventInfo, EventKind, EventQuery, EventSpec, + HistoryEntry, HistoryPage, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, + TopicInfo, UserRef, activity_kind, +}; +use voelin_model::{ChannelId, ChatTarget}; + +use crate::config::perm_key; +use crate::db::{EventFilter, HistoryOptions, NewActivity}; +use crate::hub::{Denied, Feature, Hub, HubEvent, User, now_ms}; + +fn channel_of(target: &ChatTarget) -> Option { + match target { + ChatTarget::Channel(cid) => Some(*cid), + _ => None, + } +} + +/// The admin's page quota applied to a requested limit (0: none). +fn page_limit(requested: Option, quota: u64) -> Option { + let quota = u32::try_from(quota).unwrap_or(u32::MAX); + match (requested, quota) { + (r, 0) => r, + (Some(r), q) => Some(r.min(q)), + (None, q) => Some(q), + } +} + +impl Hub { + /// Store an activity entry and push it (if the feed is on). + pub fn add_activity(&self, activity: NewActivity<'_>) { + if !self.feature_enabled(Feature::Activity) { + return; + } + match self.db.add_activity(activity, now_ms()) { + Ok(entry) => self.emit(HubEvent::Activity(entry)), + Err(error) => warn!(%error, "could not store activity"), + } + } + + /// The actions the user may take, server-wide or in `channel`. + pub async fn permissions( + &self, + user: &User, + channel: Option, + ) -> Result, Denied> { + let mut actions = Vec::new(); + for action in Action::ALL { + if self.allowed(user, action, channel).await? { + actions.push(action); + } + } + Ok(actions) + } + + // History + + /// The original `history` request: before an id, oldest first. + pub async fn history_v1( + &self, + user: &User, + target: &ChatTarget, + before: Option, + limit: u32, + ) -> Result, Denied> { + self.require_read(user, target).await?; + if !self.feature_enabled(Feature::History) { + return Ok(Vec::new()); + } + let opts = HistoryOptions { + before, + limit: page_limit(Some(limit), self.runtime().quota.history_page), + ..Default::default() + }; + Ok(self.db.history(target, &opts, Some(&user.uid))?.0) + } + + pub async fn history(&self, user: &User, q: HistoryQuery) -> Result { + self.require_read(user, &q.target).await?; + self.require(Feature::History)?; + if let Some(topic) = q.topic { + let t = self.db.topic(topic)?.ok_or_else(|| Denied::not_found("topic"))?; + if t.target != q.target { + return Err(Denied::bad("the topic belongs to another chat")); + } + } + let opts = HistoryOptions { + before: q.before, + after: q.after, + before_ms: q.before_ms, + after_ms: q.after_ms, + limit: page_limit(q.limit, self.runtime().quota.history_page), + topic: q.topic, + exclude_topics: q.exclude_topics, + }; + let (messages, has_more) = self.db.history(&q.target, &opts, Some(&user.uid))?; + Ok(HistoryPage { target: q.target, topic: q.topic, messages, has_more }) + } + + /// New and changed messages since a revision; returns them, the revision + /// to continue from and whether more are waiting. + pub async fn sync( + &self, + user: &User, + target: &ChatTarget, + since: i64, + limit: Option, + ) -> Result<(Vec, i64, bool), Denied> { + self.require_read(user, target).await?; + self.require(Feature::History)?; + let limit = page_limit(limit, self.runtime().quota.history_page); + let (messages, more) = self.db.sync(target, since, limit, Some(&user.uid))?; + let rev = messages.last().map_or(since, |m| m.rev); + Ok((messages, rev, more)) + } + + /// A stored message the user may read. + async fn readable_message(&self, user: &User, id: i64) -> Result { + let entry = + self.db.message(id, Some(&user.uid))?.ok_or_else(|| Denied::not_found("message"))?; + self.require_read(user, &entry.message.target).await?; + Ok(entry) + } + + // Pins + + pub async fn pin(&self, user: &User, message_id: i64) -> Result<(), Denied> { + self.require(Feature::Pins)?; + let entry = self.readable_message(user, message_id).await?; + let target = entry.message.target.clone(); + self.require_allowed(user, Action::Pin, channel_of(&target)).await?; + if entry.pinned { + return Ok(()); + } + let quota = self.runtime().quota.pins_per_channel; + if quota > 0 && self.db.pin_count(&target)? >= quota { + return Err(Denied::quota(format!("at most {quota} pins per chat"))); + } + if self.db.pin(message_id, &target, &user.user_ref(), now_ms())? + && let Some(pin) = self.db.pin_info(message_id, None)? + { + self.emit(HubEvent::Pinned(pin)); + self.add_activity(NewActivity { + kind: activity_kind::PINNED, + actor: Some(&user.user_ref()), + channel: channel_of(&target), + ref_id: Some(message_id.to_string()), + text: format!("{} pinned a message", user.nickname), + data: json!({ "message_id": message_id, "target": target }), + }); + } + Ok(()) + } + + pub async fn unpin(&self, user: &User, message_id: i64) -> Result<(), Denied> { + self.require(Feature::Pins)?; + let entry = self.readable_message(user, message_id).await?; + let target = entry.message.target.clone(); + self.require_allowed(user, Action::Pin, channel_of(&target)).await?; + if self.db.unpin(message_id, now_ms())?.is_some() { + self.emit(HubEvent::Unpinned { target, message_id, by: user.user_ref() }); + } + Ok(()) + } + + pub async fn pins(&self, user: &User, target: &ChatTarget) -> Result, Denied> { + self.require(Feature::Pins)?; + self.require_read(user, target).await?; + Ok(self.db.pins(target, Some(&user.uid))?) + } + + // Reactions + + pub async fn react( + &self, + user: &User, + message_id: i64, + emoji: &str, + add: bool, + ) -> Result<(), Denied> { + self.require(Feature::Reactions)?; + let rt = self.runtime(); + if emoji.is_empty() || emoji.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(Denied::bad("a reaction is a non-empty string without spaces")); + } + if rt.quota.reaction_bytes > 0 && emoji.len() as u64 > rt.quota.reaction_bytes { + return Err(Denied::quota(format!( + "reactions are limited to {} bytes", + rt.quota.reaction_bytes + ))); + } + let entry = self.readable_message(user, message_id).await?; + let target = entry.message.target; + self.require_allowed(user, Action::React, channel_of(&target)).await?; + let me = user.user_ref(); + let count = if add { + let quota = rt.quota.reactions_per_message; + if quota > 0 + && !entry.reactions.iter().any(|r| r.emoji == emoji) + && self.db.reaction_kinds(message_id)? >= quota + { + return Err(Denied::quota(format!( + "at most {quota} different reactions per message" + ))); + } + self.db.add_reaction(message_id, emoji, &me, now_ms())? + } else { + self.db.remove_reaction(message_id, emoji, &me.uid, now_ms())? + }; + if let Some(count) = count { + self.emit(HubEvent::Reaction { + target, + message_id, + emoji: emoji.to_string(), + user: me, + added: add, + count, + }); + } + Ok(()) + } + + pub async fn reactors( + &self, + user: &User, + message_id: i64, + emoji: &str, + ) -> Result, Denied> { + self.require(Feature::Reactions)?; + self.readable_message(user, message_id).await?; + Ok(self.db.reactors(message_id, emoji)?) + } + + // Topics + + pub async fn create_topic( + &self, + user: &User, + target: &ChatTarget, + title: &str, + message_id: Option, + ) -> Result { + self.require(Feature::Topics)?; + let title = title.trim(); + if title.is_empty() { + return Err(Denied::bad("a topic needs a title")); + } + self.require_post(user, target).await?; + self.require_allowed(user, Action::CreateTopic, channel_of(target)).await?; + if let Some(id) = message_id { + let root = self.db.message(id, None)?.ok_or_else(|| Denied::not_found("message"))?; + if root.message.target != *target { + return Err(Denied::bad("the message belongs to another chat")); + } + } + let quota = self.runtime().quota.topics_per_channel; + if quota > 0 && self.db.open_topic_count(target)? >= quota { + return Err(Denied::quota(format!("at most {quota} open topics per chat"))); + } + let topic = self.db.create_topic(target, title, &user.user_ref(), message_id, now_ms())?; + self.emit(HubEvent::Topic(topic.clone())); + self.add_activity(NewActivity { + kind: activity_kind::TOPIC_CREATED, + actor: Some(&user.user_ref()), + channel: channel_of(target), + ref_id: Some(topic.id.to_string()), + text: format!("{} started the topic {}", user.nickname, topic.title), + data: json!({ "title": topic.title, "target": target }), + }); + Ok(topic) + } + + pub async fn update_topic( + &self, + user: &User, + id: i64, + title: Option<&str>, + archived: Option, + ) -> Result { + self.require(Feature::Topics)?; + let topic = self.db.topic(id)?.ok_or_else(|| Denied::not_found("topic"))?; + self.require_read(user, &topic.target).await?; + if topic.creator.uid != user.uid { + self.require_allowed(user, Action::Moderate, channel_of(&topic.target)).await?; + } + let title = title.map(str::trim); + if title == Some("") { + return Err(Denied::bad("a topic needs a title")); + } + let topic = + self.db.update_topic(id, title, archived)?.ok_or_else(|| Denied::not_found("topic"))?; + self.emit(HubEvent::Topic(topic.clone())); + Ok(topic) + } + + pub async fn topics( + &self, + user: &User, + target: &ChatTarget, + include_archived: bool, + ) -> Result, Denied> { + self.require(Feature::Topics)?; + self.require_read(user, target).await?; + Ok(self.db.topics(target, include_archived)?) + } + + // Events + + /// The user may see an event (server-wide, or in a visible channel). + pub fn event_visible(&self, user: &User, event: &EventInfo) -> bool { + event.spec.channel.is_none_or(|c| self.channel_visible(user, c)) + } + + fn check_spec(spec: &EventSpec) -> Result<(), Denied> { + if spec.title.trim().is_empty() { + return Err(Denied::bad("an event needs a title")); + } + if spec.end_ms.is_some_and(|end| end < spec.start_ms) { + return Err(Denied::bad("the event ends before it starts")); + } + if spec.kind == EventKind::Unknown { + return Err(Denied::bad("unknown event kind")); + } + Ok(()) + } + + async fn check_event_channel(&self, user: &User, spec: &EventSpec) -> Result<(), Denied> { + if let Some(cid) = spec.channel + && !self.channel_visible(user, cid) + { + return Err(Denied::forbidden("no access to this channel")); + } + self.require_allowed(user, Action::CreateEvent, spec.channel).await + } + + pub async fn create_event(&self, user: &User, spec: EventSpec) -> Result { + self.require(Feature::Events)?; + Self::check_spec(&spec)?; + self.check_event_channel(user, &spec).await?; + if spec.host_uid.as_ref().is_some_and(|h| *h != user.uid) { + self.require_allowed(user, Action::Moderate, spec.channel).await?; + } + let quota = self.runtime().quota.events_per_user; + if quota > 0 && self.db.upcoming_events_by(&user.uid, now_ms())? >= quota { + return Err(Denied::quota(format!("at most {quota} upcoming events per user"))); + } + let event = self.db.create_event(&spec, &user.user_ref(), now_ms())?; + self.emit(HubEvent::Event(EventInfo { my_rsvp: None, ..event.clone() })); + self.add_activity(NewActivity { + kind: activity_kind::EVENT_CREATED, + actor: Some(&user.user_ref()), + channel: spec.channel, + ref_id: Some(event.id.to_string()), + text: format!("{} scheduled {}", user.nickname, event.spec.title), + data: json!({ "title": event.spec.title, "start_ms": event.spec.start_ms, + "kind": event.spec.kind }), + }); + Ok(event) + } + + /// An event the user created, or may moderate. + async fn own_event(&self, user: &User, id: i64) -> Result { + let event = + self.db.event(id, Some(&user.uid), false)?.ok_or_else(|| Denied::not_found("event"))?; + if !self.event_visible(user, &event) { + return Err(Denied::not_found("event")); + } + if event.creator.uid != user.uid { + self.require_allowed(user, Action::Moderate, event.spec.channel).await?; + } + Ok(event) + } + + pub async fn update_event( + &self, + user: &User, + id: i64, + spec: EventSpec, + ) -> Result { + self.require(Feature::Events)?; + Self::check_spec(&spec)?; + let old = self.own_event(user, id).await?; + if spec.channel != old.spec.channel { + self.check_event_channel(user, &spec).await?; + } + self.db.update_event(id, &spec, now_ms())?.ok_or_else(|| Denied::not_found("event"))?; + self.emit(HubEvent::Event( + self.db.event(id, None, false)?.ok_or_else(|| Denied::not_found("event"))?, + )); + self.db.event(id, Some(&user.uid), false)?.ok_or_else(|| Denied::not_found("event")) + } + + pub async fn delete_event(&self, user: &User, id: i64) -> Result<(), Denied> { + self.require(Feature::Events)?; + let event = self.own_event(user, id).await?; + if self.db.delete_event(id)? { + self.emit(HubEvent::EventDeleted { id, channel: event.spec.channel }); + self.add_activity(NewActivity { + kind: activity_kind::EVENT_CANCELLED, + actor: Some(&user.user_ref()), + channel: event.spec.channel, + ref_id: Some(id.to_string()), + text: format!("{} cancelled {}", user.nickname, event.spec.title), + data: json!({ "title": event.spec.title, "start_ms": event.spec.start_ms }), + }); + } + Ok(()) + } + + pub async fn get_event(&self, user: &User, id: i64) -> Result { + self.require(Feature::Events)?; + let event = + self.db.event(id, Some(&user.uid), true)?.ok_or_else(|| Denied::not_found("event"))?; + if !self.event_visible(user, &event) { + return Err(Denied::not_found("event")); + } + Ok(event) + } + + pub async fn events(&self, user: &User, q: EventQuery) -> Result, Denied> { + self.require(Feature::Events)?; + let filter = EventFilter { + from_ms: q.from_ms.unwrap_or_else(now_ms), + to_ms: q.to_ms, + channel: q.channel, + limit: q.limit, + }; + let events = self.db.events(&filter, Some(&user.uid))?; + Ok(events.into_iter().filter(|e| self.event_visible(user, e)).collect()) + } + + pub async fn rsvp( + &self, + user: &User, + id: i64, + status: Option, + ) -> Result { + self.require(Feature::Events)?; + if status == Some(RsvpStatus::Unknown) { + return Err(Denied::bad("unknown answer")); + } + let event = self.db.event(id, None, false)?.ok_or_else(|| Denied::not_found("event"))?; + if !self.event_visible(user, &event) { + return Err(Denied::not_found("event")); + } + self.require_allowed(user, Action::Rsvp, event.spec.channel).await?; + self.db.rsvp(id, &user.user_ref(), status, now_ms())?; + if let Some(event) = self.db.event(id, None, false)? { + self.emit(HubEvent::Event(event)); + } + self.db.event(id, Some(&user.uid), false)?.ok_or_else(|| Denied::not_found("event")) + } + + // Activity + + pub async fn activity( + &self, + user: &User, + before: Option, + limit: Option, + ) -> Result<(Vec, bool), Denied> { + self.require(Feature::Activity)?; + let (entries, more) = self.db.activity(before, limit)?; + let visible = + entries.into_iter().filter(|e| e.channel.is_none_or(|c| self.channel_visible(user, c))); + Ok((visible.collect(), more)) + } + + // Administration + + pub async fn require_admin(&self, user: &User) -> Result<(), Denied> { + if self.is_admin(user).await? { + Ok(()) + } else { + Err(Denied::forbidden("only gateway admins may do this")) + } + } + + pub async fn config_list(&self, user: &User) -> Result, Denied> { + self.require_admin(user).await?; + Ok(self.settings.entries()) + } + + pub async fn config_get(&self, user: &User, key: &str) -> Result { + self.require_admin(user).await?; + self.settings.entry(key).ok_or_else(|| Denied::not_found("setting")) + } + + pub async fn config_set( + &self, + user: &User, + key: &str, + value: Value, + ) -> Result { + self.require_admin(user).await?; + if self.settings.entry(key).is_none() { + return Err(Denied::not_found("setting")); + } + let entry = self + .settings + .set(&self.db, key, value, Some(&user.uid)) + .map_err(|e| Denied::new(ErrorCode::BadRequest, format!("{e:#}")))?; + self.audit(Some(&user.uid), "config_set", &format!("{key}={}", entry.value)); + Ok(entry) + } + + pub async fn config_reset(&self, user: &User, key: &str) -> Result { + self.require_admin(user).await?; + let entry = self + .settings + .reset(&self.db, key, Some(&user.uid)) + .map_err(|e| Denied::new(ErrorCode::NotFound, format!("{e:#}")))?; + self.audit(Some(&user.uid), "config_reset", key); + Ok(entry) + } + + pub async fn config_reload(&self, user: &User) -> Result, Denied> { + self.require_admin(user).await?; + self.settings.reload().map_err(|e| Denied::new(ErrorCode::BadRequest, format!("{e:#}")))?; + self.audit(Some(&user.uid), "config_reload", ""); + Ok(self.settings.entries()) + } + + pub async fn perm_list(&self, user: &User) -> Result, Denied> { + self.require_admin(user).await?; + Ok(self.settings.perm_rules()) + } + + pub async fn perm_set( + &self, + user: &User, + action: Action, + rule: Option, + ) -> Result, Denied> { + if action == Action::Unknown { + return Err(Denied::bad("unknown action")); + } + let key = perm_key(action); + match rule { + Some(rule) => { + let value = serde_json::to_value(rule).expect("serializable"); + self.config_set(user, &key, value).await?; + } + None => { + self.config_reset(user, &key).await?; + } + } + Ok(self.settings.perm_rules()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn page_quota() { + assert_eq!(page_limit(None, 0), None); + assert_eq!(page_limit(Some(50_000), 0), Some(50_000)); + assert_eq!(page_limit(Some(50), 100), Some(50)); + assert_eq!(page_limit(Some(500), 100), Some(100)); + assert_eq!(page_limit(None, 100), Some(100)); + } +} diff --git a/crates/voelin-gateway/src/hub.rs b/crates/voelin-gateway/src/hub.rs index 5e14f7b..70f9ea2 100644 --- a/crates/voelin-gateway/src/hub.rs +++ b/crates/voelin-gateway/src/hub.rs @@ -1,9 +1,13 @@ //! State shared by all sessions: one observer, one relay pool, one query -//! session for lookups, chat storage and fan-out. +//! session for lookups, storage, runtime settings and fan-out of events. +//! +//! The chat features (pins, reactions, topics), events and the activity +//! feed are in `features.rs`, the stream directory in `streams.rs`, the +//! background tasks in `tasks.rs`. use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::Instant; use anyhow::{Context, Result}; use base64::prelude::*; @@ -11,26 +15,32 @@ use rand::RngExt; use sha2::{Digest, Sha256}; use tokio::sync::broadcast; use tracing::{info, warn}; -use voelin_gateway_proto::{ErrorCode, UniqueIds, identity_level, verify_auth}; -use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text}; -use voelin_observer::{ - Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool, +use voelin_gateway_proto::{ + Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo, + UniqueIds, UserRef, feature, identity_level, verify_auth, }; -use voelin_query::{Command, QueryClient}; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text}; +use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool}; +use voelin_query::{Command, Connect, QueryClient}; -use crate::config::Config; +use crate::config::{Bootstrap, Layers, Runtime}; use crate::db::{Db, TokenInfo}; -use crate::perms::{ChannelAccess, PermIds, PermResolver, channel_access, effective}; +use crate::perms::{ + ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective, + granted, rule_allows, +}; +use crate::settings::Settings; +use crate::streams::Directory; pub fn now_secs() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or_default() + now_ms() / 1000 } -fn now_ms() -> i64 { - now_secs() * 1000 +pub fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() } /// A logged-in user. @@ -45,14 +55,36 @@ pub struct User { pub subscribe_power: i64, } +impl User { + pub fn user_ref(&self) -> UserRef { + UserRef { uid: self.uid.clone(), name: self.nickname.clone() } + } +} + /// An error to send to the client. #[derive(Debug)] pub struct Denied(pub ErrorCode, pub String); impl Denied { - fn new(code: ErrorCode, msg: impl Into) -> Self { + pub fn new(code: ErrorCode, msg: impl Into) -> Self { Self(code, msg.into()) } + + pub fn forbidden(msg: impl Into) -> Self { + Self::new(ErrorCode::Forbidden, msg) + } + + pub fn not_found(what: &str) -> Self { + Self::new(ErrorCode::NotFound, format!("no such {what}")) + } + + pub fn bad(msg: impl Into) -> Self { + Self::new(ErrorCode::BadRequest, msg) + } + + pub fn quota(msg: impl Into) -> Self { + Self::new(ErrorCode::QuotaExceeded, msg) + } } impl From for Denied { @@ -61,8 +93,107 @@ impl From for Denied { } } +impl From for Denied { + fn from(e: rusqlite::Error) -> Self { + warn!(error = %e, "database error"); + Denied::new(ErrorCode::Internal, "database error") + } +} + +/// Something sessions may want to forward; each session filters by what it +/// opened, subscribed to and may see. +#[derive(Clone, Debug)] +pub enum HubEvent { + Chat(HistoryEntry), + Pinned(PinInfo), + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + Topic(TopicInfo), + Event(EventInfo), + EventDeleted { + id: i64, + channel: Option, + }, + Reminder { + event: EventInfo, + starts_in_ms: i64, + }, + StreamStarted(StreamEntry), + StreamUpdated(StreamEntry), + StreamEnded { + id: String, + channel: Option, + reason: String, + }, + Activity(ActivityEntry), + /// Features changed; sessions recompute their capabilities. + Capabilities, +} + +/// Optional features, for [`Hub::feature_enabled`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Feature { + History, + Pins, + Reactions, + Topics, + Events, + Streams, + Activity, +} + +impl Feature { + pub fn name(self) -> &'static str { + match self { + Feature::History => feature::HISTORY, + Feature::Pins => feature::PINS, + Feature::Reactions => feature::REACTIONS, + Feature::Topics => feature::TOPICS, + Feature::Events => feature::EVENTS, + Feature::Streams => feature::STREAMS, + Feature::Activity => feature::ACTIVITY, + } + } + + pub fn enabled(self, rt: &Runtime) -> bool { + let f = &rt.features; + match self { + Feature::History => rt.history.enabled, + // These live on stored messages. + Feature::Pins => rt.history.enabled && f.pins, + Feature::Reactions => rt.history.enabled && f.reactions, + Feature::Topics => rt.history.enabled && f.topics, + Feature::Events => f.events, + Feature::Streams => f.streams, + Feature::Activity => f.activity, + } + } + + pub const ALL: [Feature; 7] = [ + Feature::History, + Feature::Pins, + Feature::Reactions, + Feature::Topics, + Feature::Events, + Feature::Streams, + Feature::Activity, + ]; +} + pub struct Hub { - pub config: Config, + pub boot: Bootstrap, + pub settings: Settings, pub gateway_id: String, pub server_uid: String, pub server_name: String, @@ -70,21 +201,34 @@ pub struct Hub { needed_level: u8, default_channel: ChannelId, pub observer: Observer, - relays: RelayPool, + connect: Connect, + relays: RwLock, + /// Serializes rebuilding the relay pool. + relay_rebuild: tokio::sync::Mutex<()>, lookup: QueryClient, perms: PermResolver, - pub db: Option, - chat: broadcast::Sender<(i64, ChatMessage)>, + groups: GroupResolver, + pub db: Db, + events: broadcast::Sender>, /// Readers per relayed channel, and when the last one left. readers: Mutex>, /// Our own query clients, whose messages are echoes. own_clients: Mutex>, + /// Message ids while history is off. next_message_id: Mutex, + pub(crate) directory: Mutex, } impl Hub { - pub async fn start(config: Config) -> Result> { - let connect = config.query_connect(); + /// Connect to the server, open the database and start the background tasks. + pub async fn start(layers: Layers) -> Result> { + let boot = layers.bootstrap()?; + let db = Db::open(&boot.db_path) + .with_context(|| format!("failed to open {}", boot.db_path.display()))?; + let settings = Settings::new(layers, &db)?; + let rt = settings.current(); + + let connect = boot.query_connect(); let (lookup, _) = QueryClient::connect(&connect).await.context("query login for lookups failed")?; let info = lookup.send(&Command::new("serverinfo")).await?; @@ -103,140 +247,148 @@ impl Hub { .unwrap_or(1); let perms = PermResolver::new(PermIds::load(&lookup).await?); let own_id = lookup.own_client_id().await?; - let _ = lookup - .send( - &Command::new("clientupdate") - .arg("client_nickname", format!("{} Gateway", config.relay.nickname)), - ) - .await; - - let db = if config.history.enabled { - let db = Db::open(&config.history.path) - .with_context(|| format!("failed to open {}", config.history.path.display()))?; - db.prune(now_secs(), config.history.retention_days)?; - Some(db) - } else { - None - }; + set_lookup_nickname(&lookup, &rt.relay.nickname).await; let observer = Observer::spawn(ObserverConfig::new(connect.clone())); - let mut relay_config = RelayConfig::new(connect); - relay_config.nickname = config.relay.nickname.clone(); - relay_config.format = config.relay.format.clone(); - let relays = RelayPool::new(relay_config); + let relays = new_relay_pool(&connect, &rt.relay.nickname); + let directory = Directory::load(&db); info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server"); let hub = Arc::new(Self { - gateway_id: config.gateway_id(), - config, + gateway_id: boot.gateway_id(), + boot, + settings, server_uid, server_name, is_ts6, needed_level, default_channel, observer, - relays, + connect, + relays: RwLock::new(relays), + relay_rebuild: Default::default(), lookup, perms, + groups: GroupResolver::default(), db, - chat: broadcast::channel(1024).0, + events: broadcast::channel(4096).0, readers: Default::default(), own_clients: Mutex::new([own_id].into()), next_message_id: Mutex::new(0), + directory: Mutex::new(directory), }); - tokio::spawn(hub.clone().pump_observer_chat()); - tokio::spawn(hub.clone().pump_relays()); - tokio::spawn(hub.clone().teardown_idle_relays()); - for &cid in &hub.config.relay.pinned_channels { - if let Err(error) = hub.relays.open(cid).await { + crate::tasks::spawn_all(&hub); + for &cid in &rt.relay.pinned_channels { + if let Err(error) = hub.relays().open(cid).await { warn!(cid, %error, "could not open pinned relay"); } } Ok(hub) } - pub fn subscribe_chat(&self) -> broadcast::Receiver<(i64, ChatMessage)> { - self.chat.subscribe() + pub fn runtime(&self) -> Arc { + self.settings.current() } - /// Store (if history is on) and fan out a message. - fn publish(&self, msg: ChatMessage) { - let id = match &self.db { - Some(db) => db.add_message(&msg).unwrap_or_else(|error| { - warn!(%error, "failed to store message"); - -1 - }), - None => { - let mut next = self.next_message_id.lock().unwrap(); - *next += 1; - *next - } - }; - let _ = self.chat.send((id, msg)); + pub fn subscribe(&self) -> broadcast::Receiver> { + self.events.subscribe() } - /// Server chat seen by the observer. - async fn pump_observer_chat(self: Arc) { - let mut events = self.observer.subscribe(); - loop { - match events.recv().await { - Ok(ObserverEvent::Chat(msg)) if msg.target == ChatTarget::Server => { - let own = msg - .author_id - .is_some_and(|id| self.own_clients.lock().unwrap().contains(&id)); - if !own { - self.publish(msg); - } - } - Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => return, - } + pub fn emit(&self, event: HubEvent) { + let _ = self.events.send(Arc::new(event)); + } + + pub fn relays(&self) -> RelayPool { + self.relays.read().unwrap().clone() + } + + pub(crate) fn is_own_client(&self, id: u16) -> bool { + self.own_clients.lock().unwrap().contains(&id) + } + + /// Features for the `hello` message. + pub fn capabilities(&self) -> Vec { + let rt = self.runtime(); + let mut caps = vec![feature::PRESENCE.to_string(), feature::RELAY.to_string()]; + caps.extend( + Feature::ALL.into_iter().filter(|f| f.enabled(&rt)).map(|f| f.name().to_string()), + ); + caps + } + + /// Features for one user: [`Hub::capabilities`] plus `admin`. + pub async fn user_capabilities(&self, user: &User) -> Vec { + let mut caps = self.capabilities(); + if self.is_admin(user).await.unwrap_or(false) { + caps.push(feature::ADMIN.to_string()); + } + caps + } + + pub fn feature_enabled(&self, feature: Feature) -> bool { + feature.enabled(&self.runtime()) + } + + /// Fail with `feature_disabled` unless the feature is on. + pub fn require(&self, feature: Feature) -> Result<(), Denied> { + if self.feature_enabled(feature) { + Ok(()) + } else { + Err(Denied::new( + ErrorCode::FeatureDisabled, + format!("{} is turned off on this gateway", feature.name()), + )) } } - /// Channel chat seen by relays. - async fn pump_relays(self: Arc) { - let mut events = self.relays.subscribe(); - loop { - match events.recv().await { - Ok(RelayEvent::Message(msg)) => { - let own = msg - .author_id - .is_some_and(|id| self.own_clients.lock().unwrap().contains(&id)); - if !own { - self.publish(msg); - } - } - Ok(RelayEvent::Closed { channel, reason }) => { - warn!(channel, %reason, "relay closed"); - } - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => return, + /// Rebuild the relay pool, e.g. for a new nickname; open relays move over. + pub(crate) async fn rebuild_relays(self: &Arc, nickname: &str) { + let _guard = self.relay_rebuild.lock().await; + let pool = new_relay_pool(&self.connect, nickname); + tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe())); + let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool); + let channels = old.channels().await; + old.close_all().await; + drop(old); + set_lookup_nickname(&self.lookup, nickname).await; + let pool = self.relays(); + for cid in channels { + if let Err(error) = pool.open(cid).await { + warn!(cid, %error, "could not reopen relay"); } } + info!(nickname, "relays renamed"); + } + + /// Pinned channels changed: open new ones, let removed ones idle out. + pub(crate) async fn apply_pinned_channels(&self, old: &[u64], new: &[u64]) { + let pool = self.relays(); + for cid in new.iter().filter(|c| !old.contains(c)) { + if let Err(error) = pool.open(*cid).await { + warn!(cid, %error, "could not open pinned relay"); + } + } + for cid in old.iter().filter(|c| !new.contains(c)) { + // The idle teardown closes it once nobody reads it. + self.readers.lock().unwrap().entry(*cid).or_insert((0, Instant::now())); + } } - async fn teardown_idle_relays(self: Arc) { - let idle = Duration::from_secs(self.config.relay.idle_teardown_secs); - loop { - tokio::time::sleep(Duration::from_secs(15).min(idle)).await; - let idle_channels: Vec = self - .readers - .lock() - .unwrap() - .iter() - .filter(|(cid, (n, since))| { - *n == 0 - && since.elapsed() >= idle - && !self.config.relay.pinned_channels.contains(cid) - }) - .map(|(cid, _)| *cid) - .collect(); - for cid in idle_channels { - self.readers.lock().unwrap().remove(&cid); - self.relays.close(cid).await; - } + /// Channels whose relay nobody needs any more. + pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec { + let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs); + let mut readers = self.readers.lock().unwrap(); + let channels: Vec = readers + .iter() + .filter(|(cid, (n, since))| { + *n == 0 && since.elapsed() >= idle && !rt.relay.pinned_channels.contains(cid) + }) + .map(|(cid, _)| *cid) + .collect(); + for cid in &channels { + readers.remove(cid); } + channels } // Authentication @@ -261,7 +413,7 @@ impl Hub { ) .map_err(|e| Denied::new(ErrorCode::AuthFailed, e.to_string()))?; let uid = ids.for_server(self.is_ts6).to_string(); - let needed = self.needed_level.max(self.config.auth.min_security_level); + let needed = self.needed_level.max(self.runtime().auth.min_security_level); let level = identity_level(omega, key_offset); if level < needed { return Err(Denied::new( @@ -277,11 +429,9 @@ impl Hub { /// Log in with a token from an earlier login. pub async fn resume(&self, token: &str) -> Result<(User, String, i64), Denied> { - let hash = hash_token(token); let info = self .db - .as_ref() - .and_then(|db| db.token(&hash, now_secs()).ok().flatten()) + .token(&hash_token(token), now_secs())? .ok_or_else(|| Denied::new(ErrorCode::AuthFailed, "unknown or expired token"))?; let user = self.lookup_user(&info.uid).await?; self.audit(Some(&user.uid), "login", "token"); @@ -291,20 +441,18 @@ impl Hub { fn issue_token(&self, user: &User) -> Result<(String, i64), Denied> { let bytes: [u8; 32] = rand::rng().random(); let token = BASE64_URL_SAFE_NO_PAD.encode(bytes); - let expires = now_secs() + self.config.auth.token_ttl_hours as i64 * 3600; - if let Some(db) = &self.db { - db.add_token( - &hash_token(&token), - &TokenInfo { uid: user.uid.clone(), cldbid: user.cldbid, expires }, - ) - .map_err(|e| Denied::new(ErrorCode::Internal, e.to_string()))?; - } + let expires = now_secs() + self.runtime().auth.token_ttl_hours as i64 * 3600; + self.db.add_token( + &hash_token(&token), + &TokenInfo { uid: user.uid.clone(), cldbid: user.cldbid, expires }, + )?; Ok((token, expires)) } async fn lookup_user(&self, uid: &str) -> Result { - if self.config.auth.deny_uids.iter().any(|d| d == uid) { - return Err(Denied::new(ErrorCode::Forbidden, "not allowed on this gateway")); + let rt = self.runtime(); + if rt.auth.deny_uids.iter().any(|d| d == uid) { + return Err(Denied::forbidden("not allowed on this gateway")); } let bans = self.lookup.send(&Command::new("banlist")).await.unwrap_or_default(); if bans.iter().any(|b| b.get("uid") == Some(uid)) { @@ -318,17 +466,10 @@ impl Hub { let info = self.lookup.send(&Command::new("clientdbinfo").arg("cldbid", cldbid)).await?; let nickname = info.first().and_then(|r| r.get("client_nickname")).unwrap_or("unknown").to_string(); - if !self.config.auth.require_server_groups.is_empty() { - let groups = self - .lookup - .send(&Command::new("servergroupsbyclientid").arg("cldbid", cldbid)) - .await?; - let allowed = groups - .iter() - .filter_map(|r| r.parse::("sgid")) - .any(|g| self.config.auth.require_server_groups.contains(&g)); - if !allowed { - return Err(Denied::new(ErrorCode::Forbidden, "missing required server group")); + if !rt.auth.require_server_groups.is_empty() { + let groups = self.groups.server_groups(&self.lookup, cldbid).await?; + if !groups.iter().any(|g| rt.auth.require_server_groups.contains(g)) { + return Err(Denied::forbidden("missing required server group")); } } let entries = self.perms.entries(&self.lookup, cldbid, self.default_channel).await?; @@ -347,7 +488,7 @@ impl Hub { let presence = self.observer.presence(); let presence = presence.read().unwrap(); let Some(channel) = presence.channels.get(&cid) else { - return Err(Denied::new(ErrorCode::BadRequest, format!("no channel {cid}"))); + return Err(Denied::bad(format!("no channel {cid}"))); }; if channel.needed_subscribe_power as i64 > user.subscribe_power { return Ok(ChannelAccess { read: false, post: false }); @@ -363,6 +504,142 @@ impl Hub { Ok(effective(&entries, self.perms.ids.server_text_send) > 0) } + /// Whether the user may see a channel at all (presence filter). + pub fn channel_visible(&self, user: &User, cid: ChannelId) -> bool { + let presence = self.observer.presence(); + let p = presence.read().unwrap(); + p.channels + .get(&cid) + .is_some_and(|c| c.needed_subscribe_power as i64 <= user.subscribe_power) + } + + /// The user may read `target`. + pub async fn require_read(&self, user: &User, target: &ChatTarget) -> Result<(), Denied> { + match target { + ChatTarget::Server => Ok(()), + ChatTarget::Channel(cid) => { + if self.channel_access(user, *cid).await?.read { + Ok(()) + } else { + Err(Denied::forbidden("no access to this channel")) + } + } + ChatTarget::Private(_) => Err(Denied::bad("private chat is not relayed")), + } + } + + /// The user may write in `target`. + pub async fn require_post(&self, user: &User, target: &ChatTarget) -> Result<(), Denied> { + let allowed = match target { + ChatTarget::Server => self.can_post_server_chat(user).await?, + ChatTarget::Channel(cid) => self.channel_access(user, *cid).await?.post, + ChatTarget::Private(_) => return Err(Denied::bad("private chat is not relayed")), + }; + if allowed { Ok(()) } else { Err(Denied::forbidden("no permission to post here")) } + } + + async fn user_groups( + &self, + user: &User, + channel: Option, + ) -> Result { + let online = { + let presence = self.observer.presence(); + let p = presence.read().unwrap(); + p.clients + .values() + .find(|c| { + c.uid.as_deref() == Some(user.uid.as_str()) && !c.server_groups.is_empty() + }) + .map(|c| c.server_groups.clone()) + }; + let server = match online { + Some(groups) => groups, + None => self.groups.server_groups(&self.lookup, user.cldbid).await?, + }; + let channel = match channel { + Some(cid) => self.groups.channel_groups(&self.lookup, user.cldbid, cid).await?, + None => Vec::new(), + }; + Ok(UserGroups { server, channel }) + } + + async fn rule_allows( + &self, + user: &User, + action: Action, + channel: Option, + ) -> Result, Denied> { + let rt = self.runtime(); + let Some(rule) = rt.perm.get(action) else { return Ok(None) }; + let needs_channel = !rule.channel_groups.is_empty() && !rule.everyone; + let groups = self.user_groups(user, channel.filter(|_| needs_channel)).await?; + Ok(Some(rule_allows(rule, &groups))) + } + + pub async fn is_admin(&self, user: &User) -> Result { + if let Some(allowed) = self.rule_allows(user, Action::Admin, None).await? { + return Ok(allowed); + } + let entries = self.perms.entries(&self.lookup, user.cldbid, self.default_channel).await?; + Ok(granted(&entries, self.perms.ids.server_modify_name)) + } + + /// Whether a rule (or the action's default) lets the user act, server-wide + /// or in `channel`. Access to the chat itself is checked separately. + pub async fn allowed( + &self, + user: &User, + action: Action, + channel: Option, + ) -> Result { + if action == Action::Unknown { + return Ok(false); + } + if self.is_admin(user).await? { + return Ok(true); + } + if action == Action::Admin { + return Ok(false); + } + if action == Action::Pin && Box::pin(self.allowed(user, Action::Moderate, channel)).await? { + return Ok(true); + } + if let Some(allowed) = self.rule_allows(user, action, channel).await? { + return Ok(allowed); + } + Ok(match action { + Action::React | Action::CreateTopic | Action::Rsvp | Action::Stream => true, + Action::CreateEvent => match channel { + Some(cid) => self.channel_access(user, cid).await?.post, + None => self.can_post_server_chat(user).await?, + }, + Action::Moderate => match channel { + Some(cid) => { + let entries = self.perms.entries(&self.lookup, user.cldbid, cid).await?; + granted(&entries, self.perms.ids.channel_modify_name) + } + None => false, + }, + // Moderators, handled above. + Action::Pin => false, + Action::Admin | Action::Unknown => false, + }) + } + + pub async fn require_allowed( + &self, + user: &User, + action: Action, + channel: Option, + ) -> Result<(), Denied> { + if self.allowed(user, action, channel).await? { + Ok(()) + } else { + Err(Denied::forbidden(format!("not allowed to {}", action.as_str().replace('_', " ")))) + } + } + /// Presence as this user may see it: channels within their subscribe /// power, no query clients. pub fn filtered_presence(&self, user: &User) -> Presence { @@ -385,17 +662,53 @@ impl Hub { // Chat + /// Store (if history is on) and fan out a message. + pub fn publish(&self, msg: ChatMessage, topic_id: Option) -> HistoryEntry { + let entry = if self.runtime().history.enabled { + self.db.add_message(msg.clone(), topic_id).unwrap_or_else(|error| { + warn!(%error, "failed to store message"); + HistoryEntry { topic_id, ..HistoryEntry::new(-1, msg) } + }) + } else { + let mut next = self.next_message_id.lock().unwrap(); + *next += 1; + HistoryEntry { topic_id, ..HistoryEntry::new(*next, msg) } + }; + if let Some(topic) = topic_id.and_then(|t| self.db.topic(t).ok().flatten()) { + self.emit(HubEvent::Topic(topic)); + } + self.emit(HubEvent::Chat(entry.clone())); + entry + } + + /// A message seen in TeamSpeak. Posts in the topic format (from official + /// clients) join that topic. + pub(crate) fn publish_incoming(&self, mut msg: ChatMessage) { + let mut topic_id = None; + if self.feature_enabled(Feature::Topics) + && let Some((title, text)) = + parse_topic_post(&self.runtime().topics.relay_format, &msg.text) + && let Ok(Some(topic)) = self.db.topic_by_title(&msg.target, title) + { + topic_id = Some(topic.id); + msg.text = text.to_string(); + } + self.publish(msg, topic_id); + } + /// Start reading a channel for one more session. pub async fn add_reader(&self, cid: ChannelId) -> Result<(), Denied> { - let open = self.readers.lock().unwrap().len(); - let already = self.readers.lock().unwrap().contains_key(&cid); - if !already && open >= self.config.relay.max_channel_relays { - return Err(Denied::new( - ErrorCode::Unavailable, - "too many relayed channels, try later", - )); + let max = self.runtime().relay.max_channel_relays as usize; + { + let readers = self.readers.lock().unwrap(); + if max > 0 && !readers.contains_key(&cid) && readers.len() >= max { + return Err(Denied::new( + ErrorCode::Unavailable, + "too many relayed channels, try later", + )); + } } - self.relays.open(cid).await?; + self.relays().open(cid).await?; self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1; Ok(()) } @@ -407,16 +720,41 @@ impl Hub { } } - /// Post on behalf of `user`; the message is published to readers directly - /// (the relay's echo is dropped). - pub async fn post(&self, user: &User, target: &ChatTarget, text: &str) -> Result<(), Denied> { + /// Post on behalf of `user`, optionally into a topic; the message is + /// published to readers directly (the relay's echo is dropped). + pub async fn post( + &self, + user: &User, + target: &ChatTarget, + text: &str, + topic: Option, + ) -> Result { + let rt = self.runtime(); + if rt.quota.message_bytes > 0 && text.len() as u64 > rt.quota.message_bytes { + return Err(Denied::quota(format!( + "messages are limited to {} bytes", + rt.quota.message_bytes + ))); + } + self.require_post(user, target).await?; + let relayed = match topic { + Some(id) => { + self.require(Feature::Topics)?; + let topic = self.db.topic(id)?.ok_or_else(|| Denied::not_found("topic"))?; + if topic.target != *target { + return Err(Denied::bad("the topic belongs to another chat")); + } + if topic.archived { + return Err(Denied::forbidden("the topic is archived")); + } + rt.topics.relay_format.replace("{topic}", &topic.title).replace("{text}", text) + } + None => text.to_string(), + }; + let full = relay_text(&rt.relay.format, &user.nickname, &relayed); match target { ChatTarget::Server => { - if !self.can_post_server_chat(user).await? { - return Err(Denied::new(ErrorCode::Forbidden, "no permission for server chat")); - } - let msg = relay_text(&self.config.relay.format, &user.nickname, text); - for part in voelin_model::split_message(&msg, 1024) { + for part in voelin_model::split_message(&full, 1024) { self.lookup .send( &Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part), @@ -425,40 +763,80 @@ impl Hub { } } ChatTarget::Channel(cid) => { - if !self.channel_access(user, *cid).await?.post { - return Err(Denied::new(ErrorCode::Forbidden, "no permission to post here")); - } if !self.readers.lock().unwrap().contains_key(cid) { // Posting without reading still needs a relay in the channel. self.add_reader(*cid).await?; self.remove_reader(*cid); } - self.relays.send(*cid, &user.nickname, text).await?; - } - ChatTarget::Private(_) => { - return Err(Denied::new(ErrorCode::BadRequest, "private chat is not relayed")); + // The pool's format is `{text}`: `full` is already formatted. + self.relays().send(*cid, &user.nickname, &full).await?; } + ChatTarget::Private(_) => unreachable!("checked by require_post"), } self.audit(Some(&user.uid), "post", &format!("{target:?}")); - self.publish(ChatMessage { - target: target.clone(), - author_name: user.nickname.clone(), - author_uid: Some(user.uid.clone()), - author_id: None, - text: text.to_string(), - ts_ms: now_ms(), - via_relay: true, - }); - Ok(()) + Ok(self.publish( + ChatMessage { + target: target.clone(), + author_name: user.nickname.clone(), + author_uid: Some(user.uid.clone()), + author_id: None, + text: text.to_string(), + ts_ms: now_ms(), + via_relay: true, + }, + topic, + )) } pub fn audit(&self, uid: Option<&str>, action: &str, detail: &str) { - if let Some(db) = &self.db { - db.audit(now_secs(), uid, action, detail); - } + self.db.audit(now_secs(), uid, action, detail); } } -fn hash_token(token: &str) -> String { +fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool { + let mut config = RelayConfig::new(connect.clone()); + config.nickname = nickname.to_string(); + // Posts are formatted by the hub, with the current settings. + config.format = "{text}".into(); + RelayPool::new(config) +} + +async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) { + let _ = lookup + .send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway"))) + .await; +} + +/// Split `text` by a topic format like `[#{topic}] {text}` into title and +/// the rest. +pub fn parse_topic_post<'a>(format: &str, text: &'a str) -> Option<(&'a str, &'a str)> { + let (prefix, rest) = format.split_once("{topic}")?; + let (middle, suffix) = rest.split_once("{text}")?; + if middle.is_empty() { + return None; + } + let body = text.strip_prefix(prefix)?.strip_suffix(suffix)?; + let (title, text) = body.split_once(middle)?; + (!title.is_empty()).then_some((title, text)) +} + +pub fn hash_token(token: &str) -> String { BASE64_STANDARD.encode(Sha256::digest(token.as_bytes())) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn topic_posts_parse() { + assert_eq!( + parse_topic_post("[#{topic}] {text}", "[#Raid] go now"), + Some(("Raid", "go now")) + ); + assert_eq!(parse_topic_post("[#{topic}] {text}", "[#Raid]go"), None); + assert_eq!(parse_topic_post("[#{topic}] {text}", "hello"), None); + assert_eq!(parse_topic_post("{text}", "hello"), None); + assert_eq!(parse_topic_post("{topic}: {text} <<", "T: x <<"), Some(("T", "x"))); + } +} diff --git a/crates/voelin-gateway/src/main.rs b/crates/voelin-gateway/src/main.rs index 0cff9dd..f7981c1 100644 --- a/crates/voelin-gateway/src/main.rs +++ b/crates/voelin-gateway/src/main.rs @@ -1,14 +1,21 @@ //! tsgw: companion gateway for TeamSpeak 3/6 servers. //! //! Gives app users invisible presence (who is in which channel) and channel -//! chat without joining voice, through ServerQuery. See +//! chat without joining voice, through ServerQuery, plus pins, reactions, +//! topics, events, a stream directory and an activity feed. See //! docs/gateway-admin.md and the protocol in `voelin-gateway-proto`. mod config; mod db; +mod features; mod hub; mod perms; mod session; +mod settings; +mod streams; +mod tasks; +#[cfg(test)] +mod tests; use std::path::PathBuf; use std::sync::Arc; @@ -19,7 +26,7 @@ use axum::extract::{State, WebSocketUpgrade}; use axum::response::IntoResponse; use axum::routing::get; use clap::Parser; -use tracing::info; +use tracing::{info, warn}; use tracing_subscriber::EnvFilter; use crate::hub::Hub; @@ -30,6 +37,10 @@ struct Args { /// Configuration file. #[arg(long, short, default_value = "tsgw.toml", env = "TSGW_CONFIG")] config: PathBuf, + /// Set a key, e.g. `--set history.retention_days=90`; wins over the + /// environment and the file, but not over values set at runtime. + #[arg(long = "set", value_name = "KEY=VALUE")] + set: Vec, } #[tokio::main] @@ -40,25 +51,41 @@ async fn main() -> Result<()> { ) .init(); let args = Args::parse(); - let config = config::Config::load(&args.config)?; - let bind = config.listen.bind; - let hub = Hub::start(config).await?; - let app = Router::new() - .route("/v1", get(ws)) - .route("/health", get(|| async { "ok" })) - .with_state(hub); + let layers = config::Layers::load(&args.config, &args.set)?; + let bind = layers.bootstrap()?.bind; + let hub = Hub::start(layers).await?; + tokio::spawn(reload_on_hangup(hub.clone())); let listener = tokio::net::TcpListener::bind(bind).await?; info!(%bind, "listening"); - axum::serve(listener, app).with_graceful_shutdown(shutdown()).await?; + axum::serve(listener, router(hub)).with_graceful_shutdown(shutdown()).await?; Ok(()) } +pub fn router(hub: Arc) -> Router { + Router::new().route("/v1", get(ws)).route("/health", get(|| async { "ok" })).with_state(hub) +} + async fn ws(State(hub): State>, upgrade: WebSocketUpgrade) -> impl IntoResponse { upgrade .protocols([voelin_gateway_proto::SUBPROTOCOL]) .on_upgrade(move |socket| session::run(hub, socket)) } +/// `SIGHUP` reads the configuration file again. +#[cfg(unix)] +async fn reload_on_hangup(hub: Arc) { + use tokio::signal::unix::{SignalKind, signal}; + let Ok(mut hangup) = signal(SignalKind::hangup()) else { return }; + while hangup.recv().await.is_some() { + if let Err(error) = hub.settings.reload() { + warn!(error = format!("{error:#}"), "reload failed; keeping the current configuration"); + } + } +} + +#[cfg(not(unix))] +async fn reload_on_hangup(_hub: Arc) {} + async fn shutdown() { let _ = tokio::signal::ctrl_c().await; info!("shutting down"); diff --git a/crates/voelin-gateway/src/perms.rs b/crates/voelin-gateway/src/perms.rs index c7de711..1c9c795 100644 --- a/crates/voelin-gateway/src/perms.rs +++ b/crates/voelin-gateway/src/perms.rs @@ -9,6 +9,7 @@ use std::collections::HashMap; use std::sync::Mutex; use std::time::{Duration, Instant}; +use voelin_gateway_proto::PermRule; use voelin_query::{Command, QueryClient, Row}; const CACHE_TTL: Duration = Duration::from_secs(60); @@ -78,6 +79,11 @@ pub struct PermIds { pub channel_text_send: u32, pub server_text_send: u32, pub ignore_password: u32, + /// `b_channel_modify_name`: default for moderating a channel (0: unknown). + pub channel_modify_name: u32, + /// `b_virtualserver_modify_name`: default for administering the gateway + /// (0: unknown). + pub server_modify_name: u32, } impl PermIds { @@ -97,6 +103,16 @@ impl PermIds { voelin_query::Error::Protocol(format!("unknown permission {name}")) })?; } + // Only used for defaults of the gateway's own rules; without them the + // default grants nobody. + let mut optional = [0u32; 2]; + for (i, name) in ["b_channel_modify_name", "b_virtualserver_modify_name"].iter().enumerate() + { + match client.send(&Command::new("permidgetbyname").arg("permsid", name)).await { + Ok(rows) => optional[i] = rows.first().and_then(|r| r.parse("permid")).unwrap_or(0), + Err(error) => tracing::warn!(%error, name, "unknown permission"), + } + } Ok(Self { join_power: ids[0], needed_join_power: ids[1], @@ -104,10 +120,81 @@ impl PermIds { channel_text_send: ids[3], server_text_send: ids[4], ignore_password: ids[5], + channel_modify_name: optional[0], + server_modify_name: optional[1], }) } } +/// [`effective`] > 0 for a permission id that may be unknown (0). +pub fn granted(entries: &[Entry], perm: u32) -> bool { + perm != 0 && effective(entries, perm) > 0 +} + +/// A user's TeamSpeak groups, as far as a rule needs them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UserGroups { + pub server: Vec, + /// In the channel concerned; empty without one. + pub channel: Vec, +} + +/// Whether a rule lets a user with these groups act. +pub fn rule_allows(rule: &PermRule, groups: &UserGroups) -> bool { + rule.everyone + || rule.server_groups.iter().any(|g| groups.server.contains(g)) + || rule.channel_groups.iter().any(|g| groups.channel.contains(g)) +} + +type GroupCache = Mutex)>>; + +/// Server groups per user and channel groups per (user, channel), cached, +/// for users who are not online (online users' server groups come from +/// presence). +#[derive(Default)] +pub struct GroupResolver { + server: GroupCache, + channel: GroupCache<(u64, u64)>, +} + +impl GroupResolver { + pub async fn server_groups( + &self, + client: &QueryClient, + cldbid: u64, + ) -> voelin_query::Result> { + if let Some((at, groups)) = self.server.lock().unwrap().get(&cldbid) + && at.elapsed() < CACHE_TTL + { + return Ok(groups.clone()); + } + let rows = + client.send(&Command::new("servergroupsbyclientid").arg("cldbid", cldbid)).await?; + let groups: Vec = rows.iter().filter_map(|r| r.parse("sgid")).collect(); + self.server.lock().unwrap().insert(cldbid, (Instant::now(), groups.clone())); + Ok(groups) + } + + pub async fn channel_groups( + &self, + client: &QueryClient, + cldbid: u64, + cid: u64, + ) -> voelin_query::Result> { + if let Some((at, groups)) = self.channel.lock().unwrap().get(&(cldbid, cid)) + && at.elapsed() < CACHE_TTL + { + return Ok(groups.clone()); + } + let rows = client + .send(&Command::new("channelgroupclientlist").arg("cid", cid).arg("cldbid", cldbid)) + .await?; + let groups: Vec = rows.iter().filter_map(|r| r.parse("cgid")).collect(); + self.channel.lock().unwrap().insert((cldbid, cid), (Instant::now(), groups.clone())); + Ok(groups) + } +} + /// What a user may do in a channel. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ChannelAccess { @@ -212,6 +299,8 @@ mod tests { channel_text_send: 4, server_text_send: 5, ignore_password: 6, + channel_modify_name: 7, + server_modify_name: 0, }; // Guest in an open channel: can read and post. let guest = [e(0, 4, 1)]; @@ -229,5 +318,24 @@ mod tests { assert!(channel_access(&[e(0, 4, 1), e(0, 6, 1)], &ids, true).read); // No text permission: read only. assert_eq!(channel_access(&[], &ids, false), ChannelAccess { read: true, post: false }); + // Unknown permission ids grant nothing. + assert!(granted(&[e(3, 7, 1)], ids.channel_modify_name)); + assert!(!granted(&[e(0, 0, 1)], ids.server_modify_name)); + } + + #[test] + fn rules() { + let groups = UserGroups { server: vec![7, 9], channel: vec![5] }; + let rule = |everyone, server_groups: &[u64], channel_groups: &[u64]| PermRule { + everyone, + server_groups: server_groups.to_vec(), + channel_groups: channel_groups.to_vec(), + }; + assert!(rule_allows(&rule(true, &[], &[]), &UserGroups::default())); + assert!(rule_allows(&rule(false, &[6, 9], &[]), &groups)); + assert!(rule_allows(&rule(false, &[6], &[5]), &groups)); + assert!(!rule_allows(&rule(false, &[6], &[1]), &groups)); + // An empty rule allows nobody. + assert!(!rule_allows(&rule(false, &[], &[]), &groups)); } } diff --git a/crates/voelin-gateway/src/session.rs b/crates/voelin-gateway/src/session.rs index 861b832..75cd2ac 100644 --- a/crates/voelin-gateway/src/session.rs +++ b/crates/voelin-gateway/src/session.rs @@ -7,16 +7,34 @@ use std::time::{Duration, Instant}; use axum::extract::ws::{Message, WebSocket}; use base64::prelude::*; use rand::RngExt; +use serde::Deserialize; use tokio::sync::broadcast::error::RecvError; use tracing::{debug, info}; -use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg}; +use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, EventInfo, ServerMsg, feature}; use voelin_model::{ChatTarget, Presence}; use voelin_observer::ObserverEvent; -use crate::hub::{Denied, Hub, User}; +use crate::hub::{Denied, Feature, Hub, HubEvent, User}; -/// At most this many posts per window per session. -const POST_LIMIT: (usize, Duration) = (5, Duration::from_secs(5)); +/// Requests within a sliding window. +#[derive(Default)] +struct RateLimit(Vec); + +impl RateLimit { + /// Count one request; `false` if over `max` per `window` (`max` 0: no limit). + fn allow(&mut self, max: u64, window_secs: u64) -> bool { + if max == 0 { + return true; + } + let window = Duration::from_secs(window_secs); + self.0.retain(|t| t.elapsed() < window); + if self.0.len() as u64 >= max { + return false; + } + self.0.push(Instant::now()); + true + } +} struct Session { hub: Arc, @@ -24,7 +42,21 @@ struct Session { user: Option, presence: Option<(Presence, u64)>, open_chats: HashSet, - posts: Vec, + /// Extension features the client asked for ([`ClientMsg::Enable`]). + enabled: Option>, + events: bool, + streams: bool, + activity: bool, + /// Directory entries this session registered. + own_streams: Vec, + posts: RateLimit, + actions: RateLimit, +} + +/// Enough of an envelope to answer one that did not parse. +#[derive(Deserialize)] +struct RawEnvelope { + id: Option, } pub async fn run(hub: Arc, mut socket: WebSocket) { @@ -35,22 +67,28 @@ pub async fn run(hub: Arc, mut socket: WebSocket) { user: None, presence: None, open_chats: HashSet::new(), - posts: Vec::new(), + enabled: None, + events: false, + streams: false, + activity: false, + own_streams: Vec::new(), + posts: RateLimit::default(), + actions: RateLimit::default(), }; let hello = ServerMsg::Hello { gateway_id: hub.gateway_id.clone(), server_uid: hub.server_uid.clone(), server_name: hub.server_name.clone(), nonce: session.nonce.clone(), - capabilities: vec!["presence".into(), "relay".into(), "history".into()], + capabilities: hub.capabilities(), }; if send(&mut socket, None, hello).await.is_err() { return; } let mut observer = hub.observer.subscribe(); - let mut chat = hub.subscribe_chat(); + let mut events = hub.subscribe(); - loop { + 'outer: loop { tokio::select! { msg = socket.recv() => { let Some(Ok(msg)) = msg else { break }; @@ -61,11 +99,19 @@ pub async fn run(hub: Arc, mut socket: WebSocket) { }; let replies = match serde_json::from_str::>(text.as_str()) { Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(), - Err(e) => vec![(None, error(ErrorCode::BadRequest, &e.to_string()))], + Err(e) => { + let id = serde_json::from_str::(text.as_str()).ok().and_then(|r| r.id); + let code = if e.to_string().starts_with("unknown variant") { + ErrorCode::UnknownType + } else { + ErrorCode::BadRequest + }; + vec![(id, error(code, &e.to_string()))] + } }; for (id, reply) in replies { if send(&mut socket, id, reply).await.is_err() { - break; + break 'outer; } } } @@ -76,19 +122,20 @@ pub async fn run(hub: Arc, mut socket: WebSocket) { } for msg in session.presence_update(resync) { if send(&mut socket, None, msg).await.is_err() { - break; + break 'outer; } } } - event = chat.recv() => { - match event { - Ok((id, message)) if session.open_chats.contains(&message.target) => { - if send(&mut socket, None, ServerMsg::ChatEvent { id, message }).await.is_err() { - break; - } - } - Ok(_) | Err(RecvError::Lagged(_)) => {} + event = events.recv() => { + let event = match event { + Ok(event) => event, + Err(RecvError::Lagged(_)) => continue, Err(RecvError::Closed) => break, + }; + for msg in session.push(&event).await { + if send(&mut socket, None, msg).await.is_err() { + break 'outer; + } } } } @@ -106,6 +153,26 @@ fn error(code: ErrorCode, message: &str) -> ServerMsg { ServerMsg::Error { code, message: message.to_string() } } +/// Changes that count toward `limits.actions_per_window`. +fn is_action(msg: &ClientMsg) -> bool { + matches!( + msg, + ClientMsg::Pin { .. } + | ClientMsg::Unpin { .. } + | ClientMsg::React { .. } + | ClientMsg::Unreact { .. } + | ClientMsg::CreateTopic { .. } + | ClientMsg::UpdateTopic { .. } + | ClientMsg::CreateEvent { .. } + | ClientMsg::UpdateEvent { .. } + | ClientMsg::DeleteEvent { .. } + | ClientMsg::Rsvp { .. } + | ClientMsg::RegisterStream(_) + | ClientMsg::UpdateStream { .. } + | ClientMsg::UnregisterStream { .. } + ) +} + impl Session { async fn handle(&mut self, msg: ClientMsg) -> Vec { match self.handle_inner(msg).await { @@ -114,103 +181,366 @@ impl Session { } } - fn user(&self) -> Result<&User, Denied> { - self.user.as_ref().ok_or(Denied(ErrorCode::NotAuthenticated, "log in first".into())) + fn user(&self) -> Result { + self.user.clone().ok_or(Denied(ErrorCode::NotAuthenticated, "log in first".into())) + } + + /// Extension pushes of `feature` go to this session. + fn wants(&self, feature: Feature) -> bool { + self.enabled.as_ref().is_some_and(|f| f.is_empty() || f.contains(feature.name())) + && self.hub.feature_enabled(feature) } async fn handle_inner(&mut self, msg: ClientMsg) -> Result, Denied> { + let hub = self.hub.clone(); + let rt = hub.runtime(); + if is_action(&msg) + && !self.actions.allow(rt.limits.actions_per_window, rt.limits.action_window_secs) + { + return Err(Denied(ErrorCode::RateLimited, "slow down".into())); + } + let ok = || Ok(vec![ServerMsg::Ok]); match msg { ClientMsg::Ping => Ok(vec![ServerMsg::Pong]), ClientMsg::Auth { omega, key_offset, ts, signature, .. } => { let (user, token, token_expires) = - self.hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?; + hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?; info!(uid = %user.uid, nickname = %user.nickname, "user logged in"); - let uid = user.uid.clone(); - self.user = Some(user); - Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + self.logged_in(user, token, token_expires).await } ClientMsg::Resume { token, .. } => { - let (user, token, token_expires) = self.hub.resume(&token).await?; - let uid = user.uid.clone(); - self.user = Some(user); - Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + let (user, token, token_expires) = hub.resume(&token).await?; + self.logged_in(user, token, token_expires).await } ClientMsg::SubscribePresence => { self.user()?; - self.presence = None; self.presence = Some((Presence::default(), 0)); Ok(self.presence_update(true)) } ClientMsg::UnsubscribePresence => { self.presence = None; - Ok(vec![ServerMsg::Ok]) + ok() } ClientMsg::OpenChat { target } => { - let user = self.user()?.clone(); + let user = self.user()?; if self.open_chats.contains(&target) { - return Ok(vec![ServerMsg::Ok]); + return ok(); } - match &target { - ChatTarget::Server => {} - ChatTarget::Channel(cid) => { - if !self.hub.channel_access(&user, *cid).await?.read { - return Err(Denied( - ErrorCode::Forbidden, - "no access to this channel".into(), - )); - } - self.hub.add_reader(*cid).await?; - } - ChatTarget::Private(_) => { - return Err(Denied( - ErrorCode::BadRequest, - "private chat is not relayed".into(), - )); - } + hub.require_read(&user, &target).await?; + if let ChatTarget::Channel(cid) = target { + hub.add_reader(cid).await?; } debug!(uid = %user.uid, ?target, "chat opened"); self.open_chats.insert(target); - Ok(vec![ServerMsg::Ok]) + ok() } ClientMsg::CloseChat { target } => { if self.open_chats.remove(&target) && let ChatTarget::Channel(cid) = target { - self.hub.remove_reader(cid); + hub.remove_reader(cid); } - Ok(vec![ServerMsg::Ok]) + ok() } ClientMsg::SendChat { target, text } => { - let user = self.user()?.clone(); - self.posts.retain(|t| t.elapsed() < POST_LIMIT.1); - if self.posts.len() >= POST_LIMIT.0 { + let user = self.user()?; + if !self.posts.allow(rt.limits.posts_per_window, rt.limits.post_window_secs) { return Err(Denied(ErrorCode::Unavailable, "slow down".into())); } - self.posts.push(Instant::now()); - self.hub.post(&user, &target, &text).await?; - Ok(vec![ServerMsg::Ok]) + hub.post(&user, &target, &text, None).await?; + ok() } ClientMsg::History { target, before, limit } => { - let user = self.user()?.clone(); - if let ChatTarget::Channel(cid) = target - && !self.hub.channel_access(&user, cid).await?.read - { - return Err(Denied(ErrorCode::Forbidden, "no access to this channel".into())); - } - let Some(db) = &self.hub.db else { - return Ok(vec![ServerMsg::History { messages: Vec::new() }]); - }; - let messages = db - .history(&target, before, limit.min(200)) - .map_err(|e| Denied(ErrorCode::Internal, e.to_string()))? - .into_iter() - .map(|(id, message)| HistoryEntry { id, message }) - .collect(); + let user = self.user()?; + let messages = hub.history_v1(&user, &target, before, limit).await?; Ok(vec![ServerMsg::History { messages }]) } + ClientMsg::Enable { features } => { + self.user()?; + let all: Vec = hub + .capabilities() + .into_iter() + .filter(|c| { + [feature::PINS, feature::REACTIONS, feature::TOPICS].contains(&c.as_str()) + }) + .collect(); + let chosen: HashSet = if features.is_empty() { + all.iter().cloned().collect() + } else { + features.into_iter().filter(|f| all.contains(f)).collect() + }; + let mut list: Vec = chosen.iter().cloned().collect(); + list.sort(); + self.enabled = Some(chosen); + Ok(vec![ServerMsg::Enabled { features: list }]) + } + ClientMsg::Permissions { channel } => { + let user = self.user()?; + let actions = hub.permissions(&user, channel).await?; + Ok(vec![ServerMsg::Permissions { channel, actions }]) + } + ClientMsg::QueryHistory(q) => { + let user = self.user()?; + Ok(vec![ServerMsg::HistoryPage(hub.history(&user, q).await?)]) + } + ClientMsg::Sync { target, since_rev, limit } => { + let user = self.user()?; + let (messages, rev, has_more) = hub.sync(&user, &target, since_rev, limit).await?; + Ok(vec![ServerMsg::SyncPage { target, messages, rev, has_more }]) + } + ClientMsg::Post { target, text, topic } => { + let user = self.user()?; + if !self.posts.allow(rt.limits.posts_per_window, rt.limits.post_window_secs) { + return Err(Denied(ErrorCode::RateLimited, "slow down".into())); + } + let entry = hub.post(&user, &target, &text, topic).await?; + Ok(vec![ServerMsg::Posted { entry }]) + } + ClientMsg::Pin { message_id } => { + hub.pin(&self.user()?, message_id).await?; + ok() + } + ClientMsg::Unpin { message_id } => { + hub.unpin(&self.user()?, message_id).await?; + ok() + } + ClientMsg::ListPins { target } => { + let pins = hub.pins(&self.user()?, &target).await?; + Ok(vec![ServerMsg::Pins { target, pins }]) + } + ClientMsg::React { message_id, emoji } => { + hub.react(&self.user()?, message_id, &emoji, true).await?; + ok() + } + ClientMsg::Unreact { message_id, emoji } => { + hub.react(&self.user()?, message_id, &emoji, false).await?; + ok() + } + ClientMsg::Reactors { message_id, emoji } => { + let users = hub.reactors(&self.user()?, message_id, &emoji).await?; + Ok(vec![ServerMsg::Reactors { message_id, emoji, users }]) + } + ClientMsg::CreateTopic { target, title, message_id } => { + let topic = hub.create_topic(&self.user()?, &target, &title, message_id).await?; + Ok(vec![ServerMsg::Topic { topic }]) + } + ClientMsg::UpdateTopic { topic_id, title, archived } => { + let topic = + hub.update_topic(&self.user()?, topic_id, title.as_deref(), archived).await?; + Ok(vec![ServerMsg::Topic { topic }]) + } + ClientMsg::ListTopics { target, include_archived } => { + let topics = hub.topics(&self.user()?, &target, include_archived).await?; + Ok(vec![ServerMsg::Topics { target, topics }]) + } + ClientMsg::CreateEvent { event } => { + Ok(vec![ServerMsg::Event { event: hub.create_event(&self.user()?, event).await? }]) + } + ClientMsg::UpdateEvent { id, event } => Ok(vec![ServerMsg::Event { + event: hub.update_event(&self.user()?, id, event).await?, + }]), + ClientMsg::DeleteEvent { id } => { + hub.delete_event(&self.user()?, id).await?; + ok() + } + ClientMsg::GetEvent { id } => { + Ok(vec![ServerMsg::Event { event: hub.get_event(&self.user()?, id).await? }]) + } + ClientMsg::ListEvents(q) => { + Ok(vec![ServerMsg::Events { events: hub.events(&self.user()?, q).await? }]) + } + ClientMsg::Rsvp { event_id, status } => Ok(vec![ServerMsg::Event { + event: hub.rsvp(&self.user()?, event_id, status).await?, + }]), + ClientMsg::SubscribeEvents => { + self.user()?; + hub.require(Feature::Events)?; + self.events = true; + ok() + } + ClientMsg::UnsubscribeEvents => { + self.events = false; + ok() + } + ClientMsg::RegisterStream(spec) => { + let stream = hub.register_stream(&self.user()?, spec).await?; + self.own_streams.push(stream.id.clone()); + Ok(vec![ServerMsg::Stream { stream }]) + } + ClientMsg::UpdateStream { stream_id, title, viewers } => { + let stream = hub.update_stream(&self.user()?, &stream_id, title, viewers).await?; + Ok(vec![ServerMsg::Stream { stream }]) + } + ClientMsg::UnregisterStream { stream_id } => { + hub.unregister_stream(&self.user()?, &stream_id).await?; + self.own_streams.retain(|s| *s != stream_id); + ok() + } + ClientMsg::ListStreams => { + let user = self.user()?; + hub.require(Feature::Streams)?; + Ok(vec![ServerMsg::Streams { streams: hub.streams_for(&user) }]) + } + ClientMsg::SubscribeStreams => { + let user = self.user()?; + hub.require(Feature::Streams)?; + self.streams = true; + Ok(vec![ServerMsg::Streams { streams: hub.streams_for(&user) }]) + } + ClientMsg::UnsubscribeStreams => { + self.streams = false; + ok() + } + ClientMsg::ListActivity { before, limit } => { + let (entries, has_more) = hub.activity(&self.user()?, before, limit).await?; + Ok(vec![ServerMsg::Activity { entries, has_more }]) + } + ClientMsg::SubscribeActivity => { + self.user()?; + hub.require(Feature::Activity)?; + self.activity = true; + ok() + } + ClientMsg::UnsubscribeActivity => { + self.activity = false; + ok() + } + ClientMsg::ConfigList => { + Ok(vec![ServerMsg::Config { entries: hub.config_list(&self.user()?).await? }]) + } + ClientMsg::ConfigGet { key } => Ok(vec![ServerMsg::ConfigValue { + entry: hub.config_get(&self.user()?, &key).await?, + }]), + ClientMsg::ConfigSet { key, value } => Ok(vec![ServerMsg::ConfigValue { + entry: hub.config_set(&self.user()?, &key, value).await?, + }]), + ClientMsg::ConfigReset { key } => Ok(vec![ServerMsg::ConfigValue { + entry: hub.config_reset(&self.user()?, &key).await?, + }]), + ClientMsg::ConfigReload => { + Ok(vec![ServerMsg::Config { entries: hub.config_reload(&self.user()?).await? }]) + } + ClientMsg::PermList => { + Ok(vec![ServerMsg::PermRules { rules: hub.perm_list(&self.user()?).await? }]) + } + ClientMsg::PermSet { action, rule } => Ok(vec![ServerMsg::PermRules { + rules: hub.perm_set(&self.user()?, action, Some(rule)).await?, + }]), + ClientMsg::PermReset { action } => Ok(vec![ServerMsg::PermRules { + rules: hub.perm_set(&self.user()?, action, None).await?, + }]), } } + async fn logged_in( + &mut self, + user: User, + token: String, + token_expires: i64, + ) -> Result, Denied> { + let capabilities = self.hub.user_capabilities(&user).await; + let uid = user.uid.clone(); + self.user = Some(user); + Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities }]) + } + + /// What to send this session for a hub event. + async fn push(&mut self, event: &HubEvent) -> Vec { + let Some(user) = self.user.clone() else { return Vec::new() }; + let hub = &self.hub; + let open = |target: &ChatTarget| self.open_chats.contains(target); + let visible = |channel: Option| channel.is_none_or(|c| hub.channel_visible(&user, c)); + let msg = match event { + HubEvent::Chat(entry) if open(&entry.message.target) => { + if self.enabled.is_some() { + ServerMsg::Message { entry: entry.clone() } + } else { + let mut message = entry.message.clone(); + // Show older clients which topic a post belongs to. + if let Some(topic) = entry.topic_id.and_then(|t| hub.db.topic(t).ok().flatten()) + { + message.text = hub + .runtime() + .topics + .relay_format + .replace("{topic}", &topic.title) + .replace("{text}", &message.text); + } + ServerMsg::ChatEvent { id: entry.id, message } + } + } + HubEvent::Pinned(pin) + if self.wants(Feature::Pins) && open(&pin.entry.message.target) => + { + ServerMsg::Pinned { target: pin.entry.message.target.clone(), pin: pin.clone() } + } + HubEvent::Unpinned { target, message_id, by } + if self.wants(Feature::Pins) && open(target) => + { + ServerMsg::Unpinned { + target: target.clone(), + message_id: *message_id, + by: by.clone(), + } + } + HubEvent::Reaction { target, message_id, emoji, user: by, added, count } + if self.wants(Feature::Reactions) && open(target) => + { + ServerMsg::Reaction { + target: target.clone(), + message_id: *message_id, + emoji: emoji.clone(), + user: by.clone(), + added: *added, + count: *count, + } + } + HubEvent::Topic(topic) if self.wants(Feature::Topics) && open(&topic.target) => { + ServerMsg::TopicUpdated { topic: topic.clone() } + } + HubEvent::Event(event) if self.events && visible(event.spec.channel) => { + ServerMsg::EventUpdated { event: self.personal(event) } + } + HubEvent::EventDeleted { id, channel } if self.events && visible(*channel) => { + ServerMsg::EventDeleted { id: *id } + } + HubEvent::Reminder { event, starts_in_ms } + if self.events && visible(event.spec.channel) => + { + ServerMsg::EventReminder { + event: self.personal(event), + starts_in_ms: *starts_in_ms, + } + } + HubEvent::StreamStarted(stream) if self.streams && visible(stream.channel) => { + ServerMsg::StreamStarted { stream: stream.clone() } + } + HubEvent::StreamUpdated(stream) if self.streams && visible(stream.channel) => { + ServerMsg::StreamUpdated { stream: stream.clone() } + } + HubEvent::StreamEnded { id, channel, reason } if self.streams && visible(*channel) => { + ServerMsg::StreamEnded { id: id.clone(), reason: reason.clone() } + } + HubEvent::Activity(entry) if self.activity && visible(entry.channel) => { + ServerMsg::ActivityAdded { entry: entry.clone() } + } + HubEvent::Capabilities + if self.enabled.is_some() || self.events || self.streams || self.activity => + { + let capabilities = hub.user_capabilities(&user).await; + ServerMsg::Capabilities { capabilities } + } + _ => return Vec::new(), + }; + vec![msg] + } + + /// An event with this user's own answer. + fn personal(&self, event: &EventInfo) -> EventInfo { + let uid = self.user.as_ref().map(|u| u.uid.as_str()); + self.hub.db.event(event.id, uid, false).ok().flatten().unwrap_or_else(|| event.clone()) + } + /// Send what changed in this user's view of the server (or a snapshot). fn presence_update(&mut self, snapshot: bool) -> Vec { let Some(user) = &self.user else { return Vec::new() }; @@ -238,5 +568,6 @@ impl Session { self.hub.remove_reader(cid); } } + self.hub.session_streams_closed(&self.own_streams); } } diff --git a/crates/voelin-gateway/src/settings.rs b/crates/voelin-gateway/src/settings.rs new file mode 100644 index 0000000..491bdf0 --- /dev/null +++ b/crates/voelin-gateway/src/settings.rs @@ -0,0 +1,322 @@ +//! Runtime settings: values stored in the database win over the command +//! line, environment, file and defaults ([`crate::config::Layers`]). +//! +//! Every change (set, reset, reload) builds a new [`Runtime`] and publishes +//! it on a watch channel; subsystems read the current value on use or wait +//! for changes, so nothing needs a restart. + +use std::sync::{Arc, Mutex}; + +use anyhow::{Result, anyhow, bail}; +use serde_json::Value; +use tokio::sync::watch; +use tracing::{info, warn}; +use voelin_gateway_proto::{Action, ConfigEntry, PermRuleInfo}; + +use crate::config::{KEYS, KeyDef, Layers, Runtime, Source, Values, key_def, perm_key, validate}; +use crate::db::Db; + +/// What a reload found. +#[derive(Debug, Default, PartialEq)] +pub struct ReloadReport { + /// Keys whose effective value changed. + pub changed: Vec, + /// Keys where the file has a different value than the database, which wins. + pub overridden: Vec, + /// Bootstrap keys changed in the file; they apply after a restart. + pub restart_needed: Vec, +} + +pub struct Settings { + layers: Mutex, + /// Values set at runtime, mirrored from the database. + db_values: Mutex, + tx: watch::Sender>, +} + +impl Settings { + /// Combine the sources with the values stored in `db`. Invalid stored + /// values (e.g. from an older version) are ignored with a warning. + pub fn new(layers: Layers, db: &Db) -> Result { + let mut db_values = Values::new(); + for (key, value) in db.config_values()? { + match key_def(&key).filter(|d| !d.bootstrap).map(|d| validate(d, value)) { + Some(Ok(v)) => { + db_values.insert(key, v); + } + Some(Err(error)) => warn!(%key, %error, "ignoring stored setting"), + None => warn!(%key, "ignoring stored setting of unknown key"), + } + } + let runtime = build(&layers, &db_values)?; + Ok(Self { + layers: Mutex::new(layers), + db_values: Mutex::new(db_values), + tx: watch::channel(Arc::new(runtime)).0, + }) + } + + /// The configuration file, if any. + pub fn path(&self) -> Option { + self.layers.lock().unwrap().path.clone() + } + + pub fn current(&self) -> Arc { + self.tx.borrow().clone() + } + + /// Changes as they happen. + pub fn subscribe(&self) -> watch::Receiver> { + self.tx.subscribe() + } + + fn entry_of(&self, def: &KeyDef, layers: &Layers, db_values: &Values) -> ConfigEntry { + let (value, source) = resolve(def, layers, db_values); + let mask = |v: Value| if def.secret && !v.is_null() { Value::from("***") } else { v }; + ConfigEntry { + key: def.key.to_string(), + value: mask(value), + source, + default: def.default_value(), + value_type: def.kind.name().to_string(), + description: def.description.to_string(), + bootstrap: def.bootstrap, + } + } + + pub fn entries(&self) -> Vec { + let layers = self.layers.lock().unwrap(); + let db_values = self.db_values.lock().unwrap(); + KEYS.iter().map(|d| self.entry_of(d, &layers, &db_values)).collect() + } + + pub fn entry(&self, key: &str) -> Option { + let def = key_def(key)?; + Some(self.entry_of(def, &self.layers.lock().unwrap(), &self.db_values.lock().unwrap())) + } + + /// Store a value at runtime; it applies at once. + pub fn set(&self, db: &Db, key: &str, value: Value, by: Option<&str>) -> Result { + let def = key_def(key).ok_or_else(|| anyhow!("unknown setting {key}"))?; + if def.bootstrap { + bail!("{key} is read at start only; change it in tsgw.toml, the environment or --set"); + } + let value = validate(def, value)?; + let mut db_values = self.db_values.lock().unwrap(); + let mut candidate = db_values.clone(); + candidate.insert(key.to_string(), value.clone()); + let layers = self.layers.lock().unwrap(); + let runtime = build(&layers, &candidate)?; + db.set_config(key, &value, by)?; + *db_values = candidate; + info!(key, %value, by, "setting changed"); + self.tx.send_replace(Arc::new(runtime)); + Ok(self.entry_of(def, &layers, &db_values)) + } + + /// Drop the runtime value; the key falls back to the lower sources. + pub fn reset(&self, db: &Db, key: &str, by: Option<&str>) -> Result { + let def = key_def(key).ok_or_else(|| anyhow!("unknown setting {key}"))?; + let mut db_values = self.db_values.lock().unwrap(); + let layers = self.layers.lock().unwrap(); + if db_values.remove(key).is_some() { + db.delete_config(key)?; + info!(key, by, "setting reset"); + self.tx.send_replace(Arc::new(build(&layers, &db_values)?)); + } + Ok(self.entry_of(def, &layers, &db_values)) + } + + /// Read the file again. Values stored at runtime keep winning; keys where + /// the file now differs from them are reported (and logged). + pub fn reload(&self) -> Result { + let mut layers = self.layers.lock().unwrap(); + let Some(path) = layers.path.clone() else { return Ok(ReloadReport::default()) }; + let file = Layers::read_file(&path)?; + let db_values = self.db_values.lock().unwrap(); + let new_layers = Layers { file, ..layers.clone() }; + let runtime = build(&new_layers, &db_values)?; + let mut report = ReloadReport::default(); + for def in KEYS { + let old = resolve(def, &layers, &db_values).0; + let new = resolve(def, &new_layers, &db_values).0; + let file_value = new_layers.file.get(def.key); + if def.bootstrap { + if layers.file.get(def.key) != file_value { + report.restart_needed.push(def.key.to_string()); + } + } else if old != new { + report.changed.push(def.key.to_string()); + } + if let (Some(stored), Some(file_value)) = (db_values.get(def.key), file_value) + && stored != file_value + { + report.overridden.push(def.key.to_string()); + info!( + key = def.key, + file = %file_value, + database = %stored, + "file differs from the value set at runtime, which wins (ConfigReset uses the file)" + ); + } + } + for key in &report.restart_needed { + warn!(%key, "changed in the file; applies after a restart"); + } + *layers = new_layers; + info!(path = %path.display(), changed = ?report.changed, "configuration reloaded"); + self.tx.send_replace(Arc::new(runtime)); + Ok(report) + } + + /// Rules of every action, with where they come from. + pub fn perm_rules(&self) -> Vec { + let layers = self.layers.lock().unwrap(); + let db_values = self.db_values.lock().unwrap(); + Action::ALL + .into_iter() + .map(|action| { + let def = key_def(&perm_key(action)).expect("perm key"); + let (value, source) = resolve(def, &layers, &db_values); + PermRuleInfo { + action, + rule: serde_json::from_value(value).ok().flatten(), + source, + default: def.description.split("default: ").nth(1).unwrap_or("").to_string(), + } + }) + .collect() + } +} + +fn resolve(def: &KeyDef, layers: &Layers, db_values: &Values) -> (Value, Source) { + match db_values.get(def.key) { + Some(v) if !def.bootstrap => (v.clone(), Source::Db), + _ => layers.resolve(def), + } +} + +fn build(layers: &Layers, db_values: &Values) -> Result { + Runtime::from_values(|def| resolve(def, layers, db_values).0) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use serde_json::json; + + use super::*; + use crate::config::{cli_values, env_values, file_values}; + + fn layers(file: &str, env: &[(&str, &str)], cli: &[&str]) -> Layers { + let env: Vec<(String, String)> = + env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + Layers { + path: None, + cli: cli_values(&cli.iter().map(|s| s.to_string()).collect::>()).unwrap(), + env: env_values(|name| env.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())) + .unwrap(), + file: file_values(file).unwrap(), + } + } + + #[test] + fn precedence_db_cli_env_file_default() { + let db = Db::in_memory().unwrap(); + let l = layers( + "[history]\nretention_days = 30\n[relay]\nidle_teardown_secs = 60\nnickname = \"File\"\nformat = \"<{nick}> {text}\"\n", + &[("TSGW_HISTORY_RETENTION_DAYS", "20"), ("TSGW_RELAY_NICKNAME", "Env")], + &["relay.nickname=Cli"], + ); + let s = Settings::new(l, &db).unwrap(); + let e = |k: &str| { + let e = s.entry(k).unwrap(); + (e.value, e.source) + }; + assert_eq!(e("relay.max_channel_relays"), (json!(6), Source::Default)); + assert_eq!(e("relay.format"), (json!("<{nick}> {text}"), Source::File)); + assert_eq!(e("history.retention_days"), (json!(20), Source::Env)); + assert_eq!(e("relay.nickname"), (json!("Cli"), Source::Cli)); + s.set(&db, "relay.nickname", json!("Db"), Some("admin")).unwrap(); + s.set(&db, "history.retention_days", json!(0), None).unwrap(); + assert_eq!(e("relay.nickname"), (json!("Db"), Source::Db)); + assert_eq!(s.current().history.retention_days, 0); + // Stored values survive a restart and still win. + let s2 = Settings::new( + layers("[relay]\nnickname = \"File\"\n", &[], &["relay.nickname=Cli"]), + &db, + ) + .unwrap(); + assert_eq!(s2.current().relay.nickname, "Db"); + // Reset falls back to the next source. + let entry = s.reset(&db, "relay.nickname", None).unwrap(); + assert_eq!((entry.value, entry.source), (json!("Cli"), Source::Cli)); + assert_eq!(s.current().relay.nickname, "Cli"); + } + + #[test] + fn changes_apply_live() { + let db = Db::in_memory().unwrap(); + let s = Settings::new(layers("", &[], &[]), &db).unwrap(); + let mut rx = s.subscribe(); + assert!(s.current().features.pins); + s.set(&db, "features.pins", json!(false), None).unwrap(); + assert!(rx.has_changed().unwrap()); + assert!(!rx.borrow_and_update().features.pins); + s.set(&db, "perm.pin", json!({"server_groups": [6]}), None).unwrap(); + assert_eq!(rx.borrow_and_update().perm.pin.as_ref().unwrap().server_groups, [6]); + let rules = s.perm_rules(); + let pin = rules.iter().find(|r| r.action == Action::Pin).unwrap(); + assert_eq!( + (pin.source, pin.rule.as_ref().unwrap().server_groups.clone()), + (Source::Db, vec![6]) + ); + assert!(pin.default.contains("moderators")); + } + + #[test] + fn rejects_invalid_and_bootstrap() { + let db = Db::in_memory().unwrap(); + let s = Settings::new(layers("", &[], &[]), &db).unwrap(); + assert!(s.set(&db, "history.retention_days", json!("x"), None).is_err()); + assert!(s.set(&db, "history.retention_days", json!(-1), None).is_err()); + assert!(s.set(&db, "auth.min_security_level", json!(300), None).is_err()); + assert!(s.set(&db, "query.addr", json!("1.2.3.4:1"), None).is_err()); + assert!(s.set(&db, "no.such", json!(1), None).is_err()); + assert!(db.config_values().unwrap().is_empty()); + // Secrets are masked. + let s = Settings::new(layers("[query]\npassword = \"pw\"\n", &[], &[]), &db).unwrap(); + assert_eq!(s.entry("query.password").unwrap().value, "***"); + assert!(s.entry("query.password").unwrap().bootstrap); + } + + #[test] + fn reload_keeps_db_values() { + let dir = std::env::temp_dir().join(format!("tsgw-reload-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tsgw.toml"); + let write = |text: &str| { + let mut f = std::fs::File::create(&path).unwrap(); + f.write_all(text.as_bytes()).unwrap(); + }; + write("[query]\naddr = \"a:1\"\n[relay]\nidle_teardown_secs = 60\nnickname = \"File\"\n"); + let db = Db::in_memory().unwrap(); + let s = Settings::new(Layers::load(&path, &[]).unwrap(), &db).unwrap(); + s.set(&db, "relay.nickname", json!("Db"), None).unwrap(); + write("[query]\naddr = \"b:2\"\n[relay]\nidle_teardown_secs = 90\nnickname = \"File2\"\n"); + let report = s.reload().unwrap(); + assert_eq!(report.changed, ["relay.idle_teardown_secs"]); + assert_eq!(report.overridden, ["relay.nickname"]); + assert_eq!(report.restart_needed, ["query.addr"]); + assert_eq!(s.current().relay.idle_teardown_secs, 90); + assert_eq!(s.current().relay.nickname, "Db"); + s.reset(&db, "relay.nickname", None).unwrap(); + assert_eq!(s.current().relay.nickname, "File2"); + // A broken file changes nothing. + write("[relay]\nidle_teardown_secs = \"x\"\n"); + assert!(s.reload().is_err()); + assert_eq!(s.current().relay.idle_teardown_secs, 90); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/voelin-gateway/src/streams.rs b/crates/voelin-gateway/src/streams.rs new file mode 100644 index 0000000..cef67d6 --- /dev/null +++ b/crates/voelin-gateway/src/streams.rs @@ -0,0 +1,353 @@ +//! Directory of running streams. +//! +//! TeamSpeak 6 does not tell clients that join later about streams that +//! are already running. Voelin streamers register theirs here; the gateway +//! drops entries when the streamer's client leaves or stops streaming +//! (`client_is_streaming`, when the server reports it), and lists clients +//! that stream without a registration as `detected` (no stream id). + +use std::collections::{BTreeMap, HashMap}; +use std::time::{Duration, Instant}; + +use serde_json::json; +use tracing::{debug, warn}; +use voelin_gateway_proto::{ + Action, ErrorCode, StreamEntry, StreamSource, StreamSpec, UserRef, activity_kind, +}; +use voelin_model::{ClientId, ClientInfo, Presence}; + +use crate::db::{Db, NewActivity}; +use crate::hub::{Denied, Feature, Hub, HubEvent, User, now_ms}; + +/// Presence may lag behind a registration (query sessions only see +/// `client_is_streaming` when they poll); give it this long. +pub const GRACE: Duration = Duration::from_secs(30); + +#[derive(Default)] +pub struct Directory { + entries: BTreeMap, + /// When registered entries were added or confirmed by presence. + seen: HashMap, +} + +impl Directory { + /// The entries stored before a restart; checked against presence once + /// the observer has a snapshot. + pub fn load(db: &Db) -> Self { + let entries = db.streams().unwrap_or_else(|error| { + warn!(%error, "could not read the stream directory"); + Vec::new() + }); + let now = Instant::now(); + Self { + seen: entries.iter().map(|e| (e.id.clone(), now)).collect(), + entries: entries.into_iter().map(|e| (e.id.clone(), e)).collect(), + } + } + + pub fn list(&self) -> Vec { + self.entries.values().cloned().collect() + } + + fn by_client(&self, client: ClientId) -> Vec<&StreamEntry> { + self.entries.values().filter(|e| e.client_id == Some(client)).collect() + } +} + +fn detected_id(client: ClientId) -> String { + format!("client/{client}") +} + +/// What changed after comparing the directory with presence. +enum Change { + Start(StreamEntry), + Update(StreamEntry), + End(String, &'static str), +} + +impl Hub { + pub fn streams_for(&self, user: &User) -> Vec { + let list = self.directory.lock().unwrap().list(); + list.into_iter() + .filter(|e| e.channel.is_none_or(|c| self.channel_visible(user, c))) + .collect() + } + + pub async fn register_stream( + &self, + user: &User, + spec: StreamSpec, + ) -> Result { + self.require(Feature::Streams)?; + self.require_allowed(user, Action::Stream, spec.channel).await?; + if spec.stream_id.is_empty() || spec.stream_id.starts_with("client/") { + return Err(Denied::bad("invalid stream id")); + } + let mut channel = spec.channel; + if let Some(clid) = spec.client_id { + let presence = self.observer.presence(); + let p = presence.read().unwrap(); + if let Some(client) = p.clients.get(&clid) { + if client.uid.as_deref() != Some(user.uid.as_str()) { + return Err(Denied::forbidden("that client is someone else")); + } + channel = channel.or(Some(client.channel)); + } + } + let quota = self.runtime().quota.streams_per_user; + { + let dir = self.directory.lock().unwrap(); + if let Some(existing) = dir.entries.get(&spec.stream_id) + && existing.streamer.uid != user.uid + { + return Err(Denied::forbidden("someone else registered this stream")); + } + let mine = dir + .entries + .values() + .filter(|e| e.streamer.uid == user.uid && e.id != spec.stream_id) + .count() as u64; + if quota > 0 && mine >= quota { + return Err(Denied::quota(format!("at most {quota} streams per user"))); + } + } + let entry = StreamEntry { + id: spec.stream_id.clone(), + stream_id: Some(spec.stream_id), + streamer: user.user_ref(), + client_id: spec.client_id, + channel, + title: spec.title, + kind: spec.kind, + started_ms: now_ms(), + viewers: spec.viewers, + source: StreamSource::Registered, + event_id: None, + }; + // A detected entry for the same client is replaced. + if let Some(clid) = spec.client_id { + self.end_stream(&detected_id(clid), "registered"); + } + let entry = self.start_stream(entry); + self.audit(Some(&user.uid), "stream", &entry.id); + Ok(entry) + } + + fn start_stream(&self, mut entry: StreamEntry) -> StreamEntry { + let rt = self.runtime(); + let window = rt.events.stream_link_minutes as i64 * 60_000; + let now = now_ms(); + if let Ok(events) = self.db.linkable_events(&entry.streamer.uid, now, window) { + for id in events { + if let Err(error) = self.db.set_live_stream(id, Some(&entry.id), now) { + warn!(%error, "could not link stream to event"); + continue; + } + entry.event_id = entry.event_id.or(Some(id)); + if let Ok(Some(event)) = self.db.event(id, None, false) { + self.emit(HubEvent::Event(event)); + } + } + } + let replaced = { + let mut dir = self.directory.lock().unwrap(); + dir.seen.insert(entry.id.clone(), Instant::now()); + dir.entries.insert(entry.id.clone(), entry.clone()).is_some() + }; + if let Err(error) = self.db.save_stream(&entry) { + warn!(%error, "could not store stream"); + } + if replaced { + self.emit(HubEvent::StreamUpdated(entry.clone())); + } else { + self.emit(HubEvent::StreamStarted(entry.clone())); + let title = + if entry.title.is_empty() { String::new() } else { format!(": {}", entry.title) }; + self.add_activity(NewActivity { + kind: activity_kind::STREAM_STARTED, + actor: Some(&entry.streamer), + channel: entry.channel, + ref_id: Some(entry.id.clone()), + text: format!("{} started streaming{title}", entry.streamer.name), + data: json!({ "title": entry.title, "kind": entry.kind, "event_id": entry.event_id, + "source": entry.source }), + }); + } + entry + } + + pub async fn update_stream( + &self, + user: &User, + id: &str, + title: Option, + viewers: Option, + ) -> Result { + self.require(Feature::Streams)?; + let entry = self.own_stream(user, id).await?; + let entry = StreamEntry { + title: title.unwrap_or(entry.title), + viewers: viewers.or(entry.viewers), + ..entry + }; + self.directory.lock().unwrap().entries.insert(entry.id.clone(), entry.clone()); + if let Err(error) = self.db.save_stream(&entry) { + warn!(%error, "could not store stream"); + } + self.emit(HubEvent::StreamUpdated(entry.clone())); + Ok(entry) + } + + pub async fn unregister_stream(&self, user: &User, id: &str) -> Result<(), Denied> { + self.require(Feature::Streams)?; + self.own_stream(user, id).await?; + self.end_stream(id, "stopped"); + Ok(()) + } + + /// An entry the user registered, or may moderate. + async fn own_stream(&self, user: &User, id: &str) -> Result { + let entry = self.directory.lock().unwrap().entries.get(id).cloned(); + let entry = entry.ok_or_else(|| Denied::not_found("stream"))?; + if entry.streamer.uid != user.uid + && !self.allowed(user, Action::Moderate, entry.channel).await? + { + return Err(Denied::new(ErrorCode::Forbidden, "not your stream")); + } + Ok(entry) + } + + /// Remove an entry (no-op if it is not there). + pub fn end_stream(&self, id: &str, reason: &str) { + let entry = { + let mut dir = self.directory.lock().unwrap(); + dir.seen.remove(id); + dir.entries.remove(id) + }; + let Some(entry) = entry else { return }; + debug!(id, reason, "stream ended"); + if let Err(error) = self.db.delete_stream(id) { + warn!(%error, "could not delete stream"); + } + let now = now_ms(); + for event in self.db.events_with_stream(id).unwrap_or_default() { + let _ = self.db.set_live_stream(event, None, now); + if let Ok(Some(event)) = self.db.event(event, None, false) { + self.emit(HubEvent::Event(event)); + } + } + self.emit(HubEvent::StreamEnded { + id: id.to_string(), + channel: entry.channel, + reason: reason.to_string(), + }); + self.add_activity(NewActivity { + kind: activity_kind::STREAM_ENDED, + actor: Some(&entry.streamer), + channel: entry.channel, + ref_id: Some(entry.id.clone()), + text: format!("{} stopped streaming", entry.streamer.name), + data: json!({ "reason": reason, "duration_ms": now - entry.started_ms }), + }); + } + + /// Bring the directory in line with presence: drop entries of clients + /// that left or stopped streaming, follow moves, list unregistered + /// streamers. `full` means `presence` is complete (a snapshot or resync). + pub(crate) fn reconcile_streams(&self, presence: &Presence, full: bool) { + if !self.feature_enabled(Feature::Streams) || presence.clients.is_empty() { + return; + } + let changes = { + let mut dir = self.directory.lock().unwrap(); + let mut changes = Vec::new(); + let mut confirmed = Vec::new(); + for entry in dir.entries.values() { + let Some(clid) = entry.client_id else { continue }; + let young = dir.seen.get(&entry.id).is_some_and(|t| t.elapsed() < GRACE); + match presence.clients.get(&clid) { + None if full && !young => changes.push(Change::End(entry.id.clone(), "left")), + None => {} + Some(c) if c.streaming == Some(false) && !young => { + changes.push(Change::End(entry.id.clone(), "stopped streaming")); + } + Some(c) => { + if c.streaming == Some(true) { + // Presence confirms it: the grace starts again for later lags. + confirmed.push(entry.id.clone()); + } + if Some(c.channel) != entry.channel { + let moved = StreamEntry { channel: Some(c.channel), ..entry.clone() }; + changes.push(Change::Update(moved)); + } + } + } + } + for id in confirmed { + dir.seen.insert(id, Instant::now()); + } + let unregistered = presence.clients.values().filter(|c| { + c.streaming == Some(true) && !c.is_query && dir.by_client(c.id).is_empty() + }); + changes.extend(unregistered.map(|c| Change::Start(detected(c)))); + changes + }; + for change in changes { + match change { + Change::Start(entry) => { + self.start_stream(entry); + } + Change::Update(entry) => { + self.directory.lock().unwrap().entries.insert(entry.id.clone(), entry.clone()); + let _ = self.db.save_stream(&entry); + self.emit(HubEvent::StreamUpdated(entry)); + } + Change::End(id, reason) => self.end_stream(&id, reason), + } + } + } + + /// A client left: its streams end at once. + pub(crate) fn client_left(&self, client: ClientId) { + let ids: Vec = + self.directory.lock().unwrap().by_client(client).iter().map(|e| e.id.clone()).collect(); + for id in ids { + self.end_stream(&id, "left"); + } + } + + /// Entries without a client id end with the session that registered them. + pub(crate) fn session_streams_closed(&self, ids: &[String]) { + for id in ids { + let orphan = self + .directory + .lock() + .unwrap() + .entries + .get(id) + .is_some_and(|e| e.client_id.is_none()); + if orphan { + self.end_stream(id, "streamer disconnected"); + } + } + } +} + +fn detected(client: &ClientInfo) -> StreamEntry { + StreamEntry { + id: detected_id(client.id), + stream_id: None, + streamer: UserRef { + uid: client.uid.clone().unwrap_or_default(), + name: client.nickname.clone(), + }, + client_id: Some(client.id), + channel: Some(client.channel), + title: String::new(), + kind: String::new(), + started_ms: now_ms(), + viewers: None, + source: StreamSource::Detected, + event_id: None, + } +} diff --git a/crates/voelin-gateway/src/tasks.rs b/crates/voelin-gateway/src/tasks.rs new file mode 100644 index 0000000..e15361e --- /dev/null +++ b/crates/voelin-gateway/src/tasks.rs @@ -0,0 +1,228 @@ +//! Background tasks: chat pumps, relay teardown, stream tracking, retention, +//! event reminders, and applying setting changes as they happen. + +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use serde_json::json; +use tokio::sync::broadcast; +use tokio::sync::broadcast::error::RecvError; +use tracing::{info, warn}; +use voelin_gateway_proto::activity_kind; +use voelin_model::{ChatTarget, PresenceDelta}; +use voelin_observer::{ObserverEvent, RelayEvent}; + +use crate::db::NewActivity; +use crate::hub::{Feature, Hub, HubEvent, now_ms, now_secs}; + +pub fn spawn_all(hub: &Arc) { + tokio::spawn(pump_observer(hub.clone())); + tokio::spawn(pump_relays(hub.clone(), hub.relays().subscribe())); + tokio::spawn(teardown_idle_relays(hub.clone())); + tokio::spawn(prune(hub.clone())); + tokio::spawn(reminders(hub.clone())); + tokio::spawn(apply_settings(hub.clone())); + tokio::spawn(check_streams(hub.clone())); + if let Some(path) = hub.settings.path() { + tokio::spawn(watch_file(hub.clone(), path)); + } +} + +/// Server chat and presence changes seen by the observer. +async fn pump_observer(hub: Arc) { + let mut events = hub.observer.subscribe(); + loop { + match events.recv().await { + Ok(ObserverEvent::Chat(msg)) if msg.target == ChatTarget::Server => { + if !msg.author_id.is_some_and(|id| hub.is_own_client(id)) { + hub.publish_incoming(msg); + } + } + Ok(ObserverEvent::Delta(PresenceDelta::ClientLeft { id })) => hub.client_left(id), + Ok(ObserverEvent::Delta( + PresenceDelta::ClientJoined(_) + | PresenceDelta::ClientChanged(_) + | PresenceDelta::ClientMoved { .. }, + )) => { + let presence = hub.observer.presence(); + let presence = presence.read().unwrap().clone(); + hub.reconcile_streams(&presence, false); + } + Ok(ObserverEvent::Snapshot(_)) | Err(RecvError::Lagged(_)) => { + let presence = hub.observer.presence(); + let presence = presence.read().unwrap().clone(); + hub.reconcile_streams(&presence, true); + } + Ok(_) => {} + Err(RecvError::Closed) => return, + } + } +} + +/// The observer's poll does not produce events for changes it cannot see +/// as deltas; check the directory against presence now and then. +async fn check_streams(hub: Arc) { + let mut tick = tokio::time::interval(Duration::from_secs(15)); + loop { + tick.tick().await; + let presence = hub.observer.presence(); + let presence = presence.read().unwrap().clone(); + hub.reconcile_streams(&presence, true); + } +} + +/// Channel chat seen by one relay pool; subscribed before the pool opens +/// any relay, so nothing is missed when the pool is rebuilt. Ends with the pool. +pub async fn pump_relays(hub: Arc, mut events: broadcast::Receiver) { + loop { + match events.recv().await { + Ok(RelayEvent::Message(msg)) => { + if !msg.author_id.is_some_and(|id| hub.is_own_client(id)) { + hub.publish_incoming(msg); + } + } + Ok(RelayEvent::Closed { channel, reason }) => { + warn!(channel, %reason, "relay closed"); + } + Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => return, + } + } +} + +async fn teardown_idle_relays(hub: Arc) { + loop { + let rt = hub.runtime(); + let wait = Duration::from_secs(rt.relay.idle_teardown_secs.clamp(1, 15)); + tokio::time::sleep(wait).await; + let rt = hub.runtime(); + for cid in hub.idle_relays(&rt) { + hub.relays().close(cid).await; + } + } +} + +/// Retention: at start, hourly, and whenever a retention setting changes. +async fn prune(hub: Arc) { + let mut changes = hub.settings.subscribe(); + loop { + let rt = hub.runtime(); + let now = now_ms(); + let day = 86_400_000; + if rt.history.retention_days > 0 { + let cutoff = now - rt.history.retention_days as i64 * day; + match hub.db.prune_messages(cutoff) { + Ok(n) if n > 0 => info!(messages = n, "pruned history"), + Ok(_) => {} + Err(error) => warn!(%error, "pruning history failed"), + } + } + if rt.activity.retention_days > 0 + && let Err(error) = hub.db.prune_activity(now - rt.activity.retention_days as i64 * day) + { + warn!(%error, "pruning activity failed"); + } + if let Err(error) = hub.db.prune_tokens(now_secs()) { + warn!(%error, "pruning tokens failed"); + } + let (history, activity) = (rt.history.retention_days, rt.activity.retention_days); + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(3600)) => {} + _ = async { + while changes.changed().await.is_ok() { + let rt = changes.borrow_and_update().clone(); + if rt.history.retention_days != history || rt.activity.retention_days != activity { + break; + } + } + } => {} + } + } +} + +/// Reminders before events start, and an activity entry when they do. +async fn reminders(hub: Arc) { + let mut tick = tokio::time::interval(Duration::from_secs(5)); + let mut changes = hub.settings.subscribe(); + // Catch reminders due shortly before a restart. + let mut last = now_ms() - 60_000; + loop { + tokio::select! { + _ = tick.tick() => {} + // New reminder times apply at once. + r = changes.changed() => if r.is_err() { return }, + } + if !hub.feature_enabled(Feature::Events) { + last = now_ms(); + continue; + } + let now = now_ms(); + let offsets = hub.runtime().events.reminder_minutes.clone(); + for offset in offsets { + let offset_ms = offset as i64 * 60_000; + let due = hub.db.events_starting(last + offset_ms, now + offset_ms).unwrap_or_default(); + for event in due { + if hub.db.mark_notice(event.id, offset as i64).unwrap_or(false) { + let starts_in_ms = event.spec.start_ms - now; + hub.emit(HubEvent::Reminder { event, starts_in_ms }); + } + } + } + // Offset -1: the event started. + for event in hub.db.events_starting(last, now).unwrap_or_default() { + if hub.db.mark_notice(event.id, -1).unwrap_or(false) { + hub.add_activity(NewActivity { + kind: activity_kind::EVENT_STARTING, + actor: Some(&event.creator), + channel: event.spec.channel, + ref_id: Some(event.id.to_string()), + text: format!("{} is starting", event.spec.title), + data: json!({ "title": event.spec.title, "kind": event.spec.kind, + "live_stream": event.live_stream }), + }); + } + } + last = now; + } +} + +/// Apply setting changes that need more than reading the new value. +async fn apply_settings(hub: Arc) { + let mut changes = hub.settings.subscribe(); + let mut old = changes.borrow_and_update().clone(); + while changes.changed().await.is_ok() { + let new = changes.borrow_and_update().clone(); + if new.relay.nickname != old.relay.nickname { + hub.rebuild_relays(&new.relay.nickname).await; + } + if new.relay.pinned_channels != old.relay.pinned_channels { + hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels).await; + } + let features_changed = Feature::ALL.iter().any(|f| f.enabled(&old) != f.enabled(&new)); + if features_changed || new.perm.admin != old.perm.admin { + hub.emit(HubEvent::Capabilities); + } + if new.features.streams && !old.features.streams { + let presence = hub.observer.presence(); + let presence = presence.read().unwrap().clone(); + hub.reconcile_streams(&presence, true); + } + old = new; + } +} + +/// Reload the file when it changes (checked every few seconds). +async fn watch_file(hub: Arc, path: std::path::PathBuf) { + let modified = |p: &std::path::Path| std::fs::metadata(p).and_then(|m| m.modified()).ok(); + let mut last: Option = modified(&path); + loop { + tokio::time::sleep(Duration::from_secs(5)).await; + let now = modified(&path); + if now != last { + last = now; + if let Err(error) = hub.settings.reload() { + warn!(error = format!("{error:#}"), "not reloading the changed configuration"); + } + } + } +} diff --git a/crates/voelin-gateway/src/tests/fake.rs b/crates/voelin-gateway/src/tests/fake.rs new file mode 100644 index 0000000..51e5dd3 --- /dev/null +++ b/crates/voelin-gateway/src/tests/fake.rs @@ -0,0 +1,270 @@ +//! A fake TeamSpeak 3 ServerQuery server (raw TCP) with just enough state +//! for the gateway: channels, online clients, the client database, groups, +//! permissions, and a log of what was posted. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use voelin_query::{Command, escape}; + +/// Permission ids the fake server uses. +pub const JOIN_POWER: u32 = 1; +pub const SUBSCRIBE_POWER: u32 = 3; +pub const CHANNEL_TEXT: u32 = 4; +pub const SERVER_TEXT: u32 = 5; +pub const VIRTUALSERVER_MODIFY_NAME: u32 = 8; + +const PERMS: &[(&str, u32)] = &[ + ("i_channel_join_power", JOIN_POWER), + ("i_channel_needed_join_power", 2), + ("i_channel_subscribe_power", SUBSCRIBE_POWER), + ("b_client_channel_textmessage_send", CHANNEL_TEXT), + ("b_client_server_textmessage_send", SERVER_TEXT), + ("b_channel_join_ignore_password", 6), + ("b_channel_modify_name", 7), + ("b_virtualserver_modify_name", VIRTUALSERVER_MODIFY_NAME), +]; + +#[derive(Clone, Debug)] +pub struct Online { + pub clid: u16, + pub cid: u64, + pub uid: String, + pub nickname: String, + pub server_groups: Vec, + pub streaming: bool, +} + +#[derive(Default)] +pub struct State { + pub online: Vec, + /// uid to (cldbid, nickname). + pub known: HashMap, + /// Extra permissions per cldbid: (perm, value) at server group level. + pub perms: HashMap>, + pub server_groups: HashMap>, + /// (target mode, channel of the posting connection, text) + pub posted: Vec<(u8, u64, String)>, + /// Nicknames set with clientupdate. + pub nicknames: Vec, + /// Connections that registered for server events (the observer). + observers: Vec>, + /// Relay connections by channel. + relays: Vec<(u64, mpsc::UnboundedSender)>, + next_clid: u16, +} + +#[derive(Clone)] +pub struct FakeServer { + pub addr: SocketAddr, + pub state: Arc>, +} + +impl FakeServer { + pub async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() })); + let server = Self { addr, state }; + let s = server.clone(); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + tokio::spawn(s.clone().connection(stream)); + } + }); + server + } + + /// A user known to the server's database (connected with voice once). + pub fn add_known(&self, uid: &str, cldbid: u64, nickname: &str, groups: &[u64]) { + let mut s = self.state.lock().unwrap(); + s.known.insert(uid.to_string(), (cldbid, nickname.to_string())); + s.server_groups.insert(cldbid, groups.to_vec()); + } + + pub fn grant(&self, cldbid: u64, perm: u32, value: i64) { + self.state.lock().unwrap().perms.entry(cldbid).or_default().push((perm, value)); + } + + pub fn add_online(&self, client: Online) { + self.state.lock().unwrap().online.push(client); + } + + /// Send an event to the observer's connections. + pub fn notify_observers(&self, line: &str) { + for tx in &self.state.lock().unwrap().observers { + let _ = tx.send(line.to_string()); + } + } + + /// Someone writes in a channel (seen by its relay). + pub fn say_in_channel(&self, cid: u64, name: &str, uid: &str, text: &str) { + let line = format!( + "notifytextmessage targetmode=2 msg={} invokerid=77 invokername={} invokeruid={}", + escape(text), + escape(name), + escape(uid) + ); + for (c, tx) in &self.state.lock().unwrap().relays { + if *c == cid { + let _ = tx.send(line.clone()); + } + } + } + + pub fn posted(&self) -> Vec<(u8, u64, String)> { + self.state.lock().unwrap().posted.clone() + } + + async fn connection(self, stream: tokio::net::TcpStream) { + let (r, mut w) = stream.into_split(); + let mut lines = BufReader::new(r).lines(); + let (tx, mut rx) = mpsc::unbounded_channel::(); + let clid = { + let mut s = self.state.lock().unwrap(); + s.next_clid += 1; + s.next_clid + }; + let mut channel = 1u64; + if w.write_all(b"TS3\n\rWelcome to the fake ServerQuery interface.\n\r").await.is_err() { + return; + } + loop { + tokio::select! { + line = lines.next_line() => { + let Ok(Some(line)) = line else { return }; + let Some(cmd) = Command::parse(&line) else { continue }; + let reply = self.answer(&cmd, clid, &mut channel, &tx); + if w.write_all(reply.as_bytes()).await.is_err() { + return; + } + } + Some(event) = rx.recv() => { + if w.write_all(format!("{event}\n\r").as_bytes()).await.is_err() { + return; + } + } + } + } + } + + fn answer( + &self, + cmd: &Command, + clid: u16, + channel: &mut u64, + tx: &mpsc::UnboundedSender, + ) -> String { + let arg = |key: &str| { + cmd.rows.first().and_then(|r| r.iter().find(|(k, _)| k == key)).map(|(_, v)| v.clone()) + }; + let num = |key: &str| arg(key).and_then(|v| v.parse::().ok()).unwrap_or(0); + let ok = "error id=0 msg=ok\n\r".to_string(); + let empty = "error id=1281 msg=database\\sempty\\sresult\\sset\n\r".to_string(); + let data = |rows: Vec| { + if rows.is_empty() { empty.clone() } else { format!("{}\n\r{ok}", rows.join("|")) } + }; + let mut s = self.state.lock().unwrap(); + match cmd.name.as_str() { + "serverinfo" => data(vec![ + "virtualserver_name=Fake virtualserver_unique_identifier=fake-server-uid \ + virtualserver_version=3.13.7\\s[Build:\\s1] \ + virtualserver_needed_identity_security_level=0" + .into(), + ]), + "channellist" => data(vec![ + "cid=1 pid=0 channel_order=0 channel_name=Lobby channel_flag_default=1".into(), + "cid=2 pid=0 channel_order=1 channel_name=Games".into(), + "cid=3 pid=0 channel_order=2 channel_name=Staff channel_needed_subscribe_power=100" + .into(), + ]), + "permidgetbyname" => { + let name = arg("permsid").unwrap_or_default(); + match PERMS.iter().find(|(n, _)| *n == name) { + Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]), + None => "error id=2 msg=invalid\\spermission\n\r".into(), + } + } + "whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]), + "clientupdate" => { + if let Some(nick) = arg("client_nickname") { + s.nicknames.push(nick); + } + ok + } + "servernotifyregister" => { + match arg("event").as_deref() { + Some("server") => s.observers.push(tx.clone()), + Some("textchannel") => s.relays.push((*channel, tx.clone())), + _ => {} + } + ok + } + "clientmove" => { + *channel = num("cid"); + ok + } + "clientlist" => data( + s.online + .iter() + .map(|c| { + format!( + "clid={} cid={} client_database_id=0 client_nickname={} client_type=0 \ + client_unique_identifier={} client_servergroups={} client_is_streaming={}", + c.clid, + c.cid, + escape(&c.nickname), + escape(&c.uid), + c.server_groups + .iter() + .map(u64::to_string) + .collect::>() + .join(","), + u8::from(c.streaming) + ) + }) + .collect(), + ), + "banlist" => empty, + "clientdbfind" => { + let uid = arg("pattern").unwrap_or_default(); + data(s.known.get(&uid).map(|(id, _)| format!("cldbid={id}")).into_iter().collect()) + } + "clientdbinfo" => { + let id = num("cldbid"); + let nick = s.known.values().find(|(c, _)| *c == id).map(|(_, n)| n.clone()); + data(nick.map(|n| format!("client_nickname={}", escape(&n))).into_iter().collect()) + } + "servergroupsbyclientid" => data( + s.server_groups + .get(&num("cldbid")) + .map(|g| g.iter().map(|g| format!("sgid={g}")).collect()) + .unwrap_or_default(), + ), + "channelgroupclientlist" => empty, + "permoverview" => { + let cldbid = num("cldbid"); + let mut rows = vec![ + format!("t=0 id1=0 id2=0 p={JOIN_POWER} v=50 n=0 s=0"), + format!("t=0 id1=0 id2=0 p={SUBSCRIBE_POWER} v=50 n=0 s=0"), + format!("t=0 id1=0 id2=0 p={CHANNEL_TEXT} v=1 n=0 s=0"), + format!("t=0 id1=0 id2=0 p={SERVER_TEXT} v=1 n=0 s=0"), + ]; + for (perm, value) in s.perms.get(&cldbid).into_iter().flatten() { + rows.push(format!("t=0 id1=0 id2=0 p={perm} v={value} n=0 s=0")); + } + data(rows) + } + "sendtextmessage" => { + let mode = num("targetmode") as u8; + s.posted.push((mode, *channel, arg("msg").unwrap_or_default())); + ok + } + _ => ok, + } + } +} diff --git a/crates/voelin-gateway/src/tests/live.rs b/crates/voelin-gateway/src/tests/live.rs new file mode 100644 index 0000000..e65ce7c --- /dev/null +++ b/crates/voelin-gateway/src/tests/live.rs @@ -0,0 +1,105 @@ +//! Against a real TeamSpeak server and a running tsgw (ignored by default): +//! +//! ```sh +//! cargo run -p voelin-gateway -- --config dev/tsgw-ts3.toml & +//! TSGW_LIVE_URL=ws://127.0.0.1:7787/v1 \ +//! TSGW_LIVE_IDENTITY=dev/.state/ts3-gateway-user.json \ +//! TSGW_LIVE_ADMIN=dev/.state/ts3-admin.json \ +//! cargo test -p voelin-gateway live -- --ignored --nocapture +//! ``` +//! +//! The identities must have connected to the server with voice once +//! (`scripts/it-smoke.sh` leaves such files in `dev/.state`); the admin one +//! must be in the Server Admin group. + +use serde_json::json; +use tsproto_types::crypto::EccKeyPrivP256; +use voelin_gateway_proto::client::{GatewayClient, Login, Push, connect}; +use voelin_gateway_proto::{ + Action, EventKind, EventSpec, HistoryQuery, PermRule, RsvpStatus, StreamSpec, feature, +}; +use voelin_model::ChatTarget; + +use super::expect; +use crate::hub::now_ms; + +async fn login(var: &str) -> (GatewayClient, tokio::sync::mpsc::UnboundedReceiver) { + let url = std::env::var("TSGW_LIVE_URL").expect("TSGW_LIVE_URL"); + let path = std::env::var(var).unwrap_or_else(|_| panic!("{var}")); + let file: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let key = EccKeyPrivP256::import_str(file["key"].as_str().unwrap()).unwrap(); + let key_offset = file["counter"].as_u64().unwrap(); + connect(&url, Login::Identity { key, key_offset }).await.unwrap() +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs a running tsgw and TeamSpeak server"] +async fn live_gateway() { + let (user, mut user_rx) = login("TSGW_LIVE_IDENTITY").await; + let (admin, _admin_rx) = login("TSGW_LIVE_ADMIN").await; + println!("capabilities: user {:?}, admin {:?}", user.capabilities(), admin.capabilities()); + assert!(admin.has(feature::ADMIN), "the admin identity is not a Server Admin"); + let lobby = ChatTarget::Channel(1); + user.enable(Vec::new()).await.unwrap(); + user.open_chat(lobby.clone()).await.unwrap(); + admin.open_chat(lobby.clone()).await.unwrap(); + + let token = format!("live-{}", now_ms()); + let posted = user.post(lobby.clone(), format!("hello {token}"), None).await.unwrap(); + println!("posted #{} rev {}", posted.id, posted.rev); + admin.pin(posted.id).await.unwrap(); + expect(&mut user_rx, "pinned", |p| matches!(p, Push::Pinned { .. })).await; + user.react(posted.id, "🎉".into()).await.unwrap(); + let topic = + user.create_topic(lobby.clone(), format!("topic {token}"), Some(posted.id)).await.unwrap(); + let in_topic = user.post(lobby.clone(), "in the topic".into(), Some(topic.id)).await.unwrap(); + let q = HistoryQuery { topic: Some(topic.id), ..HistoryQuery::latest(lobby.clone(), None) }; + assert_eq!(user.history(q).await.unwrap().messages[0].id, in_topic.id); + let page = user.history(HistoryQuery::latest(lobby.clone(), Some(5))).await.unwrap(); + let entry = page.messages.iter().find(|e| e.id == posted.id).unwrap(); + println!("history entry: pinned {} reactions {:?}", entry.pinned, entry.reactions); + assert!(entry.pinned && entry.reactions[0].me); + + user.subscribe_events().await.unwrap(); + let event = admin + .create_event(EventSpec { + title: format!("event {token}"), + start_ms: now_ms() + 3_600_000, + kind: EventKind::Stream, + channel: Some(1), + ..Default::default() + }) + .await + .unwrap(); + let answered = user.rsvp(event.id, Some(RsvpStatus::Maybe)).await.unwrap(); + assert_eq!(answered.maybe, 1); + admin.delete_event(event.id).await.unwrap(); + + user.subscribe_streams().await.unwrap(); + let stream = user + .register_stream(StreamSpec { + stream_id: token.clone(), + title: "live test".into(), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(user.streams().await.unwrap().iter().filter(|s| s.id == stream.id).count(), 1); + user.unregister_stream(stream.id).await.unwrap(); + + let before = admin.config_get("quota.history_page".into()).await.unwrap(); + admin.config_set("quota.history_page".into(), json!(1)).await.unwrap(); + assert_eq!( + user.history(HistoryQuery::latest(lobby.clone(), None)).await.unwrap().messages.len(), + 1 + ); + admin.config_reset("quota.history_page".into()).await.unwrap(); + println!("quota.history_page back to {} ({:?})", before.value, before.source); + admin.perm_set(Action::React, PermRule::default()).await.unwrap(); + assert!(user.react(posted.id, "👍".into()).await.is_err()); + admin.perm_reset(Action::React).await.unwrap(); + admin.unpin(posted.id).await.unwrap(); + let (feed, _) = user.activity(None, Some(10)).await.unwrap(); + println!("activity: {:?}", feed.iter().map(|e| &e.text).collect::>()); +} diff --git a/crates/voelin-gateway/src/tests/mod.rs b/crates/voelin-gateway/src/tests/mod.rs new file mode 100644 index 0000000..e268f35 --- /dev/null +++ b/crates/voelin-gateway/src/tests/mod.rs @@ -0,0 +1,535 @@ +//! The gateway in-process: hub, observer, relays and sessions against a +//! fake ServerQuery server, driven by the typed client over a real +//! WebSocket. + +mod fake; +mod live; + +use std::sync::Arc; +use std::time::Duration; + +use serde_json::json; +use tokio::sync::mpsc; +use tsproto_types::crypto::EccKeyPrivP256; +use voelin_gateway_proto::client::{ClientError, GatewayClient, Login, Push, connect}; +use voelin_gateway_proto::{ + Action, ErrorCode, EventKind, EventSpec, HistoryQuery, PermRule, RsvpStatus, StreamSource, + StreamSpec, UniqueIds, feature, +}; +use voelin_model::ChatTarget; + +use self::fake::{FakeServer, Online, VIRTUALSERVER_MODIFY_NAME}; +use crate::config::{Layers, file_values}; +use crate::hub::{Hub, now_ms}; + +const LOBBY: ChatTarget = ChatTarget::Channel(1); + +struct Fixture { + fake: FakeServer, + hub: Arc, + url: String, + dir: std::path::PathBuf, + people: [Person; 3], +} + +struct Person { + key: EccKeyPrivP256, + uid: String, +} + +impl Person { + fn new() -> Self { + let key = EccKeyPrivP256::create(); + let uid = UniqueIds::from_omega(&key.to_pub().to_ts()).ts3; + Self { key, uid } + } + + async fn connect(&self, fx: &Fixture) -> (GatewayClient, mpsc::UnboundedReceiver) { + connect(&fx.url, Login::Identity { key: self.key.clone(), key_offset: 0 }).await.unwrap() + } +} + +impl Fixture { + async fn start(name: &str, extra: &str) -> Self { + let fake = FakeServer::start().await; + let dir = std::env::temp_dir().join(format!("tsgw-it-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let toml = format!( + "[query]\ntransport = \"raw\"\naddr = \"{}\"\nallowlisted = true\n\ + [history]\npath = \"{}\"\n{extra}", + fake.addr, + dir.join("tsgw.db").display() + ); + // Alice (admin, online in the lobby as client 10), Bob (online as + // 11, server group 7) and Carol (not online). + let people = [Person::new(), Person::new(), Person::new()]; + let [alice, bob, carol] = &people; + fake.add_known(&alice.uid, 1, "Alice", &[6]); + fake.add_known(&bob.uid, 2, "Bob", &[7]); + fake.add_known(&carol.uid, 3, "Carol", &[8]); + fake.grant(1, VIRTUALSERVER_MODIFY_NAME, 1); + for (clid, p, nick, groups) in [(10, alice, "Alice", vec![6]), (11, bob, "Bob", vec![7])] { + fake.add_online(Online { + clid, + cid: 1, + uid: p.uid.clone(), + nickname: nick.into(), + server_groups: groups, + streaming: false, + }); + } + let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() }; + let hub = Hub::start(layers).await.unwrap(); + // Wait for the observer's first snapshot. + for _ in 0..100 { + if !hub.observer.presence().read().unwrap().clients.is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/v1", listener.local_addr().unwrap()); + let app = crate::router(hub.clone()); + tokio::spawn(async move { axum::serve(listener, app).await }); + Self { fake, hub, url, dir, people } + } + + fn people(&self) -> (&Person, &Person, &Person) { + let [a, b, c] = &self.people; + (a, b, c) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// The next push matching `pred`, skipping others. +async fn expect( + rx: &mut mpsc::UnboundedReceiver, + what: &str, + pred: impl Fn(&Push) -> bool, +) -> Push { + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + match tokio::time::timeout_at(deadline, rx.recv()).await { + Ok(Some(push)) if pred(&push) => return push, + Ok(Some(_)) => {} + Ok(None) => panic!("connection closed waiting for {what}"), + Err(_) => panic!("timed out waiting for {what}"), + } + } +} + +/// No push matching `pred` arrives for a moment. +async fn expect_none(rx: &mut mpsc::UnboundedReceiver, pred: impl Fn(&Push) -> bool) { + let deadline = tokio::time::Instant::now() + Duration::from_millis(300); + while let Ok(Some(push)) = tokio::time::timeout_at(deadline, rx.recv()).await { + assert!(!pred(&push), "unexpected {push:?}"); + } +} + +fn code(result: Result) -> ErrorCode { + match result { + Err(e) => e.code().unwrap_or_else(|| panic!("{e}")), + Ok(v) => panic!("expected an error, got {v:?}"), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn chat_pins_reactions_topics() { + let fx = Fixture::start("chat", "").await; + let (alice, bob, carol) = fx.people(); + let (a, mut a_rx) = alice.connect(&fx).await; + let (b, mut b_rx) = bob.connect(&fx).await; + let (c, mut c_rx) = carol.connect(&fx).await; + for f in [feature::PINS, feature::REACTIONS, feature::TOPICS, feature::EVENTS, feature::STREAMS] + { + assert!(b.has(f), "{f}"); + } + assert!(a.has(feature::ADMIN)); + assert!(!b.has(feature::ADMIN)); + assert_eq!(b.enable(Vec::new()).await.unwrap(), ["pins", "reactions", "topics"]); + a.enable(vec!["pins".into(), "reactions".into(), "topics".into()]).await.unwrap(); + // Carol is an older client: no enable. + for client in [&a, &b, &c] { + client.open_chat(LOBBY).await.unwrap(); + } + + let hello = b.post(LOBBY, "hello".into(), None).await.unwrap(); + assert_eq!((hello.message.author_name.as_str(), hello.message.text.as_str()), ("Bob", "hello")); + assert!(hello.id > 0 && hello.rev > 0); + let Push::Message(got) = expect(&mut a_rx, "message", |p| matches!(p, Push::Message(_))).await + else { + unreachable!() + }; + assert_eq!(got.id, hello.id); + let Push::Chat { id, message } = + expect(&mut c_rx, "chat event", |p| matches!(p, Push::Chat { .. })).await + else { + unreachable!() + }; + assert_eq!((id, message.text.as_str()), (hello.id, "hello")); + assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into()))); + + // Pins: moderators only by default; Alice is an admin. + assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden); + a.pin(hello.id).await.unwrap(); + let Push::Pinned { pin, .. } = + expect(&mut b_rx, "pinned", |p| matches!(p, Push::Pinned { .. })).await + else { + unreachable!() + }; + assert_eq!((pin.entry.id, pin.by.name.as_str()), (hello.id, "Alice")); + assert_eq!(b.pins(LOBBY).await.unwrap().len(), 1); + expect_none(&mut c_rx, |p| matches!(p, Push::Pinned { .. })).await; + + // Reactions: any emoji, counts, who reacted. + b.react(hello.id, "🦀".into()).await.unwrap(); + a.react(hello.id, "🦀".into()).await.unwrap(); + let push = + expect(&mut b_rx, "reaction", |p| matches!(p, Push::Reaction { count: 2, .. })).await; + assert!(matches!(push, Push::Reaction { added: true, ref emoji, .. } if emoji == "🦀")); + assert_eq!(b.reactors(hello.id, "🦀".into()).await.unwrap().len(), 2); + assert_eq!(code(b.react(hello.id, "no spaces".into()).await), ErrorCode::BadRequest); + let page = b.history(HistoryQuery::latest(LOBBY, None)).await.unwrap(); + let entry = page.messages.iter().find(|e| e.id == hello.id).unwrap(); + assert!(entry.pinned); + assert_eq!((entry.reactions[0].count, entry.reactions[0].me), (2, true)); + a.unreact(hello.id, "🦀".into()).await.unwrap(); + expect(&mut b_rx, "unreact", |p| matches!(p, Push::Reaction { added: false, count: 1, .. })) + .await; + + // Topics: relayed with a prefix, readable for official clients. + let topic = b.create_topic(LOBBY, "Plans".into(), Some(hello.id)).await.unwrap(); + let Push::TopicUpdated(t) = + expect(&mut a_rx, "topic", |p| matches!(p, Push::TopicUpdated(_))).await + else { + unreachable!() + }; + assert_eq!(t.id, topic.id); + let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap(); + assert_eq!(in_topic.topic_id, Some(topic.id)); + assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into()))); + expect( + &mut c_rx, + "prefixed chat event", + |p| matches!(p, Push::Chat { message, .. } if message.text == "[#Plans] saturday?"), + ) + .await; + // Someone in TeamSpeak answers in the topic format. + fx.fake.say_in_channel(1, "Dave", "dave-uid", "[#Plans] yes!"); + let Push::Message(answer) = expect( + &mut a_rx, + "answer", + |p| matches!(p, Push::Message(e) if e.message.author_name == "Dave"), + ) + .await + else { + unreachable!() + }; + assert_eq!((answer.topic_id, answer.message.text.as_str()), (Some(topic.id), "yes!")); + let q = HistoryQuery { topic: Some(topic.id), ..HistoryQuery::latest(LOBBY, None) }; + let texts: Vec = + b.history(q).await.unwrap().messages.into_iter().map(|e| e.message.text).collect(); + assert_eq!(texts, ["saturday?", "yes!"]); + let topics = a.topics(LOBBY, false).await.unwrap(); + assert_eq!((topics[0].message_count, topics[0].root_message_id), (2, Some(hello.id))); + assert_eq!( + code(c.update_topic(topic.id, Some("Mine".into()), None).await), + ErrorCode::Forbidden + ); + b.update_topic(topic.id, None, Some(true)).await.unwrap(); + assert_eq!(code(b.post(LOBBY, "late".into(), Some(topic.id)).await), ErrorCode::Forbidden); + + // Sync: what changed since the first post. + let (changed, rev, more) = c.sync(LOBBY, hello.rev, None).await.unwrap(); + assert!(!more && rev > hello.rev); + assert_eq!(changed.first().map(|e| e.id), Some(hello.id), "reactions bumped the revision"); + let (none, same, _) = c.sync(LOBBY, rev, None).await.unwrap(); + assert!(none.is_empty() && same == rev); + + // Cursors: after an id, oldest first. + let q = + HistoryQuery { after: Some(hello.id), limit: Some(1), ..HistoryQuery::latest(LOBBY, None) }; + let page = c.history(q).await.unwrap(); + assert_eq!((page.messages.len(), page.has_more), (1, true)); + assert_eq!(page.messages[0].id, in_topic.id); + + // Access: nobody reads a channel above their subscribe power. + assert_eq!(code(c.open_chat(ChatTarget::Channel(3)).await), ErrorCode::Forbidden); + assert_eq!(code(c.pin(999_999).await), ErrorCode::NotFound); +} + +#[tokio::test(flavor = "multi_thread")] +async fn unknown_types_keep_the_connection() { + use futures_util::{SinkExt, StreamExt}; + use tokio_tungstenite::tungstenite::Message; + let fx = Fixture::start("unknown", "").await; + let (ws, _) = tokio_tungstenite::connect_async(fx.url.as_str()).await.unwrap(); + let (mut tx, rx) = ws.split(); + let rx = rx.filter_map(async |m| match m { + Ok(Message::Text(t)) => serde_json::from_str::(t.as_str()).ok(), + _ => None, + }); + let mut rx = std::pin::pin!(rx); + assert_eq!(rx.next().await.unwrap()["type"], "hello"); + for (frame, want) in [ + (r#"{"v":1,"id":5,"type":"teleport","data":{}}"#, "unknown_type"), + (r#"{"v":1,"id":6,"type":"pin","data":{"message_id":"x"}}"#, "bad_request"), + (r#"{"v":1,"id":7,"type":"list_streams"}"#, "not_authenticated"), + ] { + tx.send(Message::Text(frame.into())).await.unwrap(); + let reply = rx.next().await.unwrap(); + assert_eq!( + (reply["type"].as_str(), reply["data"]["code"].as_str()), + (Some("error"), Some(want)) + ); + assert!(reply["id"].is_u64(), "{reply}"); + } + tx.send(Message::Text(r#"{"v":1,"id":8,"type":"ping"}"#.into())).await.unwrap(); + let pong = rx.next().await.unwrap(); + assert_eq!((pong["type"].as_str(), pong["id"].as_u64()), (Some("pong"), Some(8))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn events_streams_activity() { + let fx = Fixture::start("events", "[events]\nreminder_minutes = [30]\n").await; + let (alice, bob, _) = fx.people(); + let (a, mut a_rx) = alice.connect(&fx).await; + let (b, mut b_rx) = bob.connect(&fx).await; + a.subscribe_events().await.unwrap(); + a.subscribe_activity().await.unwrap(); + assert!(a.subscribe_streams().await.unwrap().is_empty()); + b.subscribe_streams().await.unwrap(); + + let start = now_ms() + 3_000; + let spec = EventSpec { + title: "Speedrun".into(), + start_ms: start, + end_ms: Some(start + 3_600_000), + channel: Some(1), + kind: EventKind::Stream, + stream_game: Some("Celeste".into()), + ..Default::default() + }; + let event = a.create_event(spec.clone()).await.unwrap(); + expect( + &mut a_rx, + "event created activity", + |p| matches!(p, Push::ActivityAdded(e) if e.kind == "event_created"), + ) + .await; + let bob_view = b.rsvp(event.id, Some(RsvpStatus::Going)).await.unwrap(); + assert_eq!((bob_view.going, bob_view.my_rsvp), (1, Some(RsvpStatus::Going))); + let push = + expect(&mut a_rx, "rsvp", |p| matches!(p, Push::EventUpdated(e) if e.going == 1)).await; + assert!(matches!(push, Push::EventUpdated(e) if e.my_rsvp.is_none())); + assert_eq!(a.event(event.id).await.unwrap().attendees.len(), 1); + assert_eq!(code(b.delete_event(event.id).await), ErrorCode::Forbidden); + let bad = EventSpec { end_ms: Some(start - 1), ..spec.clone() }; + assert_eq!(code(a.create_event(bad).await), ErrorCode::BadRequest); + assert_eq!(b.events(Default::default()).await.unwrap().len(), 1); + + // Reminder times change at runtime: now "when it starts". + a.config_set("events.reminder_minutes".into(), json!([0])).await.unwrap(); + let Push::EventReminder { event: reminded, .. } = + expect(&mut a_rx, "reminder", |p| matches!(p, Push::EventReminder { .. })).await + else { + unreachable!() + }; + assert_eq!(reminded.id, event.id); + expect( + &mut a_rx, + "starting activity", + |p| matches!(p, Push::ActivityAdded(e) if e.kind == "event_starting"), + ) + .await; + + // Alice (client 10) goes live: the directory lists it and links the event. + assert_eq!( + code( + b.register_stream(StreamSpec { + stream_id: "s-1".into(), + client_id: Some(10), + ..Default::default() + }) + .await + ), + ErrorCode::Forbidden + ); + let stream = a + .register_stream(StreamSpec { + stream_id: "s-1".into(), + client_id: Some(10), + title: "Any%".into(), + kind: "game".into(), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!((stream.channel, stream.event_id), (Some(1), Some(event.id))); + let Push::StreamStarted(seen) = + expect(&mut b_rx, "stream", |p| matches!(p, Push::StreamStarted(_))).await + else { + unreachable!() + }; + assert_eq!(seen.source, StreamSource::Registered); + expect( + &mut a_rx, + "live event", + |p| matches!(p, Push::EventUpdated(e) if e.live_stream.as_deref() == Some("s-1")), + ) + .await; + b.update_stream("s-1".into(), None, Some(3)).await.unwrap_err(); + a.update_stream("s-1".into(), None, Some(3)).await.unwrap(); + expect(&mut b_rx, "viewers", |p| matches!(p, Push::StreamUpdated(s) if s.viewers == Some(3))) + .await; + // A late client finds it. + assert_eq!(b.streams().await.unwrap()[0].id, "s-1"); + + // Alice's client leaves: the entry goes, the event is no longer live. + fx.fake.notify_observers("notifyclientleftview cfid=1 ctid=0 reasonid=8 clid=10"); + expect(&mut b_rx, "stream ended", |p| matches!(p, Push::StreamEnded { id, .. } if id == "s-1")) + .await; + expect( + &mut a_rx, + "not live", + |p| matches!(p, Push::EventUpdated(e) if e.id == event.id && e.live_stream.is_none()), + ) + .await; + assert!(b.streams().await.unwrap().is_empty()); + + // A client streaming without registering shows up as detected. + fx.fake.notify_observers( + "notifycliententerview cfid=0 ctid=2 reasonid=0 clid=12 client_unique_identifier=erin \ + client_nickname=Erin client_type=0 client_is_streaming=1", + ); + let Push::StreamStarted(detected) = + expect(&mut b_rx, "detected", |p| matches!(p, Push::StreamStarted(_))).await + else { + unreachable!() + }; + assert_eq!( + (detected.source, detected.stream_id, detected.channel), + (StreamSource::Detected, None, Some(2)) + ); + + let (feed, _) = b.activity(None, None).await.unwrap(); + let kinds: Vec<&str> = feed.iter().map(|e| e.kind.as_str()).collect(); + for kind in ["event_created", "event_starting", "stream_started", "stream_ended"] { + assert!(kinds.contains(&kind), "{kind} in {kinds:?}"); + } + a.delete_event(event.id).await.unwrap(); + expect(&mut a_rx, "deleted", |p| matches!(p, Push::EventDeleted(id) if *id == event.id)).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn admin_settings_apply_live() { + let fx = Fixture::start("admin", "[relay]\nformat = \"<{nick}> {text}\"\n").await; + let (alice, bob, _) = fx.people(); + let (a, _a_rx) = alice.connect(&fx).await; + let (b, mut b_rx) = bob.connect(&fx).await; + b.enable(Vec::new()).await.unwrap(); + b.open_chat(LOBBY).await.unwrap(); + + // Only admins administer. + assert_eq!(code(b.config_list().await), ErrorCode::Forbidden); + assert_eq!( + code(b.config_set("features.pins".into(), json!(false)).await), + ErrorCode::Forbidden + ); + let entries = a.config_list().await.unwrap(); + let format = entries.iter().find(|e| e.key == "relay.format").unwrap(); + assert_eq!(format.value, "<{nick}> {text}"); + assert_eq!(format.source, voelin_gateway_proto::ConfigSource::File); + assert!(entries.iter().find(|e| e.key == "query.addr").unwrap().bootstrap); + assert_eq!(code(a.config_set("query.addr".into(), json!("x:1")).await), ErrorCode::BadRequest); + assert_eq!(code(a.config_set("no.such.key".into(), json!(1)).await), ErrorCode::NotFound); + assert_eq!( + code(a.config_set("quota.history_page".into(), json!("many")).await), + ErrorCode::BadRequest + ); + + // Feature switches reach connected clients at once. + let first = b.post(LOBBY, "one".into(), None).await.unwrap(); + assert!(fx.fake.posted().contains(&(2, 1, " one".into()))); + let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap(); + assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db); + expect( + &mut b_rx, + "capabilities", + |p| matches!(p, Push::Capabilities(c) if !c.iter().any(|c| c == "pins")), + ) + .await; + assert!(!b.has(feature::PINS)); + assert_eq!(code(a.pin(first.id).await), ErrorCode::FeatureDisabled); + let entry = a.config_reset("features.pins".into()).await.unwrap(); + assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Default); + expect( + &mut b_rx, + "pins back", + |p| matches!(p, Push::Capabilities(c) if c.iter().any(|c| c == "pins")), + ) + .await; + + // Permission rules by server group. + assert!(!b.permissions(Some(1)).await.unwrap().contains(&Action::Pin)); + let rule = PermRule { server_groups: vec![7], ..Default::default() }; + let rules = a.perm_set(Action::Pin, rule).await.unwrap(); + let pin_rule = rules.iter().find(|r| r.action == Action::Pin).unwrap(); + assert_eq!(pin_rule.rule.as_ref().unwrap().server_groups, [7]); + assert!(b.permissions(Some(1)).await.unwrap().contains(&Action::Pin)); + b.pin(first.id).await.unwrap(); + a.perm_set(Action::React, PermRule::default()).await.unwrap(); + assert_eq!(code(b.react(first.id, "👍".into()).await), ErrorCode::Forbidden); + a.perm_reset(Action::React).await.unwrap(); + b.react(first.id, "👍".into()).await.unwrap(); + + // Quotas. + for i in 0..3 { + b.post(LOBBY, format!("m{i}"), None).await.unwrap(); + } + a.config_set("quota.history_page".into(), json!(2)).await.unwrap(); + let page = b.history(HistoryQuery::latest(LOBBY, Some(100))).await.unwrap(); + assert_eq!((page.messages.len(), page.has_more), (2, true)); + a.config_set("quota.pins_per_channel".into(), json!(1)).await.unwrap(); + assert_eq!(code(b.pin(page.messages[0].id).await), ErrorCode::QuotaExceeded); + // Bob posted four times so far: one more within a minute. + a.config_set("limits.post_window_secs".into(), json!(60)).await.unwrap(); + a.config_set("limits.posts_per_window".into(), json!(5)).await.unwrap(); + b.post(LOBBY, "allowed".into(), None).await.unwrap(); + assert_eq!(code(b.post(LOBBY, "too fast".into(), None).await), ErrorCode::RateLimited); + // 0: no limit. + a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap(); + + // Relay settings apply without a restart. + a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap(); + b.post(LOBBY, "two".into(), None).await.unwrap(); + assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into()))); + a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap(); + for _ in 0..100 { + if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1")); + b.post(LOBBY, "three".into(), None).await.unwrap(); + assert!(fx.fake.posted().contains(&(2, 1, "Bob: three".into()))); + // Channel chat from TeamSpeak still arrives through the new relay. + fx.fake.say_in_channel(1, "Dave", "dave", "after rename"); + expect( + &mut b_rx, + "relayed after rename", + |p| matches!(p, Push::Message(e) if e.message.text == "after rename"), + ) + .await; + + // Settings survive a restart of the hub's settings (they are in the database). + let stored = fx.hub.db.config_values().unwrap(); + assert!(stored.iter().any(|(k, v)| k == "relay.nickname" && v == "Bridge")); +} diff --git a/crates/voelin-gateway/tsgw.example.toml b/crates/voelin-gateway/tsgw.example.toml index 31ed2a9..4f355a3 100644 --- a/crates/voelin-gateway/tsgw.example.toml +++ b/crates/voelin-gateway/tsgw.example.toml @@ -1,15 +1,25 @@ # tsgw: companion gateway for invisible presence and channel chat. # Copy to tsgw.toml and adjust. See docs/gateway-admin.md. +# +# Two kinds of keys: +# - BOOTSTRAP keys (query login, addresses, database path) are read at start +# from this file, TSGW_ environment variables or `--set key=value`. +# Changing them needs a restart. +# - Everything else is a SEED: the value used unless an admin changes it at +# runtime (Voelin's admin screen / config_set). Values set at runtime are +# stored in the database and win over this file; `config_reset` goes back +# to it. Reload with SIGHUP (or just save: the file is checked every 5 s). +# Precedence: runtime (database) > --set > environment > this file > default. -# Signed into every login challenge. Defaults to listen.public_url. +# BOOTSTRAP. Signed into every login challenge. Defaults to listen.public_url. # gateway_id = "wss://gw.example.org/v1" [server] -# Voice port of the virtual server this gateway serves. +# BOOTSTRAP. Voice port of the virtual server this gateway serves. voice_port = 9987 [query] -# "ssh" (TeamSpeak 3 and 6) or "raw" (TeamSpeak 3 only). +# BOOTSTRAP. "ssh" (TeamSpeak 3 and 6) or "raw" (TeamSpeak 3 only). transport = "ssh" addr = "127.0.0.1:10022" user = "serveradmin" @@ -19,6 +29,7 @@ user = "serveradmin" allowlisted = false [listen] +# BOOTSTRAP. bind = "0.0.0.0:7788" # public_url = "wss://gw.example.org/v1" @@ -33,11 +44,61 @@ token_ttl_hours = 720 nickname = "Chat Relay" format = "[{nick}] {text}" idle_teardown_secs = 120 +# Each relay is one query connection; stay below the server's per-IP limit. max_channel_relays = 6 # Channels relayed all the time, so their history is complete. pinned_channels = [] [history] -enabled = true +# BOOTSTRAP: the database also holds tokens and runtime settings. path = "tsgw.db" -retention_days = 30 +enabled = true +# 0 keeps messages forever (pinned messages are always kept). +retention_days = 0 + +# Optional features; Voelin hides what is off. +[features] +pins = true +reactions = true +topics = true +events = true +streams = true +activity = true + +[topics] +# How topic posts appear in TeamSpeak; TeamSpeak posts in this form join the topic. +relay_format = "[#{topic}] {text}" + +[events] +# Remind subscribers this many minutes before an event (0: when it starts). +reminder_minutes = [15, 0] +stream_link_minutes = 60 + +[activity] +retention_days = 0 + +[limits] +# Per connection; 0 turns a limit off. +posts_per_window = 5 +post_window_secs = 5 +actions_per_window = 30 +action_window_secs = 10 + +# Quotas: 0 means none. +[quota] +history_page = 0 +pins_per_channel = 0 +topics_per_channel = 0 +events_per_user = 0 +reactions_per_message = 0 +reaction_bytes = 64 +message_bytes = 0 +streams_per_user = 0 + +# Who may do what, by TeamSpeak server group or channel group ids. Without +# a rule an action has its default (see docs/gateway-admin.md). +[perm] +# pin = { server_groups = [6], channel_groups = [5] } +# create_event = { server_groups = [6, 7] } +# admin = { server_groups = [6] } +# react = { everyone = true } diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index 9672a08..d127964 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -3,7 +3,12 @@ `tsgw` lets users of Voelin see who is in which channel and read and write channel chat **without joining voice**, on a server you administer. It holds ServerQuery sessions (invisible to normal users of the official clients) -and serves users over a WebSocket (`tsgw.v1+json`, see `crates/voelin-gateway-proto`). +and serves users over a WebSocket (`tsgw.v1+json`, see +[gateway-protocol.md](gateway-protocol.md)). It also adds what TeamSpeak does +not have: pinned messages, reactions, topics, scheduled events, a directory +of running streams and an activity feed. Voelin shows these only on servers +with a gateway; official TeamSpeak clients do not see them (topic posts +appear in the channel as `[#topic] text`). ## What users get @@ -12,14 +17,22 @@ and serves users over a WebSocket (`tsgw.v1+json`, see `crates/voelin-gateway-pr | Presence | One query session watches the server; each user sees the channels their `i_channel_subscribe_power` allows, without query clients | | Channel chat | A relay query session is moved into each channel someone opened; it forwards what is said and posts users' messages as `[Nick] text` | | Server chat | Read by the watcher, posted by the gateway's lookup session | -| History | Relayed messages are stored (SQLite) and can be paged | +| History | Relayed messages are stored (SQLite) with stable ids; pages by id or time in both directions, without a size limit unless you set one; `sync` returns what changed since a revision | +| Pins | Pinned messages per chat, kept even when older messages are pruned | +| Reactions | Any emoji on any stored message, with counts and who reacted | +| Topics | Threads in a chat, started from a message or standalone; posts are relayed as `[#Title] text`, and TeamSpeak posts in that form join the topic | +| Events | Scheduled events per server or channel, with RSVP (going / maybe / not going) and reminders; stream events show when the host goes live | +| Stream directory | Voelin streamers register running TeamSpeak 6 streams, so viewers who join later can find them; entries go when the streamer leaves or stops, and clients that stream without registering are listed as detected (without a stream id) | +| Activity feed | Streams started and stopped, events scheduled, starting or cancelled, topics started, messages pinned | The nickname in relayed posts is the one the server has on record for the user's identity (from `clientdbinfo`), not something the user can choose. +Each feature can be turned off (`features.*`); pins, reactions and topics +need `history.enabled`. ## Authentication and authorization -Users log in by signing a challenge with their TeamSpeak identity key. The +Users log in by signing a challenge with their TeamSpeak identity. The gateway derives the unique id (SHA-1 of the public key on TeamSpeak 3, SHA-256 on TeamSpeak 6) and looks it up with `clientdbfind`, so **an identity must have connected to the server with voice once** before it can use the gateway. @@ -35,11 +48,18 @@ Checks, mirroring what the user could do with a real connection `b_channel_join_ignore_password` - post in a channel: the above plus `b_client_channel_textmessage_send` - post in server chat: `b_client_server_textmessage_send` -- see a channel in presence: `i_channel_subscribe_power` (server level) ≥ the - channel's `channel_needed_subscribe_power` +- see a channel in presence (and its events, streams and activity): + `i_channel_subscribe_power` (server level) ≥ the channel's + `channel_needed_subscribe_power` -Posts are limited to 5 per 5 seconds per connection, and every login and post -is written to the audit table. +Pins, reactions and topics also need read (reactions, pins) or post (topics) +access to the chat. On top of that, each action has a permission rule, see +[Permission rules](#permission-rules). + +Posts are limited to `limits.posts_per_window` per `limits.post_window_secs` +per connection (5 per 5 s by default), other changes to +`limits.actions_per_window` per `limits.action_window_secs` (30 per 10 s). +Every login, post and settings change is written to the audit table. ## Setup @@ -47,8 +67,9 @@ is written to the audit table. `TSSERVER_QUERY_SSH_ENABLED=1` (the gateway needs events, so SSH, not HTTP). TeamSpeak 3: raw (10011) or SSH (10022). 2. Use a query login with enough rights for `clientdbfind`, `clientdbinfo`, - `permoverview`, `banlist`, `clientmove` and `sendtextmessage`, e.g. a - dedicated login in the Server Admin group. + `permoverview`, `banlist`, `clientmove`, `sendtextmessage`, + `servergroupsbyclientid` and `channelgroupclientlist`, e.g. a dedicated + login in the Server Admin group. 3. Put the gateway's IP into `query_ip_allowlist.txt` and set `query.allowlisted = true`. Otherwise the server's flood protection (10 commands / 3 s) applies and bans the gateway under load. @@ -85,7 +106,7 @@ sudo systemctl enable --now tsgw journalctl -u tsgw -f ``` -The audit database (`path = "tsgw.db"`) ends up in `/var/lib/tsgw`. The unit +The database (`history.path = "tsgw.db"`) ends up in `/var/lib/tsgw`. The unit (`packaging/linux/tsgw.service`) runs tsgw sandboxed: no write access outside that directory, network only. @@ -111,3 +132,138 @@ needed view power (100 by default). Server Admins, and third-party clients that ignore the rule, see the gateway's sessions. Relayed channels show the relay's posts under its own nickname (`Chat Relay `), so people in the channel can tell the messages come through the gateway. + +## Configuration + +`tsgw.toml` holds two kinds of keys (the example marks them): + +- **Bootstrap** keys are needed before the database opens: `gateway_id`, + `server.voice_port`, `query.*` (transport, address, login, password, + `allowlisted`), `listen.bind`, `listen.public_url` and `history.path`. + They come from the file, the environment or the command line and apply + at start; changing them needs a restart. +- Everything else (history, relays, features, permission rules, quotas, + limits, reminders) is a **seed**: the value in use unless an admin changes + it at runtime. Runtime changes are stored in the gateway's database and + apply at once, without a restart. + +Where a value comes from, highest first: + +| Source | How | +|---|---| +| `db` | set at runtime (`config_set`, `perm_set`), stored in the database | +| `cli` | `tsgw --set history.retention_days=90` (repeatable) | +| `env` | `TSGW_`: upper case, dots become `_`, e.g. `TSGW_HISTORY_RETENTION_DAYS=90`, `TSGW_QUERY_PASSWORD=…`; lists as `1,2,3` or JSON, rules as JSON | +| `file` | `tsgw.toml` | +| `default` | built in | + +**Reload.** `SIGHUP` (`systemctl reload tsgw`), a changed file (checked every +5 s) or the `config_reload` admin command reads the file again. Values set at +runtime keep winning; the log names every key where the file now says +something else ("file differs from the value set at runtime"). Bootstrap keys +changed in the file are logged as needing a restart. A file that does not +parse changes nothing. `config_reset` drops a runtime value, so the key falls +back to the command line, environment, file or default. + +Changes apply live: relays pick up a new `relay.nickname` (the relay +sessions are replaced; channel chat keeps flowing), newly pinned channels +open, retention prunes at once, reminder times and quotas apply to the next +request, and connected apps get the new list of features. + +### Keys + +Numbers are non-negative; quotas and limits of 0 mean none. There are no +built-in caps on history pages, pins, topics, events or reactions: only what +you set here. + +| Key | Default | | +|---|---|---| +| `auth.require_server_groups` | `[]` | If not empty, users need one of these server groups | +| `auth.deny_uids` | `[]` | Unique ids that may never use the gateway | +| `auth.min_security_level` | `0` | On top of the server's own requirement | +| `auth.token_ttl_hours` | `720` | Lifetime of login tokens | +| `relay.nickname` | `"Chat Relay"` | Relay sessions are named ` `, the lookup session ` Gateway` | +| `relay.format` | `"[{nick}] {text}"` | How posts appear in TeamSpeak | +| `relay.idle_teardown_secs` | `120` | Close a relay this long after its last reader left | +| `relay.max_channel_relays` | `6` | Concurrent relays (0: no limit) | +| `relay.pinned_channels` | `[]` | Always relayed, so their history is complete | +| `history.enabled` | `true` | Store messages; pins, reactions and topics need it | +| `history.retention_days` | `0` | Delete older messages (0: keep forever; pinned messages are kept) | +| `features.pins`, `.reactions`, `.topics`, `.events`, `.streams`, `.activity` | `true` | Turn features off; apps hide them | +| `topics.relay_format` | `"[#{topic}] {text}"` | How topic posts appear in TeamSpeak; TeamSpeak posts in this form join the topic | +| `events.reminder_minutes` | `[15, 0]` | Remind event subscribers this many minutes before the start (0: when it starts) | +| `events.stream_link_minutes` | `60` | A stream by the host links to a stream event from this long before its start until this long after its end | +| `activity.retention_days` | `0` | Delete older activity (0: keep forever) | +| `limits.posts_per_window` / `limits.post_window_secs` | `5` / `5` | Chat posts per connection | +| `limits.actions_per_window` / `limits.action_window_secs` | `30` / `10` | Pins, reactions, topics, events, streams per connection | +| `quota.history_page` | `0` | Most messages per history page | +| `quota.pins_per_channel` | `0` | Pins per chat | +| `quota.topics_per_channel` | `0` | Open topics per chat | +| `quota.events_per_user` | `0` | Upcoming events per creator | +| `quota.reactions_per_message` | `0` | Different emoji per message | +| `quota.reaction_bytes` | `64` | Longest reaction | +| `quota.message_bytes` | `0` | Longest post (TeamSpeak splits long ones anyway) | +| `quota.streams_per_user` | `0` | Directory entries per user | +| `perm.` | unset | Permission rules, below | + +Before this version history was pruned after 30 days by default; now the +default keeps it. Set `history.retention_days = 30` to keep the old behaviour. + +### Admin commands + +Users with the `admin` permission see the `admin` capability and can send +(see [gateway-protocol.md](gateway-protocol.md#administration)): + +| Command | Does | +|---|---| +| `config_list` | Every key with value, source (`db`, `cli`, `env`, `file`, `default`), default, type, description and whether it is bootstrap; the query password is shown as `***` | +| `config_get {key}` | One key | +| `config_set {key, value}` | Store a value at runtime (JSON of the key's type); applies at once | +| `config_reset {key}` | Drop the runtime value | +| `config_reload` | Read the file again, like `SIGHUP` | +| `perm_list` | The rule of every action, its source and what the default allows | +| `perm_set {action, rule}` | Set a rule (same as `config_set perm.`) | +| `perm_reset {action}` | Back to the file's rule or the default | + +## Permission rules + +Each action has a rule: who may do it, by TeamSpeak server group ids and/or +channel group ids (in the channel concerned), or everyone: + +```toml +[perm] +pin = { server_groups = [6], channel_groups = [5] } # Server Admin, Channel Admin +create_event = { server_groups = [6, 7] } +react = { everyone = true } +``` + +A rule replaces the action's default; `{}` allows nobody. Users with `admin` +may do everything, and whoever may `moderate` a channel may also pin there. +Access to the chat itself (read, or post for topics) is always required. +Groups come from presence for users who are online and from +`servergroupsbyclientid` / `channelgroupclientlist` (cached 60 s) otherwise. + +| Action | Default without a rule | +|---|---| +| `react` | everyone who can read the chat | +| `pin` | moderators and admins | +| `create_topic` | everyone who can post in the chat | +| `create_event` | everyone who can post in the event's channel (server chat for server-wide events) | +| `rsvp` | everyone | +| `stream` | everyone (their own streams) | +| `moderate` | `b_channel_modify_name` in the channel (Channel Admin): edit or delete others' topics, events, streams and pins | +| `admin` | `b_virtualserver_modify_name` (Server Admin): settings and rules | + +Creators may always edit and delete their own topics, events and stream +entries. + +## Data + +The database (`history.path`, SQLite in WAL mode) holds login tokens, chat +messages with pins, reactions and topics, events and RSVPs, the stream +directory (so it survives a restart; entries whose client is gone are dropped +once the gateway sees the server), the activity feed, settings changed at +runtime and the audit log. The schema is versioned (`PRAGMA user_version`) +and migrated in place at start, keeping existing messages and their ids. +Message ids are never reused, even after pruning, so apps can merge history +with what they store locally. diff --git a/docs/gateway-protocol.md b/docs/gateway-protocol.md new file mode 100644 index 0000000..d55259b --- /dev/null +++ b/docs/gateway-protocol.md @@ -0,0 +1,183 @@ +# Gateway protocol (`tsgw.v1+json`) + +How Voelin talks to `tsgw` ([gateway-admin.md](gateway-admin.md)). The types +are in `crates/voelin-gateway-proto` (`messages.rs`, `types.rs`); its +`client` feature is a typed client (one async method per request, pushes as +`Push`), which the app uses through `voelin_core::gateway`. + +## Transport + +WebSocket to `…/v1`, subprotocol `tsgw.v1+json`, one JSON envelope per text +frame: + +```json +{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}} +``` + +The client picks `id` for requests; the answer carries the same `id`. +Pushes have no `id`. Version 1 only grows: new message types and optional +fields. Both sides ignore unknown fields. The gateway answers a type it does +not know with `error` / `unknown_type` (and a malformed message with +`bad_request`), with the request's `id`, and keeps the connection. + +Older clients never receive a type they do not know: the newer pushes only go +to clients that asked for them (`enable`, `subscribe_*`), and newer error +codes only answer newer requests. Enums that may grow (`ErrorCode`, +`EventKind`, `RsvpStatus`, `Action`, `StreamSource`, `ConfigSource`) have an +`unknown` fallback in the Rust types; activity kinds are plain strings. + +## Login and capabilities + +1. Gateway: `hello {gateway_id, server_uid, server_name, nonce, capabilities}`. +2. Client: `auth {omega, key_offset, ts, signature, nickname}`, an ECDSA + signature with the TeamSpeak identity over + `tsgw-auth-v1\n{gateway_id}\n{server_uid}\n{nonce}\n{ts}`, or + `resume {token, nickname}`. +3. Gateway: `auth_ok {uid, token, token_expires, capabilities}` or `error`. + +`capabilities` in `hello` lists the features enabled on the gateway; +`auth_ok` repeats them for this user and adds `admin` when the user may +administer the gateway. A `capabilities {capabilities}` push follows when an +admin turns a feature on or off (to clients that sent `enable` or subscribed +to something). Clients hide what is missing. + +| Capability | Meaning | +|---|---| +| `presence` | `subscribe_presence` | +| `relay` | channel and server chat | +| `history` | stored messages: `history`, `query_history`, `sync` | +| `pins`, `reactions`, `topics` | on stored messages | +| `events` | scheduled events | +| `streams` | stream directory | +| `activity` | activity feed | +| `admin` | configuration and permission rules (only in `auth_ok`) | + +## Original messages + +| Client → gateway | Answer | +|---|---| +| `subscribe_presence` / `unsubscribe_presence` | `presence_snapshot {seq, snapshot}`, then `presence_delta {seq, delta}` pushes / `ok` | +| `open_chat {target}` / `close_chat {target}` | `ok`; chat arrives as `chat_event {id, message}` (or `message`, below) | +| `send_chat {target, text}` | `ok` | +| `history {target, before?, limit}` | `history {messages}`, oldest first | +| `ping` | `pong` | + +`history` entries now also carry `topic_id`, `reactions`, `pinned` and +`rev` (all omitted when empty); `limit` is no longer capped at 200, only by +`quota.history_page` if an admin sets it. + +## Chat extensions + +**`enable {features}`** → `enabled {features}`. After it, messages in open +chats arrive as `message {entry}` instead of `chat_event`, with the pushes +of the listed features (`pins`, `reactions`, `topics`; empty: all). Clients +that do not send it see topic posts in `chat_event` with the topic prefix. + +A stored message (`HistoryEntry`): + +```json +{"id":42,"message":{"target":{"kind":"channel","id":5},"author_name":"Bob","author_uid":"…", + "text":"hi","ts_ms":1700000000123,"via_relay":true}, + "topic_id":3,"reactions":[{"emoji":"🦀","count":2,"me":true}],"pinned":true,"rev":1700000000200001} +``` + +`id` is stable and never reused; `ts_ms` is when the gateway saw it; `rev` +increases with every change to the message (post, pin, reaction), across +restarts. + +| Request | Answer | Notes | +|---|---|---| +| `query_history {target, before?, after?, before_ms?, after_ms?, limit?, topic?, exclude_topics?}` | `history_page {target, topic?, messages, has_more}` | Oldest first. No cursor: the latest `limit`. `before`: the `limit` right before it. `after`: the `limit` right after it. Both: the range from `after`. `*_ms` are times (Unix ms). No `limit`: everything in range. `has_more`: more beyond the page in the paging direction | +| `sync {target, since_rev, limit?}` | `sync_page {target, messages, rev, has_more}` | New and changed messages by revision; pass `rev` next time | +| `post {target, text, topic?}` | `posted {entry}` | Like `send_chat`, returns the stored message; into a topic, TeamSpeak sees `[#Title] text` | +| `pin {message_id}` / `unpin {message_id}` | `ok` | Pushes `pinned {target, pin}` / `unpinned {target, message_id, by}` | +| `list_pins {target}` | `pins {target, pins}` | Newest first; `pin` is `{entry, by, ts_ms}` | +| `react {message_id, emoji}` / `unreact {…}` | `ok` | Any string without spaces. Push `reaction {target, message_id, emoji, user, added, count}` | +| `reactors {message_id, emoji}` | `reactors {message_id, emoji, users}` | | +| `create_topic {target, title, message_id?}` | `topic {topic}` | Push `topic_updated {topic}` (also on renames, archiving and new posts) | +| `update_topic {topic_id, title?, archived?}` | `topic {topic}` | Creator or moderator; archived topics take no posts | +| `list_topics {target, include_archived}` | `topics {target, topics}` | Most recently active first; `topic` has `message_count`, `last_activity_ms`, `root_message_id` | +| `permissions {channel?}` | `permissions {channel, actions}` | Actions the user may take (to hide buttons) | + +`user`, `by` and `creator` are `{uid, name}`. + +## Events + +| Request | Answer | +|---|---| +| `create_event {event: EventSpec}` | `event {event}` | +| `update_event {id, event: EventSpec}` | `event {event}` (creator or moderator) | +| `delete_event {id}` | `ok` | +| `get_event {id}` | `event {event}` with `attendees` | +| `list_events {from_ms?, to_ms?, channel?, limit?}` | `events {events}` by start; default from now, including running events | +| `rsvp {event_id, status}` | `event {event}`; `status` `going`, `maybe`, `not_going` or `null` to withdraw | +| `subscribe_events` / `unsubscribe_events` | `ok` | + +`EventSpec`: `{title, description, start_ms, end_ms?, channel?, kind: +"general"|"stream", stream_title?, stream_game?, host_uid?}`. An event adds +`id, creator, created_ms, updated_ms, going, maybe, not_going, my_rsvp?, +attendees?, live_stream?`. When the host of a stream event registers a stream +around its time, `live_stream` is the directory id until the stream ends. + +Pushes to subscribers (only for events in channels they can see): +`event_updated {event}` (created, changed, RSVP counts, live), +`event_deleted {id}`, `event_reminder {event, starts_in_ms}` at the times in +`events.reminder_minutes`. + +## Stream directory + +| Request | Answer | +|---|---| +| `register_stream {stream_id, client_id?, channel?, title, kind, viewers?}` | `stream {stream}` | +| `update_stream {stream_id, title?, viewers?}` | `stream {stream}` | +| `unregister_stream {stream_id}` | `ok` | +| `list_streams` | `streams {streams}` | +| `subscribe_streams` / `unsubscribe_streams` | `streams {streams}` / `ok` | + +An entry: `{id, stream_id?, streamer, client_id?, channel?, title, kind, +started_ms, viewers?, source: "registered"|"detected", event_id?}`. `id` is +the stream id, or `client/` for detected streams (a client with +`client_is_streaming` but no registration; its stream id is unknown). +`client_id` must be the registering user's own voice client; with it the +gateway drops the entry when that client leaves or stops streaming and +follows it to other channels. Entries without a `client_id` end with the +registering connection. Pushes to subscribers: `stream_started {stream}`, +`stream_updated {stream}`, `stream_ended {id, reason}`. + +## Activity feed + +`list_activity {before?, limit?}` → `activity {entries, has_more}`, newest +first; `subscribe_activity` / `unsubscribe_activity` → `ok`, then +`activity_added {entry}` pushes. An entry: `{id, ts_ms, kind, actor?, +channel?, ref_id?, text, data}`; `text` is a readable summary for kinds the +client does not know. Kinds so far: `stream_started`, `stream_ended`, +`event_created`, `event_cancelled`, `event_starting`, `topic_created`, +`pinned`. + +## Administration + +Needs the `admin` capability; see [gateway-admin.md](gateway-admin.md#admin-commands). + +| Request | Answer | +|---|---| +| `config_list` | `config {entries}` | +| `config_get {key}` | `config_value {entry}` | +| `config_set {key, value}` | `config_value {entry}` | +| `config_reset {key}` | `config_value {entry}` | +| `config_reload` | `config {entries}` | +| `perm_list` | `perm_rules {rules}` | +| `perm_set {action, rule: {everyone?, server_groups?, channel_groups?}}` | `perm_rules {rules}` | +| `perm_reset {action}` | `perm_rules {rules}` | + +`entry`: `{key, value, source: "db"|"cli"|"env"|"file"|"default", default, +type, description, bootstrap?}`. `rules`: `{action, rule?, source, default}` +for `react`, `pin`, `create_topic`, `create_event`, `rsvp`, `stream`, +`moderate`, `admin`. + +## Errors + +`error {code, message}` with `code`: `bad_request`, `auth_failed`, +`unknown_identity`, `level_too_low`, `banned`, `forbidden`, +`not_authenticated`, `unavailable`, `internal`, and for the extensions +`unknown_type`, `not_found`, `quota_exceeded`, `rate_limited`, +`feature_disabled`. diff --git a/packaging/linux/tsgw.service b/packaging/linux/tsgw.service index 00eded6..bc795e6 100644 --- a/packaging/linux/tsgw.service +++ b/packaging/linux/tsgw.service @@ -12,6 +12,8 @@ ConditionPathExists=/etc/tsgw/tsgw.toml [Service] ExecStart=/usr/bin/tsgw --config /etc/tsgw/tsgw.toml +# Re-reads tsgw.toml; values set at runtime keep winning. +ExecReload=/bin/kill -HUP $MAINPID # Read by systemd before dropping privileges, so it can stay root-only. EnvironmentFile=-/etc/tsgw/tsgw.env DynamicUser=yes