gateway: try every published gateway in turn
Discovery returns every gateway the server publishes, best first: the most specific name, at a name _tsgws before _tsgw, by priority, then tsgw's own /.well-known answer (only when a plain record or nothing is published, so a TLS-only server is never reached without TLS). The engine tries them in turn, each for up to 20 s, and uses the first that logs in; only a round that fails waits before the next. The bookmark keeps the published list and the one in use. A TLS proxy that answers 404 (Zoraxy without a rule for the host) no longer keeps the gateway away when tsgw's plain port is published too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
11 files changed
+477
-140
No files matched your search
@@ -8,12 +8,20 @@
|
||||
//! - SRV `_tsgws._tcp.<name>`: `wss://<target>:<port><path>`,
|
||||
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
|
||||
//!
|
||||
//! TLS first at the same name; `<path>` is `path=…` from a TXT record at the
|
||||
//! SRV record's name, `/v1` without one. Without any such record, as TSDNS
|
||||
//! has its well-known port, the gateway itself is asked at tsgw's default
|
||||
//! port: `http://<name>:7788/.well-known/tsgw` answers `{"url": "…"}`. For an
|
||||
//! IP address (or `localhost`) only that is tried. What an admin publishes is
|
||||
//! in `docs/gateway-admin.md`.
|
||||
//! `<path>` is `path=…` from a TXT record at the SRV record's name, `/v1`
|
||||
//! without one. As TSDNS has its well-known port, the gateway itself is also
|
||||
//! asked at tsgw's default port: `http://<name>:7788/.well-known/tsgw`
|
||||
//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is
|
||||
//! tried. That answer is plain HTTP, so it is asked only when nothing or a
|
||||
//! plain record is published: a TLS-only publication stays TLS-only.
|
||||
//!
|
||||
//! Every gateway found is kept, best first (the most specific name, at a
|
||||
//! name TLS before plain, by priority, then the gateway's own answer), and
|
||||
//! tried in turn ([`crate::Command::ObserveGateway`]): a TLS proxy that
|
||||
//! fails falls back to a published plain one. Discovery trusts DNS and the
|
||||
//! network as TSDNS does; falling back from a published `_tsgws` to a
|
||||
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
|
||||
//! admin publishes is in `docs/gateway-admin.md`.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
@@ -34,9 +42,12 @@ pub const DEFAULT_PORT: u16 = 7788;
|
||||
const DEFAULT_PATH: &str = "/v1";
|
||||
/// Give up on asking one name's gateway after this long.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
/// At most this many gateways are kept, best first.
|
||||
const MAX_CANDIDATES: usize = 8;
|
||||
|
||||
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
|
||||
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
|
||||
type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option<String>> + Send + Sync;
|
||||
|
||||
/// Where [`gateway`] gets its answers from; the tests put fakes in.
|
||||
#[derive(Clone)]
|
||||
@@ -45,8 +56,8 @@ struct Lookups {
|
||||
srv: Arc<SrvFn>,
|
||||
/// The strings of the TXT records at a name.
|
||||
txt: Arc<TxtFn>,
|
||||
/// Where a gateway is asked for its URL.
|
||||
probe_port: u16,
|
||||
/// The URL a gateway at a name gives for itself (`/.well-known/tsgw`).
|
||||
probe: Arc<ProbeFn>,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
@@ -101,30 +112,45 @@ impl Lookups {
|
||||
.map(Option::unwrap_or_default)
|
||||
.boxed()
|
||||
}),
|
||||
probe_port: DEFAULT_PORT,
|
||||
probe: Arc::new(|name| {
|
||||
async move {
|
||||
timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await.ok().flatten()
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL of the gateway of the server at `address` (as a bookmark has it:
|
||||
/// host, host:port, an IP), if one is published.
|
||||
pub async fn gateway(address: &str) -> Option<String> {
|
||||
gateway_with(address, Lookups::system()).await
|
||||
/// The URLs of the gateway of the server at `address` (as a bookmark has
|
||||
/// it: host, host:port, an IP), best first: everything published, to be
|
||||
/// tried in turn. Empty: none is published.
|
||||
pub async fn gateways(address: &str) -> Vec<String> {
|
||||
gateways_with(address, Lookups::system()).await
|
||||
}
|
||||
|
||||
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
|
||||
async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
|
||||
let host = host_of(address);
|
||||
let names = names(host);
|
||||
if names.is_empty() {
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
if host.parse::<IpAddr>().is_err()
|
||||
&& host.contains('.')
|
||||
&& let Some(url) = from_srv(&names, &lookups).await
|
||||
{
|
||||
return Some(url);
|
||||
let mut urls = if host.parse::<IpAddr>().is_err() && host.contains('.') {
|
||||
from_srv(&names, &lookups).await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// The gateway's own answer comes over plain HTTP: not for a server that
|
||||
// publishes only TLS.
|
||||
if urls.is_empty() || urls.iter().any(|url| url.starts_with("ws://")) {
|
||||
for url in from_well_known(&names, &lookups).await {
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
from_well_known(&names, lookups.probe_port).await
|
||||
urls.truncate(MAX_CANDIDATES);
|
||||
urls
|
||||
}
|
||||
|
||||
/// The host of an address: without the port, the brackets of an IPv6
|
||||
@@ -155,8 +181,9 @@ fn names(host: &str) -> Vec<&str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URL from SRV records, every name and service asked at once.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
/// The URLs from SRV records, every name and service asked at once: the
|
||||
/// most specific name first, at a name TLS first, by priority.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
let queries: Vec<(&str, String)> = names
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
@@ -164,14 +191,33 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
})
|
||||
.collect();
|
||||
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
|
||||
// The first (most specific, TLS first) name with a usable record.
|
||||
let ((scheme, owner), (_, target, port)) =
|
||||
queries.iter().zip(answers).find_map(|(q, records)| {
|
||||
let found: Vec<_> = queries
|
||||
.iter()
|
||||
.zip(answers)
|
||||
.filter_map(|(query, mut records)| {
|
||||
// A target of "." says there is no such service there.
|
||||
let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?;
|
||||
Some((q, best))
|
||||
})?;
|
||||
let mut path = (lookups.txt)(owner.clone())
|
||||
records.retain(|r| r.1 != ".");
|
||||
records.sort_by_key(|r| r.0);
|
||||
(!records.is_empty()).then_some((query, records))
|
||||
})
|
||||
.collect();
|
||||
let paths = join_all(found.iter().map(|((_, owner), _)| path_at(lookups, owner))).await;
|
||||
let mut urls = Vec::new();
|
||||
for (((scheme, _), records), path) in found.into_iter().zip(paths) {
|
||||
for (_, target, port) in records {
|
||||
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
/// The path at a SRV record's name: `path=…` from its TXT records, `/v1`
|
||||
/// without one.
|
||||
async fn path_at(lookups: &Lookups, owner: &str) -> String {
|
||||
let mut path = (lookups.txt)(owner.to_owned())
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
|
||||
@@ -179,15 +225,20 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
if !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
}
|
||||
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
|
||||
path
|
||||
}
|
||||
|
||||
/// The URL a gateway gives for itself at one of `names`, all asked at once;
|
||||
/// the most specific that answers wins.
|
||||
async fn from_well_known(names: &[&str], port: u16) -> Option<String> {
|
||||
let answers =
|
||||
join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await;
|
||||
answers.into_iter().find_map(|answer| answer.ok().flatten())
|
||||
/// The URLs gateways give for themselves at `names`, all asked at once,
|
||||
/// the most specific first.
|
||||
async fn from_well_known(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
let answers = join_all(names.iter().map(|name| (lookups.probe)((*name).to_owned()))).await;
|
||||
let mut urls: Vec<String> = Vec::new();
|
||||
for url in answers.into_iter().flatten() {
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
|
||||
@@ -215,8 +266,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// DNS answers from these lists only: SRV `(name, priority, target,
|
||||
/// port)`, TXT `(name, string)`.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups {
|
||||
/// port)`, TXT `(name, string)`; no gateway answers for itself.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> Lookups {
|
||||
let srv: Vec<(String, u16, String, u16)> =
|
||||
srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect();
|
||||
let txt: Vec<(String, String)> =
|
||||
@@ -231,10 +282,30 @@ mod tests {
|
||||
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
|
||||
futures::future::ready(found).boxed()
|
||||
}),
|
||||
probe_port,
|
||||
probe: Arc::new(|_| futures::future::ready(None).boxed()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `lookups` where the gateway at a name answers `(name, url)`.
|
||||
fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups {
|
||||
let answers: Vec<(String, String)> =
|
||||
answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect();
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone());
|
||||
futures::future::ready(url).boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok().flatten() }
|
||||
.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
@@ -242,20 +313,20 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn finds_the_gateway_at_the_host_or_its_domain() {
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0);
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]);
|
||||
for address in ["ts.example.test", "ts.example.test:9987", "example.test"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("ws://gw.example.test:7788/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["ws://gw.example.test:7788/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// The parent's parent is not the domain any more.
|
||||
assert_eq!(gateway_with("example", lookups).await, None);
|
||||
assert!(gateways_with("example", lookups).await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_most_specific_name_wins_then_tls() {
|
||||
async fn every_record_in_order_most_specific_name_then_tls() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
|
||||
@@ -264,18 +335,73 @@ mod tests {
|
||||
("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443),
|
||||
],
|
||||
&[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")],
|
||||
0,
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups.clone()).await.as_deref(),
|
||||
Some("wss://tls.example.test:8443/tsgw/v1")
|
||||
gateways_with("ts.example.test", lookups.clone()).await,
|
||||
[
|
||||
"wss://tls.example.test:8443/tsgw/v1",
|
||||
"wss://backup.example.test:443/tsgw/v1",
|
||||
"ws://plain.example.test:7788/v1",
|
||||
"wss://domain.example.test:443/v1",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("voice.example.test", lookups).await.as_deref(),
|
||||
Some("wss://domain.example.test:443/v1")
|
||||
gateways_with("voice.example.test", lookups).await,
|
||||
["wss://domain.example.test:443/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A TLS proxy in front of tsgw and tsgw itself published next to the
|
||||
/// server (and again at the domain): TLS first, the plain one after it,
|
||||
/// once; the gateway's own answer is the plain one again.
|
||||
#[tokio::test]
|
||||
async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443),
|
||||
("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788),
|
||||
("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_gateways_own_answer_comes_last() {
|
||||
let lookups = answering(
|
||||
fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]),
|
||||
&[("ts.example.test", "wss://gw.example.test/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tls_only_publication_is_not_widened() {
|
||||
let asked = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let mut lookups =
|
||||
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]);
|
||||
let flag = asked.clone();
|
||||
lookups.probe = Arc::new(move |_| {
|
||||
flag.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
futures::future::ready(Some("ws://ts.example.test:7788/v1".to_owned())).boxed()
|
||||
});
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1"]
|
||||
);
|
||||
assert!(!asked.load(std::sync::atomic::Ordering::SeqCst), "plain HTTP was asked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_record_that_says_no_service_is_skipped() {
|
||||
let lookups = fake(
|
||||
@@ -284,12 +410,8 @@ mod tests {
|
||||
("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80),
|
||||
],
|
||||
&[("_tsgw._tcp.example.test.", "path=ws")],
|
||||
closed_port(),
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups).await.as_deref(),
|
||||
Some("ws://gw.example.test:80/ws")
|
||||
);
|
||||
assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]);
|
||||
}
|
||||
|
||||
/// Without records the gateway next to the server answers at its port,
|
||||
@@ -313,16 +435,17 @@ mod tests {
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
});
|
||||
let lookups = fake(&[], &[], port);
|
||||
let lookups = probing(fake(&[], &[]), port);
|
||||
for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("wss://gw.example.test/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["wss://gw.example.test/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// Nothing there.
|
||||
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
|
||||
let nothing = probing(fake(&[], &[]), closed_port());
|
||||
assert!(gateways_with("127.0.0.1", nothing).await.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -65,8 +65,8 @@ pub(crate) enum GatewayCmd {
|
||||
}
|
||||
|
||||
pub(crate) enum GatewayEvent {
|
||||
/// Logged in; requests go through `client`.
|
||||
Connected(GatewayClient),
|
||||
/// Logged in at the URL; requests go through the client.
|
||||
Connected(GatewayClient, String),
|
||||
Presence(Box<Presence>),
|
||||
/// A push other than presence.
|
||||
Push(Box<Push>),
|
||||
@@ -87,37 +87,58 @@ pub async fn connect(
|
||||
voelin_gateway_proto::client::connect(url, login).await
|
||||
}
|
||||
|
||||
/// Observe through the first of `urls` (best first, as published) that
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
url: String,
|
||||
mut urls: Vec<String>,
|
||||
identity: tsclientlib::Identity,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
// A gateway that is away (down, restarting, a network change) is tried
|
||||
// again until the session stops observing; only a refused login ends it.
|
||||
// A gateway that is away (down, restarting, a network change, a proxy
|
||||
// in front of it that fails) is tried again until the session stops
|
||||
// observing; only a refused login ends it. A round tries every URL in
|
||||
// turn without waiting; only a round that fails waits.
|
||||
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;
|
||||
// What was logged per URL: once per cause, not every minute of a long
|
||||
// absence.
|
||||
let mut told: Vec<(String, String)> = Vec::new();
|
||||
let reason = 'observe: loop {
|
||||
let mut lost = None;
|
||||
let mut index = 0;
|
||||
while index < urls.len() {
|
||||
let url = urls[index].clone();
|
||||
match attempt(&url, &identity, &mut commands, &events, &mut chats).await {
|
||||
Ended::Stopped => break 'observe None,
|
||||
Ended::Refused(reason) => break 'observe Some(reason),
|
||||
Ended::Lost { reason, logged_in } => {
|
||||
let next = urls.get(index + 1);
|
||||
if told.iter().any(|(u, r)| *u == url && *r == reason) {
|
||||
debug!(%url, error = %reason, ?next, "gateway still unreachable");
|
||||
} else {
|
||||
warn!(%url, error = %reason, ?next, "gateway unreachable");
|
||||
told.retain(|(u, _)| *u != url);
|
||||
told.push((url.clone(), reason.clone()));
|
||||
}
|
||||
lost = Some(reason);
|
||||
if logged_in {
|
||||
// It worked: it is tried first again, after a wait.
|
||||
urls[..=index].rotate_right(1);
|
||||
failures = 0;
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(reason) = lost else { break None };
|
||||
failures += 1;
|
||||
let delay = retry_delay(failures);
|
||||
let _ = events.send(GatewayEvent::Retrying(reason));
|
||||
if !chats.wait(delay, &mut commands).await {
|
||||
break None;
|
||||
}
|
||||
};
|
||||
let _ = events.send(GatewayEvent::Disconnected(reason));
|
||||
}
|
||||
@@ -128,10 +149,15 @@ enum Ended {
|
||||
Stopped,
|
||||
/// The gateway refused the login: trying again would not help.
|
||||
Refused(String),
|
||||
/// Not reached, or lost: try again.
|
||||
Lost(String),
|
||||
/// Not reached, or lost (after logging in): try again.
|
||||
Lost { reason: String, logged_in: bool },
|
||||
}
|
||||
|
||||
/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket
|
||||
/// upgrade, the login's own queries at the gateway) gives up after this
|
||||
/// long, so a gateway that never answers does not hold up the next one.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// 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];
|
||||
@@ -235,37 +261,42 @@ async fn attempt(
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
chats: &mut Chats,
|
||||
failures: &mut u32,
|
||||
) -> Ended {
|
||||
let (client, mut pushes) = match connect(url, identity).await {
|
||||
Ok(connected) => connected,
|
||||
Err(ClientError::Gateway { code, message }) => {
|
||||
warn!(%url, ?code, %message, "gateway refused the login");
|
||||
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
|
||||
}
|
||||
Err(e) => return Ended::Lost(e.to_string()),
|
||||
};
|
||||
*failures = 0;
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
|
||||
let (client, mut pushes) =
|
||||
match tokio::time::timeout(CONNECT_TIMEOUT, connect(url, identity)).await {
|
||||
Ok(Ok(connected)) => connected,
|
||||
Ok(Err(ClientError::Gateway { code, message })) => {
|
||||
warn!(%url, ?code, %message, "gateway refused the login");
|
||||
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
|
||||
}
|
||||
Ok(Err(e)) => return lost(e.to_string()),
|
||||
Err(_) => return lost(format!("no answer within {} s", CONNECT_TIMEOUT.as_secs())),
|
||||
};
|
||||
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()),
|
||||
}
|
||||
let reason = match relay(url, &client, &mut pushes, commands, events, chats).await {
|
||||
Ok(Ended::Lost { reason, .. }) => reason,
|
||||
Ok(ended) => return ended,
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
Ended::Lost { reason, logged_in: true }
|
||||
}
|
||||
|
||||
async fn relay(
|
||||
url: &str,
|
||||
client: &GatewayClient,
|
||||
pushes: &mut mpsc::UnboundedReceiver<Push>,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
chats: &mut Chats,
|
||||
) -> Result<Ended, ClientError> {
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: true };
|
||||
// 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)) {
|
||||
client.send(ClientMsg::Enable { features: Vec::new() })?;
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone()));
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned()));
|
||||
client.subscribe_presence()?;
|
||||
chats.restore(client)?;
|
||||
let mut presence = Presence::default();
|
||||
@@ -274,9 +305,9 @@ async fn relay(
|
||||
tokio::select! {
|
||||
push = pushes.recv() => match push {
|
||||
None | Some(Push::Disconnected(None)) => {
|
||||
return Ok(Ended::Lost("the gateway closed the connection".into()));
|
||||
return Ok(lost("the gateway closed the connection".into()));
|
||||
}
|
||||
Some(Push::Disconnected(Some(reason))) => return Ok(Ended::Lost(reason)),
|
||||
Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)),
|
||||
Some(Push::PresenceSnapshot(snapshot)) => {
|
||||
presence = Presence::from_snapshot(snapshot);
|
||||
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
|
||||
@@ -289,7 +320,7 @@ async fn relay(
|
||||
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
|
||||
// The gateway forgot the login (restarted): log in again.
|
||||
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
|
||||
return Ok(Ended::Lost(format!("gateway session lost: {message}")));
|
||||
return Ok(lost(format!("gateway session lost: {message}")));
|
||||
}
|
||||
Some(push) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(push)));
|
||||
@@ -528,6 +559,8 @@ pub struct Pin {
|
||||
pub enum GatewayUpdate {
|
||||
/// Logged in.
|
||||
Connected {
|
||||
/// Where: the first of the published URLs that logged in.
|
||||
url: String,
|
||||
gateway_id: String,
|
||||
server_uid: String,
|
||||
server_name: String,
|
||||
|
||||
@@ -111,10 +111,12 @@ pub enum Command {
|
||||
DisconnectVoice {
|
||||
session: SessionId,
|
||||
},
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway.
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway: the first
|
||||
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
|
||||
/// turn again whenever it is lost.
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
urls: Vec<String>,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
|
||||
@@ -404,13 +404,20 @@ impl Session {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
}
|
||||
}
|
||||
Command::ObserveGateway { url, identity, .. } => {
|
||||
Command::ObserveGateway { urls, identity, .. } => {
|
||||
self.stop_observing();
|
||||
if urls.is_empty() {
|
||||
return;
|
||||
}
|
||||
let generation = self.next_generation();
|
||||
self.known_server(format!("gateway:{url}"));
|
||||
// Each is published for this server (history before its
|
||||
// unique id is known).
|
||||
for url in &urls {
|
||||
self.known_server(format!("gateway:{url}"));
|
||||
}
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx));
|
||||
tokio::spawn(gateway::run(urls, *identity, cmd_rx, ev_tx));
|
||||
self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e));
|
||||
self.gateway = Some((generation, cmd_tx));
|
||||
self.state.observe = ObserveState::Connecting;
|
||||
@@ -1711,7 +1718,7 @@ impl Session {
|
||||
|
||||
fn gateway_event(&mut self, e: GatewayEvent) {
|
||||
match e {
|
||||
GatewayEvent::Connected(client) => {
|
||||
GatewayEvent::Connected(client, url) => {
|
||||
self.state.observe = ObserveState::Observing;
|
||||
let info = client.info().clone();
|
||||
self.gateway_client = Some(client.clone());
|
||||
@@ -1721,6 +1728,7 @@ impl Session {
|
||||
self.learn_server_uid(info.server_uid.clone(), Source::Gateway);
|
||||
self.emit_state();
|
||||
self.gateway_update(GatewayUpdate::Connected {
|
||||
url,
|
||||
gateway_id: info.gateway_id,
|
||||
server_uid: info.server_uid,
|
||||
server_name: info.server_name,
|
||||
|
||||
@@ -434,7 +434,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
let identity = tsclientlib::Identity::create();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
url: gw.url.clone(),
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity),
|
||||
});
|
||||
}
|
||||
@@ -726,7 +726,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
engine.send(Command::OpenChat { session: 3, target: LOBBY });
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
url: format!("ws://127.0.0.1:{port}/v1"),
|
||||
urls: vec![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,
|
||||
@@ -766,3 +766,68 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A reverse proxy without a rule for the gateway's host, as Zoraxy's
|
||||
/// default site answers: 404 to everything.
|
||||
async fn not_found_proxy() -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut tcp, _)) = listener.accept().await {
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut request = [0; 4096];
|
||||
let _ = tcp.read(&mut request).await;
|
||||
let _ = tcp
|
||||
.write_all(
|
||||
b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\n\
|
||||
Content-Length: 19\r\n\r\n404 page not found\n",
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
url
|
||||
}
|
||||
|
||||
/// Every published gateway is tried in turn, without waiting: a TLS proxy
|
||||
/// that answers 404 and a port nothing listens on are passed over, and the
|
||||
/// plain gateway published after them is used, quietly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 4,
|
||||
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
});
|
||||
// Within one round: sooner than the first wait (2 s) after a failed round.
|
||||
let url = timeout(Duration::from_millis(1800), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::Gateway { session: 4, update: GatewayUpdate::Connected { url, .. } }) => {
|
||||
return url;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the plain gateway was not used within a round");
|
||||
assert_eq!(url, gw.url);
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 4, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
@@ -147,8 +147,14 @@ pub struct Bookmark {
|
||||
/// Identity to connect with (`IdentityEntry::id`).
|
||||
pub identity: Option<i64>,
|
||||
pub default_channel: Option<String>,
|
||||
/// `wss://` URL of a companion gateway, for invisible presence and relay chat.
|
||||
/// The companion gateway in use (`wss://` or `ws://`), for invisible
|
||||
/// presence and relay chat: the one that last logged in, else the best
|
||||
/// published one, else one typed into an older version.
|
||||
pub gateway_url: Option<String>,
|
||||
/// Every URL the server publishes for its gateway, best first: tried in
|
||||
/// this order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub gateway_urls: Vec<String>,
|
||||
/// Own ServerQuery credentials (the password is kept in [`crate::Secrets`]).
|
||||
pub query: Option<QueryConfig>,
|
||||
/// Signed client version to present (`voelinctl versions` spec), `None` for the default.
|
||||
@@ -167,6 +173,37 @@ pub struct CachedServerIcon {
|
||||
}
|
||||
|
||||
impl Bookmark {
|
||||
/// The gateways to try, best first: those published, else the one kept.
|
||||
pub fn gateways(&self) -> Vec<String> {
|
||||
if self.gateway_urls.is_empty() {
|
||||
self.gateway_url.iter().cloned().collect()
|
||||
} else {
|
||||
self.gateway_urls.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Discovery found `urls` (best first, not empty); true if what is tried
|
||||
/// changed. The one in use stays if it is still published.
|
||||
pub fn set_gateways(&mut self, urls: Vec<String>) -> bool {
|
||||
if self.gateway_urls == urls {
|
||||
return false;
|
||||
}
|
||||
if !self.gateway_url.as_ref().is_some_and(|url| urls.contains(url)) {
|
||||
self.gateway_url = urls.first().cloned();
|
||||
}
|
||||
self.gateway_urls = urls;
|
||||
true
|
||||
}
|
||||
|
||||
/// The gateway logged in at `url`; true if the one in use changed.
|
||||
pub fn gateway_in_use(&mut self, url: &str) -> bool {
|
||||
if self.gateway_url.as_deref() == Some(url) || !self.gateways().iter().any(|u| u == url) {
|
||||
return false;
|
||||
}
|
||||
self.gateway_url = Some(url.to_owned());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn server_icon_id(&self) -> Option<u32> {
|
||||
self.cached_server_icon
|
||||
.as_ref()
|
||||
@@ -562,6 +599,36 @@ mod tests {
|
||||
assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_gateways_are_kept_with_the_one_in_use() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
// From an older version: one URL, no list.
|
||||
let mut b = Bookmark {
|
||||
address: "ts.example.org".into(),
|
||||
gateway_url: Some("ws://127.0.0.1:7788/v1".into()),
|
||||
..Default::default()
|
||||
};
|
||||
b.id = store.add_bookmark(&b).unwrap();
|
||||
assert_eq!(b.gateways(), ["ws://127.0.0.1:7788/v1"]);
|
||||
let published =
|
||||
vec!["wss://gw.example.org/v1".to_owned(), "ws://ts.example.org:7788/v1".into()];
|
||||
assert!(b.set_gateways(published.clone()));
|
||||
assert!(!b.set_gateways(published.clone()), "unchanged");
|
||||
// The old one is not published: the best published one is in use.
|
||||
assert_eq!(b.gateway_url.as_deref(), Some("wss://gw.example.org/v1"));
|
||||
assert_eq!(b.gateways(), published);
|
||||
// The plain one logged in; one that is not published never counts.
|
||||
assert!(b.gateway_in_use("ws://ts.example.org:7788/v1"));
|
||||
assert!(!b.gateway_in_use("ws://ts.example.org:7788/v1"));
|
||||
assert!(!b.gateway_in_use("ws://elsewhere.test/v1"));
|
||||
store.update_bookmark(&b).unwrap();
|
||||
let reloaded = store.bookmarks().unwrap().remove(0);
|
||||
assert_eq!(reloaded, b);
|
||||
// Still published: the one in use stays.
|
||||
b.set_gateways(vec!["ws://ts.example.org:7788/v1".into()]);
|
||||
assert_eq!(b.gateway_url.as_deref(), Some("ws://ts.example.org:7788/v1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_icons_survive_reload_and_are_bound_to_the_server_address() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
|
||||
@@ -980,6 +980,9 @@ impl App {
|
||||
self.history_batch(session as i64, &target, messages, source, complete);
|
||||
}
|
||||
Event::Gateway { session, update } => {
|
||||
if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update {
|
||||
self.gateway_in_use(session as i64, url);
|
||||
}
|
||||
self.gateway_extra(session as i64, &update);
|
||||
self.gateway_update(session as i64, update);
|
||||
}
|
||||
|
||||
@@ -408,6 +408,7 @@ fn demo_ui(app: &mut App) {
|
||||
identity: None,
|
||||
default_channel: None,
|
||||
gateway_url: None,
|
||||
gateway_urls: Vec::new(),
|
||||
query: None,
|
||||
client_version: None,
|
||||
cached_server_icon: None,
|
||||
@@ -539,6 +540,7 @@ fn demo_ui(app: &mut App) {
|
||||
Event::Gateway {
|
||||
session,
|
||||
update: GatewayUpdate::Connected {
|
||||
url: "wss://gw.nightfall.example/v1".into(),
|
||||
gateway_id: "demo".into(),
|
||||
server_uid: "demo-server".into(),
|
||||
server_name: "Nightfall Guild".into(),
|
||||
|
||||
@@ -76,12 +76,9 @@ impl App {
|
||||
}
|
||||
self.social.dm.bookmark_of.clear();
|
||||
for b in &self.bookmarks {
|
||||
for alias in [
|
||||
Some(format!("voice:{}", b.address)),
|
||||
b.gateway_url.as_ref().map(|u| format!("gateway:{u}")),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
let gateways = b.gateways().into_iter().chain(b.gateway_url.clone());
|
||||
for alias in std::iter::once(format!("voice:{}", b.address))
|
||||
.chain(gateways.map(|url| format!("gateway:{url}")))
|
||||
{
|
||||
if let Ok(Some(uid)) = self.store.server_alias(&alias) {
|
||||
self.social.dm.bookmark_of.insert(uid, b.id);
|
||||
|
||||
@@ -49,6 +49,7 @@ fn bookmark_from_form(
|
||||
if old.is_some_and(|old| old.address != bookmark.address) {
|
||||
bookmark.cached_server_icon = None;
|
||||
bookmark.gateway_url = None;
|
||||
bookmark.gateway_urls.clear();
|
||||
bookmark.query = None;
|
||||
}
|
||||
bookmark.name = match form.name.trim() {
|
||||
@@ -135,10 +136,10 @@ impl App {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// run: every one the server publishes is kept, best first, and tried in
|
||||
/// turn; they take the place of a stored one that is no longer published
|
||||
/// (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;
|
||||
@@ -146,31 +147,33 @@ impl App {
|
||||
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 {
|
||||
later(move |app| app.gateway_found(id, &address, url));
|
||||
let urls = voelin_core::discover::gateways(&address).await;
|
||||
if !urls.is_empty() {
|
||||
later(move |app| app.gateway_found(id, &address, urls));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 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. Users never hear of it (logged only).
|
||||
fn gateway_found(&mut self, id: i64, address: &str, url: String) {
|
||||
/// Gateways were found for the server at `address` (best first); they
|
||||
/// are kept unless the server changed meanwhile, and the server is
|
||||
/// observed through them if it is the one shown. Users never hear of
|
||||
/// them (logged only).
|
||||
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>) {
|
||||
let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
|
||||
return;
|
||||
};
|
||||
if b.gateway_url.as_deref() == Some(url.as_str()) {
|
||||
let previous = b.gateways();
|
||||
if !b.set_gateways(urls) {
|
||||
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;
|
||||
}
|
||||
info!(server = %b.address, %url, ?previous, "gateway found");
|
||||
info!(server = %b.address, urls = ?b.gateway_urls, ?previous, "gateway found");
|
||||
self.refresh_toolbar();
|
||||
// Observed through the old one: through this one now.
|
||||
if previous.is_some() {
|
||||
// Observed through the old ones: through these now.
|
||||
if !previous.is_empty() {
|
||||
self.engine.send(Command::StopObserving { session: id as u64 });
|
||||
if let Some(view) = self.sessions.get_mut(&id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
@@ -181,6 +184,19 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The gateway logged in at `url`: it is the one in use from now on.
|
||||
pub(crate) fn gateway_in_use(&mut self, id: i64, url: &str) {
|
||||
let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id) else { return };
|
||||
if !b.gateway_in_use(url) {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.store.update_bookmark(b) {
|
||||
warn!(%e, "could not keep the gateway in use");
|
||||
return;
|
||||
}
|
||||
info!(server = %b.address, %url, "gateway in use");
|
||||
}
|
||||
|
||||
/// The server told its name: a server still named by its address takes
|
||||
/// it, so the address is all a user has to type.
|
||||
pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) {
|
||||
@@ -213,10 +229,11 @@ impl App {
|
||||
if observing {
|
||||
return;
|
||||
}
|
||||
if let Some(url) = &b.gateway_url {
|
||||
let urls = b.gateways();
|
||||
if !urls.is_empty() {
|
||||
self.engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
url: url.clone(),
|
||||
urls,
|
||||
identity: Box::new(self.identity_for(Some(b.id))),
|
||||
});
|
||||
// Still the one the server publishes?
|
||||
@@ -608,6 +625,7 @@ mod tests {
|
||||
identity: Some(2),
|
||||
default_channel: Some("Lobby/Sub".into()),
|
||||
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
|
||||
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
|
||||
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
|
||||
client_version: Some("linux".into()),
|
||||
cached_server_icon: Some(voelin_store::CachedServerIcon {
|
||||
@@ -636,6 +654,7 @@ mod tests {
|
||||
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
|
||||
assert_eq!(b.client_version.as_deref(), Some("linux"));
|
||||
assert_eq!((b.gateway_url, b.query), (None, None));
|
||||
assert!(b.gateway_urls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+24
-6
@@ -102,9 +102,11 @@ registered domain, the most specific name first; for `ts.example.org` that
|
||||
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.
|
||||
lookup that finds nothing keeps it). Every gateway found is kept and
|
||||
tried in turn, best first, each for up to 20 seconds; the first that logs
|
||||
in is used, and the log file names those it passed over (URL and error).
|
||||
Only when all of them fail does it wait (2, 5, 15, 30, then every 60
|
||||
seconds) and start over; users see nothing of it.
|
||||
|
||||
**DNS records** (preferred). An SRV record names the gateway's host and
|
||||
port, the service name says whether it speaks TLS:
|
||||
@@ -115,9 +117,14 @@ port, the service name says whether it speaks TLS:
|
||||
| `_tsgw._tcp.<name> SRV <prio> <weight> <port> <host>` | `ws://<host>:<port>/v1` (plain, e.g. tsgw itself on 7788) |
|
||||
| `_tsgws._tcp.<name> TXT "path=/<path>"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy |
|
||||
|
||||
At the same name TLS wins; among several records of one name the lowest
|
||||
priority. A target of `.` means "no gateway here" and the search goes on at
|
||||
the parent domain. Examples (zone of `example.org`):
|
||||
The order: the most specific name first; at a name `_tsgws` before
|
||||
`_tsgw`; among several records of one name the lowest priority first;
|
||||
then tsgw's own answer (below), but only when a plain record or nothing is
|
||||
published, so a server that publishes only TLS is never reached without
|
||||
it. A TLS proxy that fails (no rule for the host, no certificate) thus
|
||||
falls back to a published plain gateway. A target of `.` means "no gateway
|
||||
here" and the search goes on at the parent domain. Examples (zone of
|
||||
`example.org`):
|
||||
|
||||
```dns
|
||||
; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw:
|
||||
@@ -135,6 +142,17 @@ 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.
|
||||
|
||||
Behind [Zoraxy](https://zoraxy.aroz.org/): add an HTTP proxy rule for the
|
||||
gateway's host (`gw.example.org`) with one upstream, tsgw's plain address
|
||||
(`<tsgw host>:7788`), "Proxy Target require TLS Connection" off,
|
||||
WebSockets on, and a certificate for the host (ACME). If the rule also
|
||||
has an uptime monitor, point it at `/health` (tsgw's `/` answers 404).
|
||||
Check from outside: `curl https://gw.example.org/health` prints `ok`;
|
||||
Zoraxy's own `404 page not found` there means no rule matched the host or
|
||||
the request went to another upstream. Then set `listen.public_url =
|
||||
"wss://gw.example.org/v1"` in tsgw.toml, so its own answer points at the
|
||||
proxy.
|
||||
|
||||
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