voelin-core: typed gateway client for the new features

The engine's gateway module now builds on the typed client of
voelin-gateway-proto: connect() logs in with the user's TeamSpeak
identity and returns a GatewayClient with one async method per request
(history cursors, sync, post into topics, pins, reactions, topics,
events and RSVP, stream directory, activity, permissions, settings and
rules), capabilities() for hiding missing features, and typed Push
events. run() keeps its interface for the engine and uses the same
client; the UI and engine commands come later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 18:38:48 +00:00
1 parent 5812fdcbb9
commit 8a5faa2e76
2 files changed
+66 -75

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"
tokio-tungstenite = "0.30"
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" }
+65 -74
View File
@@ -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<String>),
}
/// 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<Push>), 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<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
) -> 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<ServerMsg> = 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 })?;
}
},
}
}