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:
1 parent
5812fdcbb9
commit
8a5faa2e76
2 files changed
+66
-75
No files matched your search
@@ -30,7 +30,7 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"
|
|||||||
tokio-tungstenite = "0.30"
|
tokio-tungstenite = "0.30"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
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-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true }
|
||||||
voelin-model = { path = "../voelin-model" }
|
voelin-model = { path = "../voelin-model" }
|
||||||
voelin-observer = { path = "../voelin-observer" }
|
voelin-observer = { path = "../voelin-observer" }
|
||||||
|
|||||||
@@ -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::sync::mpsc;
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
|
||||||
use tracing::info;
|
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};
|
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||||
|
|
||||||
pub(crate) enum GatewayCmd {
|
pub(crate) enum GatewayCmd {
|
||||||
@@ -23,6 +33,16 @@ pub(crate) enum GatewayEvent {
|
|||||||
Disconnected(Option<String>),
|
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(
|
pub(crate) async fn run(
|
||||||
url: String,
|
url: String,
|
||||||
identity: tsclientlib::Identity,
|
identity: tsclientlib::Identity,
|
||||||
@@ -40,82 +60,53 @@ async fn run_inner(
|
|||||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut request = url.into_client_request()?;
|
let (client, mut pushes) = match connect(url, identity).await {
|
||||||
request
|
Ok(connected) => connected,
|
||||||
.headers_mut()
|
Err(ClientError::Gateway { code, message }) => {
|
||||||
.insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse()?);
|
let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}")));
|
||||||
let (mut ws, _) = tokio_tungstenite::connect_async(request).await?;
|
anyhow::bail!("gateway refused login: {message}");
|
||||||
let mut next_id = 1u64;
|
}
|
||||||
|
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();
|
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 {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
msg = ws.next() => {
|
push = pushes.recv() => match push {
|
||||||
let text = match msg {
|
None | Some(Push::Disconnected(None)) => return Ok(()),
|
||||||
Some(Ok(Message::Text(t))) => t,
|
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
|
||||||
Some(Ok(Message::Close(_))) | None => return Ok(()),
|
Some(Push::PresenceSnapshot(snapshot)) => {
|
||||||
Some(Ok(_)) => continue,
|
presence = Presence::from_snapshot(snapshot);
|
||||||
Some(Err(e)) => return Err(e.into()),
|
let _ = events.send(GatewayEvent::Presence(presence.clone()));
|
||||||
};
|
|
||||||
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}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
}
|
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 {
|
cmd = commands.recv() => match cmd {
|
||||||
None | Some(GatewayCmd::Stop) => return Ok(()),
|
None | Some(GatewayCmd::Stop) => return Ok(()),
|
||||||
Some(GatewayCmd::OpenChat(target)) => send!(ClientMsg::OpenChat { target }),
|
Some(GatewayCmd::OpenChat(target)) => client.send(ClientMsg::OpenChat { target })?,
|
||||||
Some(GatewayCmd::CloseChat(target)) => send!(ClientMsg::CloseChat { target }),
|
Some(GatewayCmd::CloseChat(target)) => client.send(ClientMsg::CloseChat { target })?,
|
||||||
Some(GatewayCmd::SendChat(target, text)) => send!(ClientMsg::SendChat { target, text }),
|
Some(GatewayCmd::SendChat(target, text)) => {
|
||||||
|
client.send(ClientMsg::SendChat { target, text })?;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user