gateway: invisible to users, and tried again when away
Users never hear of the gateway:
- relayed messages look like everyone else's (no "via relay", no accent
colour) and group with the author's other messages;
- a gateway that cannot be reached or drops is tried again by itself
(after 2, 5, 15, 30, then every 60 s) with the open chats opened again
and messages written meanwhile sent, instead of a WebSocket error
("connection refused") on screen; it is logged with its URL, once per
cause;
- a server whose gateway is away is offline, not connecting, so it can
always be joined;
- failed requests the app made by itself are quiet; what the user did and
failed is told in plain words; query relay errors are logged;
- no status line about a found gateway; events and streams texts do not
mention it.
The gateway is looked up once per run even when one is stored: what the
server publishes takes the place of a stored URL (one that moved, or one
typed into an older version that showed the field, which cannot be
edited any more).
The admin guide says a _tsgws record must point at TLS, not at tsgw's own
plain port.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
1 parent
f8dcfaf0f5
commit
266148d9cd
16 files changed
+384
-78
No files matched your search
@@ -40,6 +40,19 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
fewer threads. A 1440p60 VP8 stream from a 6-8 core sender showed 35-49
|
||||
fps; FFmpeg decodes it at 95-101 fps on one thread against 54-60 on four.
|
||||
- Release builds no longer limit Cargo to one job.
|
||||
- The gateway is invisible: relayed messages look like everyone else's (no
|
||||
"via relay"), and a gateway that is away is tried again quietly instead
|
||||
of showing a WebSocket error; only what the user did and failed is
|
||||
told, in plain words. A server whose gateway is away no longer shows as
|
||||
connecting, so it can always be joined.
|
||||
- A server's published gateway replaces one stored before (found or typed
|
||||
into an older version), so a gateway that moved is followed.
|
||||
- zbus's warnings about desktop portal requests are left out of the logs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The account's avatar is downloaded from its own link; it was asked for
|
||||
as an upload link and refused with HTTP 403.
|
||||
|
||||
## [0.0.1-alpha] - 2026-10-04
|
||||
|
||||
|
||||
@@ -39,9 +39,11 @@
|
||||
//! streams look for streams that started before we joined, next to the
|
||||
//! server's `requeststreaminfo`.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::info;
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_gateway_proto::client::Login;
|
||||
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
|
||||
use voelin_gateway_proto::{
|
||||
@@ -68,6 +70,10 @@ pub(crate) enum GatewayEvent {
|
||||
Presence(Box<Presence>),
|
||||
/// A push other than presence.
|
||||
Push(Box<Push>),
|
||||
/// The gateway could not be reached, or the connection was lost; the
|
||||
/// next attempt follows by itself.
|
||||
Retrying(String),
|
||||
/// Stopped, or the gateway refused the login (the reason).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
@@ -87,11 +93,133 @@ pub(crate) async fn run(
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
let reason =
|
||||
run_inner(&url, &identity, &mut commands, &events).await.err().map(|e| e.to_string());
|
||||
// A gateway that is away (down, restarting, a network change) is tried
|
||||
// again until the session stops observing; only a refused login ends it.
|
||||
let mut chats = Chats::default();
|
||||
let mut failures = 0;
|
||||
let mut last_reason = String::new();
|
||||
let reason = loop {
|
||||
match attempt(&url, &identity, &mut commands, &events, &mut chats, &mut failures).await {
|
||||
Ended::Stopped => break None,
|
||||
Ended::Refused(reason) => break Some(reason),
|
||||
Ended::Lost(reason) => {
|
||||
failures += 1;
|
||||
let delay = retry_delay(failures);
|
||||
// Once per cause, not every minute of a long absence.
|
||||
if reason != last_reason {
|
||||
warn!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway unreachable");
|
||||
} else {
|
||||
debug!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway still unreachable");
|
||||
}
|
||||
last_reason.clone_from(&reason);
|
||||
let _ = events.send(GatewayEvent::Retrying(reason));
|
||||
if !chats.wait(delay, &mut commands).await {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = events.send(GatewayEvent::Disconnected(reason));
|
||||
}
|
||||
|
||||
/// How one connection to the gateway ended.
|
||||
enum Ended {
|
||||
/// The session stopped observing.
|
||||
Stopped,
|
||||
/// The gateway refused the login: trying again would not help.
|
||||
Refused(String),
|
||||
/// Not reached, or lost: try again.
|
||||
Lost(String),
|
||||
}
|
||||
|
||||
/// The wait before the next attempt after `failures` failed ones in a row.
|
||||
fn retry_delay(failures: u32) -> Duration {
|
||||
const SECONDS: [u64; 5] = [2, 5, 15, 30, 60];
|
||||
let index = (failures.max(1) as usize - 1).min(SECONDS.len() - 1);
|
||||
Duration::from_secs(SECONDS[index])
|
||||
}
|
||||
|
||||
/// Messages written while the gateway is away, at most this many, go out
|
||||
/// when it is back.
|
||||
const MAX_UNSENT: usize = 64;
|
||||
|
||||
/// What a new connection restores: the chats open at the gateway, and
|
||||
/// messages written while it was away.
|
||||
#[derive(Default)]
|
||||
struct Chats {
|
||||
open: Vec<ChatTarget>,
|
||||
unsent: Vec<(ChatTarget, String)>,
|
||||
}
|
||||
|
||||
impl Chats {
|
||||
/// Note a chat command; it goes out when connected.
|
||||
fn note(&mut self, cmd: GatewayCmd) {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target);
|
||||
}
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => self.open.retain(|open| *open != target),
|
||||
GatewayCmd::SendChat(target, text) => {
|
||||
if self.unsent.len() < MAX_UNSENT {
|
||||
self.unsent.push((target, text));
|
||||
}
|
||||
}
|
||||
GatewayCmd::Stop => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry out a chat command on a connected gateway.
|
||||
fn apply(&mut self, client: &GatewayClient, cmd: GatewayCmd) -> Result<(), ClientError> {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target.clone());
|
||||
}
|
||||
client.send(ClientMsg::OpenChat { target })
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => {
|
||||
self.open.retain(|open| *open != target);
|
||||
client.send(ClientMsg::CloseChat { target })
|
||||
}
|
||||
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
|
||||
GatewayCmd::Stop => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the chats again on a new connection and send what waited.
|
||||
fn restore(&mut self, client: &GatewayClient) -> Result<(), ClientError> {
|
||||
for target in &self.open {
|
||||
client.send(ClientMsg::OpenChat { target: target.clone() })?;
|
||||
}
|
||||
for (target, text) in std::mem::take(&mut self.unsent) {
|
||||
client.send(ClientMsg::SendChat { target, text })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait `delay` before the next attempt, noting the commands that come
|
||||
/// meanwhile; false when the session stops observing.
|
||||
async fn wait(
|
||||
&mut self,
|
||||
delay: Duration,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
) -> bool {
|
||||
let sleep = tokio::time::sleep(delay);
|
||||
tokio::pin!(sleep);
|
||||
loop {
|
||||
tokio::select! {
|
||||
() = &mut sleep => return true,
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return false,
|
||||
Some(cmd) => self.note(cmd),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Features whose pushes for open chats need [`ClientMsg::Enable`].
|
||||
const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::HISTORY,
|
||||
@@ -100,22 +228,38 @@ const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::TOPICS,
|
||||
];
|
||||
|
||||
async fn run_inner(
|
||||
/// One connection: log in, then relay until it ends.
|
||||
async fn attempt(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
chats: &mut Chats,
|
||||
failures: &mut u32,
|
||||
) -> Ended {
|
||||
let (client, mut pushes) = match connect(url, identity).await {
|
||||
Ok(connected) => connected,
|
||||
Err(ClientError::Gateway { code, message }) => {
|
||||
let _ = events
|
||||
.send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() })));
|
||||
anyhow::bail!("gateway refused login: {message}");
|
||||
warn!(%url, ?code, %message, "gateway refused the login");
|
||||
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
Err(e) => return Ended::Lost(e.to_string()),
|
||||
};
|
||||
info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
|
||||
*failures = 0;
|
||||
info!(%url, server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
|
||||
match relay(&client, &mut pushes, commands, events, chats).await {
|
||||
Ok(ended) => ended,
|
||||
Err(e) => Ended::Lost(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn relay(
|
||||
client: &GatewayClient,
|
||||
pushes: &mut mpsc::UnboundedReceiver<Push>,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
chats: &mut Chats,
|
||||
) -> Result<Ended, ClientError> {
|
||||
// Messages with their gateway ids, pins, reactions and topics of open
|
||||
// chats (older gateways answer `unknown_type` as a push; ignored).
|
||||
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
|
||||
@@ -123,13 +267,16 @@ async fn run_inner(
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone()));
|
||||
client.subscribe_presence()?;
|
||||
chats.restore(client)?;
|
||||
let mut presence = Presence::default();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
push = pushes.recv() => match push {
|
||||
None | Some(Push::Disconnected(None)) => return Ok(()),
|
||||
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
|
||||
None | Some(Push::Disconnected(None)) => {
|
||||
return Ok(Ended::Lost("the gateway closed the connection".into()));
|
||||
}
|
||||
Some(Push::Disconnected(Some(reason))) => return Ok(Ended::Lost(reason)),
|
||||
Some(Push::PresenceSnapshot(snapshot)) => {
|
||||
presence = Presence::from_snapshot(snapshot);
|
||||
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
|
||||
@@ -140,24 +287,17 @@ async fn run_inner(
|
||||
}
|
||||
// Answers to requests sent without waiting.
|
||||
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
|
||||
// The gateway forgot the login (restarted): log in again.
|
||||
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(Push::Error {
|
||||
code: ErrorCode::NotAuthenticated,
|
||||
message: message.clone(),
|
||||
})));
|
||||
anyhow::bail!("gateway session lost: {message}");
|
||||
return Ok(Ended::Lost(format!("gateway session lost: {message}")));
|
||||
}
|
||||
Some(push) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(push)));
|
||||
}
|
||||
},
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return Ok(()),
|
||||
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 })?;
|
||||
}
|
||||
None | Some(GatewayCmd::Stop) => return Ok(Ended::Stopped),
|
||||
Some(cmd) => chats.apply(client, cmd)?,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,10 @@ use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tracing::debug;
|
||||
use tracing::{debug, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_gateway_proto::{HistoryEntry, StreamEntry, StreamSpec, feature};
|
||||
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_stream::ClientState;
|
||||
|
||||
@@ -1736,6 +1736,15 @@ impl Session {
|
||||
self.publish_presence();
|
||||
}
|
||||
GatewayEvent::Push(push) => self.gateway_push(*push),
|
||||
// Away for now (logged where it happened): observing resumes
|
||||
// when it is back. Users never hear of the gateway.
|
||||
GatewayEvent::Retrying(reason) => {
|
||||
self.gateway_gone(Some(reason));
|
||||
self.gateway_presence = None;
|
||||
self.state.observe = ObserveState::Connecting;
|
||||
self.emit_state();
|
||||
self.publish_presence();
|
||||
}
|
||||
GatewayEvent::Disconnected(reason) => {
|
||||
self.gateway = None;
|
||||
self.gateway_gone(reason.clone());
|
||||
@@ -1743,7 +1752,7 @@ impl Session {
|
||||
self.state.observe = ObserveState::Off;
|
||||
self.emit_state();
|
||||
if let Some(reason) = reason {
|
||||
self.error(format!("gateway: {reason}"));
|
||||
warn!(%reason, "not observing through the gateway");
|
||||
}
|
||||
self.publish_presence();
|
||||
}
|
||||
@@ -1814,7 +1823,18 @@ impl Session {
|
||||
Push::Capabilities(capabilities) => {
|
||||
self.gateway_update(GatewayUpdate::Capabilities { capabilities });
|
||||
}
|
||||
Push::Error { code, message } => self.error(format!("gateway: {code:?}: {message}")),
|
||||
Push::Error { code, message } => {
|
||||
warn!(?code, %message, "gateway error");
|
||||
// What answers the user's own doing; the rest is the
|
||||
// gateway's business.
|
||||
let told = match code {
|
||||
ErrorCode::Forbidden => "Not allowed on this server.",
|
||||
ErrorCode::RateLimited => "Too many messages; try again in a moment.",
|
||||
ErrorCode::QuotaExceeded => "This server's limit is reached.",
|
||||
_ => return,
|
||||
};
|
||||
self.error(told);
|
||||
}
|
||||
Push::PresenceSnapshot(_)
|
||||
| Push::PresenceDelta(_)
|
||||
| Push::Other(_)
|
||||
@@ -1833,7 +1853,8 @@ impl Session {
|
||||
self.publish_presence();
|
||||
}
|
||||
QueryEvent::Chat(msg) => self.chat(msg, MessageSource::Query, None),
|
||||
QueryEvent::Error(message) => self.error(format!("query: {message}")),
|
||||
// The relay's business, not the user's (as the gateway's).
|
||||
QueryEvent::Error(message) => warn!(%message, "query relay"),
|
||||
QueryEvent::Disconnected => {
|
||||
self.query = None;
|
||||
self.query_presence = None;
|
||||
|
||||
@@ -127,7 +127,12 @@ struct FakeGateway {
|
||||
|
||||
impl FakeGateway {
|
||||
async fn start() -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
Self::start_on(0).await
|
||||
}
|
||||
|
||||
/// A gateway at `port` of the loopback address (0: any free port).
|
||||
async fn start_on(port: u16) -> Self {
|
||||
let listener = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let state: Arc<Mutex<State>> = Arc::default();
|
||||
let st = state.clone();
|
||||
@@ -707,3 +712,57 @@ async fn store_history_off_keeps_the_database_empty() {
|
||||
drop((engine, history));
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A gateway that is away is tried again by itself and quietly: no error for
|
||||
/// the user, "connecting" meanwhile, then observing once it is there, with
|
||||
/// the open chats opened again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
// Nothing listens there yet: the connection is refused.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let path = temp_db("retry");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::OpenChat { session: 3, target: LOBBY });
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
url: format!("ws://127.0.0.1:{port}/v1"),
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
});
|
||||
// The first attempt fails (the next one is 2 s later): still connecting,
|
||||
// and the user is told nothing.
|
||||
let mut connecting = false;
|
||||
let quiet = timeout(Duration::from_millis(1500), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::State { session: 3, state }) => {
|
||||
// (Off before observing starts.)
|
||||
assert!(!connecting || state.observe != ObserveState::Off, "gave up");
|
||||
connecting |= state.observe == ObserveState::Connecting;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(quiet.await.is_err(), "the event stream ended");
|
||||
assert!(connecting, "never started observing");
|
||||
// The gateway comes up: observing, and the open chat is opened again.
|
||||
let gw = FakeGateway::start_on(port).await;
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 3, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while !gw.requests().contains(&"open_chat".to_owned()) {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("the chat was not opened again: {:?}", gw.requests()));
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
@@ -470,6 +470,8 @@ pub(crate) struct App {
|
||||
pub demo: bool,
|
||||
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
|
||||
pub demo_ui: bool,
|
||||
/// Servers whose gateway was looked up in this run (`discover_gateway`).
|
||||
pub gateways_looked_up: HashSet<i64>,
|
||||
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
|
||||
pub autoshare: bool,
|
||||
/// `VOELIN_OPEN=client`: open the volume dialog of the first other client.
|
||||
@@ -699,6 +701,7 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
stream_volume: 100.0,
|
||||
demo: switches.demo_stream,
|
||||
demo_ui: switches.demo_ui,
|
||||
gateways_looked_up: HashSet::new(),
|
||||
autoshare: switches.autoshare,
|
||||
open_client_pending: switches.open_client,
|
||||
notices_loaded: false,
|
||||
|
||||
@@ -16,7 +16,7 @@ use voelin_core::{
|
||||
Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
|
||||
TransferState,
|
||||
};
|
||||
use voelin_gateway_proto::{TopicInfo, feature};
|
||||
use voelin_gateway_proto::{ErrorCode, TopicInfo, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget};
|
||||
|
||||
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, PinItem, SessionView, Tab};
|
||||
@@ -546,8 +546,11 @@ impl App {
|
||||
}
|
||||
tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
|
||||
}
|
||||
GatewayUpdate::Failed { request, message, .. } => {
|
||||
self.set_status(format!("{request}: {message}"));
|
||||
GatewayUpdate::Failed { request, code, message } => {
|
||||
tracing::warn!(%request, ?code, %message, "gateway request failed");
|
||||
if let Some(text) = failure_text(&request, code, &message) {
|
||||
self.set_status(text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The stream directory: how many watch each stream.
|
||||
@@ -809,6 +812,40 @@ impl App {
|
||||
}
|
||||
|
||||
/// A directory entry's stream id and viewer count, when it has both.
|
||||
/// What a failed gateway request tells the user. What the app asked for by
|
||||
/// itself (history, lists, subscriptions) fails quietly; what the user did
|
||||
/// says so in plain words, never the gateway's; the gateway's own
|
||||
/// administration page shows its message as it is.
|
||||
fn failure_text(request: &str, code: Option<ErrorCode>, message: &str) -> Option<String> {
|
||||
if request.starts_with("config_") || request.starts_with("perm_") {
|
||||
return Some(format!("{request}: {message}"));
|
||||
}
|
||||
let done_by_user = matches!(
|
||||
request,
|
||||
"post"
|
||||
| "pin" | "unpin"
|
||||
| "react" | "unreact"
|
||||
| "create_topic"
|
||||
| "update_topic"
|
||||
| "create_event"
|
||||
| "update_event"
|
||||
| "delete_event"
|
||||
| "rsvp"
|
||||
);
|
||||
if !done_by_user {
|
||||
return None;
|
||||
}
|
||||
let text = match code {
|
||||
Some(ErrorCode::Forbidden) => "Not allowed on this server.",
|
||||
Some(ErrorCode::RateLimited) => "Too many requests; try again in a moment.",
|
||||
Some(ErrorCode::QuotaExceeded) => "This server's limit is reached.",
|
||||
Some(ErrorCode::NotFound) => "That is no longer there.",
|
||||
Some(ErrorCode::FeatureDisabled) => "This server does not offer that.",
|
||||
_ => "That did not work; try again later.",
|
||||
};
|
||||
Some(text.to_owned())
|
||||
}
|
||||
|
||||
fn viewers_of(entry: &voelin_gateway_proto::StreamEntry) -> Option<(String, u32)> {
|
||||
Some((entry.stream_id.clone()?, entry.viewers?))
|
||||
}
|
||||
@@ -836,4 +873,25 @@ mod tests {
|
||||
assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago");
|
||||
assert_eq!(ago(now - 36 * 3_600_000), "yesterday");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_say_what_the_user_did_never_the_gateway() {
|
||||
let lost = "websocket: IO error: Connection refused (os error 111)";
|
||||
// The app's own requests fail quietly.
|
||||
for request in ["history", "sync", "pins", "events", "subscribe_streams"] {
|
||||
assert_eq!(failure_text(request, None, lost), None, "{request}");
|
||||
}
|
||||
// The user's own, in plain words.
|
||||
assert_eq!(
|
||||
failure_text("pin", Some(ErrorCode::Forbidden), "no b_pin").as_deref(),
|
||||
Some("Not allowed on this server.")
|
||||
);
|
||||
let text = failure_text("post", None, lost).unwrap();
|
||||
assert!(!text.contains("websocket") && !text.to_lowercase().contains("gateway"), "{text}");
|
||||
// The gateway's administration page shows its message.
|
||||
assert_eq!(
|
||||
failure_text("config_set", Some(ErrorCode::BadRequest), "bad value").as_deref(),
|
||||
Some("config_set: bad value")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! server card and the channel tree.
|
||||
|
||||
use slint::{ComponentHandle, SharedString};
|
||||
use tracing::warn;
|
||||
use tracing::{info, warn};
|
||||
use voelin_core::identity::LaunchImport;
|
||||
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_store::{Bookmark, QueryTransport};
|
||||
@@ -134,12 +134,16 @@ impl App {
|
||||
.unwrap_or_else(|| "Voelin user".to_owned())
|
||||
}
|
||||
|
||||
/// Look up the gateway of a server that has none in DNS
|
||||
/// ([`voelin_core::discover`]); one found is kept as if typed.
|
||||
pub(crate) fn discover_gateway(&self, id: i64) {
|
||||
let Some(b) = self.bookmark(id).filter(|b| b.gateway_url.is_none() && !self.demo_ui) else {
|
||||
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
|
||||
/// run: one found is kept as if typed, and takes the place of a stored
|
||||
/// one that is no longer what the server publishes (a gateway that
|
||||
/// moved, or one typed into an older version, which showed the field).
|
||||
/// Nothing found keeps what is stored.
|
||||
pub(crate) fn discover_gateway(&mut self, id: i64) {
|
||||
if self.demo_ui || !self.gateways_looked_up.insert(id) {
|
||||
return;
|
||||
};
|
||||
}
|
||||
let Some(b) = self.bookmark(id) else { return };
|
||||
let address = b.address.clone();
|
||||
self.engine.runtime().spawn(async move {
|
||||
if let Some(url) = voelin_core::discover::gateway(&address).await {
|
||||
@@ -150,23 +154,28 @@ impl App {
|
||||
|
||||
/// A gateway was found for the server at `address`; it is kept unless
|
||||
/// the server changed meanwhile, and the server is observed through it
|
||||
/// if it is the one shown.
|
||||
/// if it is the one shown. Users never hear of it (logged only).
|
||||
fn gateway_found(&mut self, id: i64, address: &str, url: String) {
|
||||
let Some(b) = self
|
||||
.bookmarks
|
||||
.iter_mut()
|
||||
.find(|b| b.id == id && b.address == address && b.gateway_url.is_none())
|
||||
else {
|
||||
let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
|
||||
return;
|
||||
};
|
||||
b.gateway_url = Some(url.clone());
|
||||
let name = b.name.clone();
|
||||
if b.gateway_url.as_deref() == Some(url.as_str()) {
|
||||
return;
|
||||
}
|
||||
let previous = b.gateway_url.replace(url.clone());
|
||||
if let Err(e) = self.store.update_bookmark(b) {
|
||||
warn!(%e, "could not keep the gateway found");
|
||||
return;
|
||||
}
|
||||
self.set_status(format!("Found the gateway of {name}: {url}"));
|
||||
info!(server = %b.address, %url, ?previous, "gateway found");
|
||||
self.refresh_toolbar();
|
||||
// Observed through the old one: through this one now.
|
||||
if previous.is_some() {
|
||||
self.engine.send(Command::StopObserving { session: id as u64 });
|
||||
if let Some(view) = self.sessions.get_mut(&id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
}
|
||||
}
|
||||
if self.current == Some(id) {
|
||||
self.observe(id);
|
||||
}
|
||||
@@ -210,6 +219,8 @@ impl App {
|
||||
url: url.clone(),
|
||||
identity: Box::new(self.identity_for(Some(b.id))),
|
||||
});
|
||||
// Still the one the server publishes?
|
||||
self.discover_gateway(b.id);
|
||||
} else if let Some(q) = &b.query {
|
||||
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
|
||||
let transport = match q.transport {
|
||||
@@ -283,11 +294,13 @@ impl App {
|
||||
if let Err(e) = result {
|
||||
warn!(%e, "could not store secret");
|
||||
}
|
||||
// Another server: what was observed is the old one's.
|
||||
// Another server: what was observed is the old one's, and its
|
||||
// gateway is looked up anew.
|
||||
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
|
||||
if old.query.is_some() {
|
||||
let _ = self.secrets.delete(&old.query_password_key());
|
||||
}
|
||||
self.gateways_looked_up.remove(&bookmark.id);
|
||||
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
|
||||
if let Some(view) = self.sessions.get_mut(&bookmark.id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
@@ -305,6 +318,7 @@ impl App {
|
||||
}
|
||||
let _ = self.store.delete_bookmark(id);
|
||||
self.sessions.remove(&id);
|
||||
self.gateways_looked_up.remove(&id);
|
||||
self.bookmarks = self.store.bookmarks().unwrap_or_default();
|
||||
self.current = self.bookmarks.first().map(|b| b.id);
|
||||
self.refresh_all();
|
||||
|
||||
@@ -18,17 +18,12 @@ const GROUP_MS: i64 = 5 * 60 * 1000;
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Previous {
|
||||
pub author: String,
|
||||
pub relayed: bool,
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
impl Previous {
|
||||
pub fn of(message: &ChatMessage) -> Self {
|
||||
Self {
|
||||
author: message.author_name.clone(),
|
||||
relayed: message.via_relay,
|
||||
ts_ms: message.ts_ms,
|
||||
}
|
||||
Self { author: message.author_name.clone(), ts_ms: message.ts_ms }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,9 +169,7 @@ fn line_of(
|
||||
files: &[FileRef],
|
||||
) -> ChatLine {
|
||||
let continued = previous.is_some_and(|p| {
|
||||
p.author == message.author_name
|
||||
&& p.relayed == message.via_relay
|
||||
&& (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
|
||||
p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
|
||||
});
|
||||
let text =
|
||||
if files.is_empty() { message.text.clone() } else { without_links(&message.text, files) };
|
||||
@@ -210,7 +203,6 @@ fn line_of(
|
||||
author: message.author_name.clone().into(),
|
||||
text: text.clone().into(),
|
||||
time: time_of(message.ts_ms).into(),
|
||||
relayed: message.via_relay,
|
||||
runs: runs.as_deref().map(runs_model).unwrap_or_default(),
|
||||
rich: runs.is_some(),
|
||||
jumbo,
|
||||
|
||||
@@ -12,11 +12,13 @@ pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Im
|
||||
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
|
||||
}
|
||||
|
||||
/// "offline", "connecting", "observing" or "connected".
|
||||
/// "offline", "connecting", "observing" or "connected". "connecting" is
|
||||
/// voice only: observing that is not there yet (a gateway that is away and
|
||||
/// tried again) is "offline", as users never hear of the gateway.
|
||||
pub fn status(state: &SessionState) -> &'static str {
|
||||
match (state.voice, state.observe) {
|
||||
(VoiceState::Connected, _) => "connected",
|
||||
(VoiceState::Connecting, _) | (_, ObserveState::Connecting) => "connecting",
|
||||
(VoiceState::Connecting, _) => "connecting",
|
||||
(_, ObserveState::Observing) => "observing",
|
||||
_ => "offline",
|
||||
}
|
||||
@@ -152,6 +154,8 @@ mod tests {
|
||||
fn states() {
|
||||
let mut s = SessionState::default();
|
||||
assert_eq!(status(&s), "offline");
|
||||
s.observe = ObserveState::Connecting;
|
||||
assert_eq!(status(&s), "offline");
|
||||
s.observe = ObserveState::Observing;
|
||||
assert_eq!(status(&s), "observing");
|
||||
s.voice = VoiceState::Connecting;
|
||||
|
||||
@@ -189,7 +189,6 @@ export struct ChatLine {
|
||||
author: string,
|
||||
text: string,
|
||||
time: string,
|
||||
relayed: bool,
|
||||
// The text split into runs; only filled when it has emoji (`rich`).
|
||||
runs: [TextRun],
|
||||
rich: bool,
|
||||
|
||||
@@ -337,7 +337,7 @@ export component MessageRow inherits Rectangle {
|
||||
alignment: start;
|
||||
Text {
|
||||
text: line.author;
|
||||
color: line.relayed ? Theme.accent-text : Theme.name-text;
|
||||
color: Theme.name-text;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
@@ -348,12 +348,6 @@ export component MessageRow inherits Rectangle {
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
if line.relayed: Chip {
|
||||
text: @tr("via relay");
|
||||
icon: Icons.radio;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if line.pinned: Chip {
|
||||
text: @tr("pinned");
|
||||
icon: Icons.pin;
|
||||
|
||||
@@ -319,7 +319,7 @@ export component EventsPage inherits VerticalLayout {
|
||||
}
|
||||
}
|
||||
if !Bridge.has-events: Banner {
|
||||
text: @tr("This server's gateway does not keep events (or there is no gateway).");
|
||||
text: @tr("This server does not keep events.");
|
||||
icon: Icons.info;
|
||||
tone: Theme.info;
|
||||
}
|
||||
|
||||
@@ -1024,7 +1024,7 @@ export component HomePage inherits Rectangle {
|
||||
action-clicked => { root.more-live(); }
|
||||
}
|
||||
if Bridge.live-rooms.length == 0: Text {
|
||||
text: @tr("No one is live on your servers right now. Streams of TeamSpeak 6 servers and those a gateway lists show up here.");
|
||||
text: @tr("No one is live on your servers right now. Streams on your servers show up here.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
wrap: word-wrap;
|
||||
|
||||
@@ -882,7 +882,7 @@ export component IntegrationsSection inherits VerticalLayout {
|
||||
icon: Icons.plug;
|
||||
subtitle: @tr("A gateway gives a server invisible presence, chat without joining, history, pins, reactions, topics, events and the stream directory.");
|
||||
if Bridge.gateways.length == 0: Hint {
|
||||
text: @tr("None of your servers has a gateway. Add its URL to a server's bookmark (Edit server).");
|
||||
text: @tr("None of your servers has a gateway. Voelin finds one by the server's address when the server's admin publishes it.");
|
||||
}
|
||||
for gw in Bridge.gateways: VerticalLayout {
|
||||
spacing: Theme.space-2;
|
||||
|
||||
@@ -943,7 +943,7 @@ component ChatRow inherits Rectangle {
|
||||
alignment: start;
|
||||
Text {
|
||||
text: line.author;
|
||||
color: line.relayed ? Theme.accent-text : Theme.name-text;
|
||||
color: Theme.name-text;
|
||||
font-size: Theme.font-body;
|
||||
font-weight: Theme.weight-medium;
|
||||
}
|
||||
|
||||
+15
-6
@@ -86,9 +86,10 @@ Every login, post and settings change is written to the audit table.
|
||||
5. Install tsgw ([below](#install)), copy the example config to
|
||||
`/etc/tsgw/tsgw.toml` and set the query address and credentials
|
||||
(`TSGW_QUERY_PASSWORD` or `password_file`).
|
||||
6. Run it behind TLS (Caddy, nginx) and publish it in DNS
|
||||
([below](#letting-voelin-find-the-gateway)), so users only add the
|
||||
server's address; or give them the `wss://…/v1` URL.
|
||||
6. Run it behind TLS (Caddy, nginx) and publish it in DNS, or let it
|
||||
answer on its default port next to the server
|
||||
([below](#letting-voelin-find-the-gateway)): users only add the
|
||||
server's address and never see the gateway.
|
||||
|
||||
## Letting Voelin find the gateway
|
||||
|
||||
@@ -98,9 +99,12 @@ for its gateway the way TeamSpeak looks for the voice server (SRV
|
||||
user selects the server (users do not type gateway URLs or query logins).
|
||||
It asks at the server's host name and then at each parent domain down to the
|
||||
registered domain, the most specific name first; for `ts.example.org` that
|
||||
is `ts.example.org`, then `example.org`. It looks again when the server is
|
||||
selected or saved without a gateway (a new address drops the old one) and
|
||||
when it connects with voice.
|
||||
is `ts.example.org`, then `example.org`. It looks once per run when the
|
||||
server is selected or connects with voice, and again when its address
|
||||
changes: what is published takes the place of what was found before (a
|
||||
lookup that finds nothing keeps it). A gateway that cannot be reached is
|
||||
tried again by itself (after 2, 5, 15, 30, then every 60 seconds); users
|
||||
see nothing of it, the log file has the URL and the error.
|
||||
|
||||
**DNS records** (preferred). An SRV record names the gateway's host and
|
||||
port, the service name says whether it speaks TLS:
|
||||
@@ -126,6 +130,11 @@ _tsgw._tcp.ts.example.org. 3600 IN SRV 0 0 7788 ts.example.org.
|
||||
; -> ws://ts.example.org:7788/v1, only for ts.example.org
|
||||
```
|
||||
|
||||
The record's service name must match what listens on the port: tsgw
|
||||
itself speaks plain WebSocket, so its own port (7788) is published as
|
||||
`_tsgw`; a `_tsgws` record there makes Voelin start TLS with it, which
|
||||
fails. Publish `_tsgws` only for a port with TLS in front.
|
||||
|
||||
One domain with several servers and several gateways: publish one record
|
||||
per server host (`_tsgws._tcp.ts1.example.org`, `_tsgws._tcp.ts2.example.org`);
|
||||
a record at the domain itself applies to every host below it that has none
|
||||
|
||||
Reference in new issue
Block a user