Merge pull request #137 from ludovic111/feat/extras-reconnect
Horizon extras: auto-reconnect (off by default)
This commit is contained in:
@@ -92,6 +92,8 @@ pub struct Extras {
|
||||
pub minimap_zoom: f32,
|
||||
/// Turn with the player (forward up) instead of north up.
|
||||
pub minimap_rotate: bool,
|
||||
/// Retry lost multiplayer connections (`reconnect`).
|
||||
pub auto_reconnect: bool,
|
||||
}
|
||||
impl Default for Extras {
|
||||
fn default() -> Self {
|
||||
@@ -113,6 +115,7 @@ impl Default for Extras {
|
||||
minimap_round: false,
|
||||
minimap_zoom: 1.0,
|
||||
minimap_rotate: false,
|
||||
auto_reconnect: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +172,7 @@ impl Extras {
|
||||
}
|
||||
}
|
||||
"minimapRotate" => e.minimap_rotate = flag(e.minimap_rotate),
|
||||
"autoReconnect" => e.auto_reconnect = flag(e.auto_reconnect),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -176,7 +180,7 @@ impl Extras {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\n",
|
||||
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\n",
|
||||
bool_text(self.zoom),
|
||||
self.zoom_key,
|
||||
self.zoom_level,
|
||||
@@ -198,6 +202,7 @@ impl Extras {
|
||||
},
|
||||
self.minimap_zoom,
|
||||
bool_text(self.minimap_rotate),
|
||||
bool_text(self.auto_reconnect),
|
||||
)
|
||||
}
|
||||
/// Written only once something differs from the defaults, so a vanilla
|
||||
@@ -398,6 +403,7 @@ pub enum Item {
|
||||
MinimapShape,
|
||||
MinimapZoom,
|
||||
MinimapRotate,
|
||||
AutoReconnect,
|
||||
}
|
||||
/// The Extras page: headers and items.
|
||||
pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
@@ -424,6 +430,8 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
Ok(Keystrokes),
|
||||
Ok(KeystrokesCorner),
|
||||
Ok(KeystrokesCps),
|
||||
Err("Multiplayer"),
|
||||
Ok(AutoReconnect),
|
||||
]
|
||||
}
|
||||
/// "1 block", "2 blocks", "½ block".
|
||||
@@ -456,6 +464,7 @@ impl Item {
|
||||
Item::MinimapShape => "Shape",
|
||||
Item::MinimapZoom => "Zoom",
|
||||
Item::MinimapRotate => "Turn with the player",
|
||||
Item::AutoReconnect => "Auto-reconnect",
|
||||
Item::FpsLows => "Minimum and 1% low",
|
||||
Item::Keystrokes => "Keystrokes",
|
||||
Item::KeystrokesCps => "Clicks per second",
|
||||
@@ -478,6 +487,9 @@ impl Item {
|
||||
Item::MinimapShape => "Square or round.",
|
||||
Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.",
|
||||
Item::MinimapRotate => "Forward is up; off keeps north up.",
|
||||
Item::AutoReconnect => {
|
||||
"Rejoins a server after a lost connection or a restart, never after a kick or ban."
|
||||
}
|
||||
Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.",
|
||||
Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.",
|
||||
Item::KeystrokesCps => "Clicks in the last second under each mouse button.",
|
||||
@@ -489,6 +501,7 @@ impl Item {
|
||||
match self {
|
||||
Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
|
||||
Item::Minimap => Some(Cost::Low),
|
||||
Item::AutoReconnect => Some(Cost::None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -504,6 +517,7 @@ impl Item {
|
||||
Item::KeystrokesCps => e.keystrokes_cps,
|
||||
Item::Minimap => e.minimap,
|
||||
Item::MinimapRotate => e.minimap_rotate,
|
||||
Item::AutoReconnect => e.auto_reconnect,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -545,6 +559,7 @@ impl Item {
|
||||
}
|
||||
Item::Minimap => e.minimap = !e.minimap,
|
||||
Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate,
|
||||
Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect,
|
||||
Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back),
|
||||
Item::MinimapSize => {
|
||||
let sizes: Vec<u8> = MINIMAP_SIZES.iter().map(|s| s.0).collect();
|
||||
@@ -564,7 +579,7 @@ mod tests {
|
||||
#[test]
|
||||
fn everything_is_off_by_default_and_round_trips() {
|
||||
let d = Extras::default();
|
||||
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap);
|
||||
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
|
||||
assert_eq!(Extras::parse(""), d);
|
||||
assert_eq!(Extras::parse(&d.serialize()), d);
|
||||
let mut e = d.clone();
|
||||
@@ -580,6 +595,7 @@ mod tests {
|
||||
e.minimap_zoom = 0.5;
|
||||
e.minimap_rotate = true;
|
||||
e.minimap_corner = Corner::BottomLeft;
|
||||
e.auto_reconnect = true;
|
||||
assert_eq!(Extras::parse(&e.serialize()), e);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ const REFRESH: u64 = id("mp.refresh", 0);
|
||||
const FIELD_A: u64 = id("mp.field", 0);
|
||||
const FIELD_B: u64 = id("mp.field", 1);
|
||||
const DONE: u64 = id("mp.done", 0);
|
||||
const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0);
|
||||
|
||||
/// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over
|
||||
/// the backdrop, then the interface comes in. A click or a key skips ahead.
|
||||
@@ -404,6 +405,7 @@ impl Title {
|
||||
Screen::Direct { .. } => 53,
|
||||
Screen::Disconnected { .. } => 54,
|
||||
}),
|
||||
CANCEL_RETRY => Some(55),
|
||||
DONE => Some(match screen {
|
||||
Screen::Direct { .. } => 52,
|
||||
_ => 50,
|
||||
@@ -809,7 +811,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
|
||||
);
|
||||
ui.divider(x, y + rh, w);
|
||||
}
|
||||
Screen::Disconnected { reason } => {
|
||||
Screen::Disconnected { reason, retry } => {
|
||||
let mut y = header(
|
||||
ui,
|
||||
x,
|
||||
@@ -836,6 +838,12 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
|
||||
);
|
||||
}
|
||||
y += box_h + 16.0;
|
||||
if let Some(r) = retry {
|
||||
// Auto-reconnect's countdown, with a way out.
|
||||
let text = r.text(std::time::Instant::now());
|
||||
ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text);
|
||||
y += 19.0 + 12.0;
|
||||
}
|
||||
let bw = ui.button_width("Back to servers", false);
|
||||
ui.button(
|
||||
BACK,
|
||||
@@ -844,6 +852,16 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
|
||||
Kind::Secondary,
|
||||
true,
|
||||
);
|
||||
if retry.is_some() {
|
||||
let cw = ui.button_width("Cancel reconnecting", false);
|
||||
ui.button(
|
||||
CANCEL_RETRY,
|
||||
[x + bw + 8.0, y, cw, CONTROL],
|
||||
"Cancel reconnecting",
|
||||
Kind::Ghost,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8691,6 +8691,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
self.extras_frame(elapsed);
|
||||
self.extras_retry()?;
|
||||
self.apply_mouse_look();
|
||||
self.pad_look(elapsed.as_secs_f32());
|
||||
self.advance_flight();
|
||||
|
||||
@@ -9,6 +9,9 @@ use horizon_client::{
|
||||
hud::{HudBatch, MINIMAP_SPRITE},
|
||||
keybinds,
|
||||
minimap::{self, Layer, Minimap, View},
|
||||
multiplayer,
|
||||
reconnect::{Retry, Tracker},
|
||||
title::Mode,
|
||||
};
|
||||
use std::time::Duration;
|
||||
use winit::{event::MouseButton, keyboard::KeyCode};
|
||||
@@ -23,6 +26,8 @@ pub(super) struct ExtrasState {
|
||||
minimap: Minimap,
|
||||
/// The dimension the minimap's tiles belong to.
|
||||
minimap_dim: Option<Dim>,
|
||||
/// Auto-reconnect's attempts at the current server.
|
||||
reconnect: Tracker,
|
||||
}
|
||||
/// CPU time the minimap's tiles may take per frame.
|
||||
const MINIMAP_BUDGET: Duration = Duration::from_micros(300);
|
||||
@@ -85,6 +90,55 @@ impl Game<'_> {
|
||||
self.extras.fps.clear();
|
||||
}
|
||||
}
|
||||
/// Auto-reconnect: a connection to `address` as `name` starts.
|
||||
pub(super) fn extras_connecting(&mut self, address: &str, name: &str) {
|
||||
self.extras.reconnect.connecting(address, name);
|
||||
}
|
||||
/// Auto-reconnect: the server let the player in.
|
||||
pub(super) fn extras_joined(&mut self) {
|
||||
self.extras.reconnect.joined(std::time::Instant::now());
|
||||
}
|
||||
/// Auto-reconnect: the player left the server on purpose.
|
||||
pub(super) fn extras_left(&mut self) {
|
||||
self.extras.reconnect.reset();
|
||||
}
|
||||
/// Auto-reconnect's next attempt after a disconnect, when it is on and
|
||||
/// the reason allows one.
|
||||
pub(super) fn reconnect_after(&mut self, reason: &str, from_server: bool) -> Option<Retry> {
|
||||
if !self.settings.extras.auto_reconnect {
|
||||
self.extras.reconnect.reset();
|
||||
return None;
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
self.extras.reconnect.ended(reason, from_server, now)
|
||||
}
|
||||
/// Show the attempt's countdown on the Disconnected screen.
|
||||
pub(super) fn offer_reconnect(&mut self, retry: Option<Retry>) {
|
||||
let Some(retry) = retry else {
|
||||
return;
|
||||
};
|
||||
if let Some(title) = self.title.as_mut()
|
||||
&& let Mode::Multiplayer(multiplayer::Screen::Disconnected { retry: slot, .. }) =
|
||||
&mut title.mode
|
||||
{
|
||||
log::info!(
|
||||
"Horizon: reconnecting to {} in {} s",
|
||||
retry.address,
|
||||
retry.seconds_left(std::time::Instant::now())
|
||||
);
|
||||
*slot = Some(retry);
|
||||
}
|
||||
}
|
||||
/// Auto-reconnect: connect again once the countdown is over. An
|
||||
/// online-mode server gets the signed-in account again: `connect_server`
|
||||
/// takes it from `auth::current()`, held in memory for the whole run
|
||||
/// (the launcher's session file is gone after the first read).
|
||||
pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> {
|
||||
if let Some(retry) = self.title.as_mut().and_then(|t| t.due_retry()) {
|
||||
self.connect_server(&retry.address, &retry.name)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The minimap's view of the player, if it shows.
|
||||
fn minimap_view(&self) -> Option<View> {
|
||||
let e = &self.settings.extras;
|
||||
|
||||
@@ -30,7 +30,7 @@ impl Game<'_> {
|
||||
if self.remote.is_none() {
|
||||
error = Some(match self.title.as_ref().map(|t| &t.mode) {
|
||||
Some(horizon_client::title::Mode::Multiplayer(
|
||||
horizon_client::multiplayer::Screen::Disconnected { reason },
|
||||
horizon_client::multiplayer::Screen::Disconnected { reason, .. },
|
||||
)) => format!("disconnected: {reason}"),
|
||||
_ => "disconnected".to_owned(),
|
||||
});
|
||||
|
||||
@@ -162,6 +162,7 @@ impl Game<'_> {
|
||||
let auth = horizon_client::auth::current();
|
||||
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
|
||||
let session = Session::connect(address, name, auth.clone(), view, lang.clone());
|
||||
self.extras_connecting(address, name);
|
||||
let player_type = super::perspective::player_type(&root);
|
||||
let mut streaming = Streaming::new(
|
||||
Arc::new(NoTerrain),
|
||||
@@ -260,6 +261,10 @@ impl Game<'_> {
|
||||
|
||||
/// Disconnect and return to the multiplayer screen (DisconnectedScreen).
|
||||
pub(super) fn leave_server(&mut self, reason: Option<String>) -> Result<()> {
|
||||
if reason.is_none() {
|
||||
// Leaving on purpose: nothing for auto-reconnect to retry.
|
||||
self.extras_left();
|
||||
}
|
||||
if let Some(mut r) = self.remote.take() {
|
||||
r.session.disconnect();
|
||||
}
|
||||
@@ -284,7 +289,10 @@ impl Game<'_> {
|
||||
let saves = std::env::current_dir()?.join("saves");
|
||||
let mut title = horizon_client::title::Title::new(saves.clone());
|
||||
title.mode = horizon_client::title::Mode::Multiplayer(match reason {
|
||||
Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason },
|
||||
Some(reason) => horizon_client::multiplayer::Screen::Disconnected {
|
||||
reason,
|
||||
retry: None,
|
||||
},
|
||||
None => horizon_client::multiplayer::Screen::list(&saves),
|
||||
});
|
||||
self.title = Some(title);
|
||||
@@ -374,6 +382,7 @@ impl Game<'_> {
|
||||
uuid,
|
||||
} => {
|
||||
self.set_registries(registries);
|
||||
self.extras_joined();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.joined = true;
|
||||
r.profile = uuid;
|
||||
@@ -389,9 +398,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Disconnected(reason) => {
|
||||
Event::Disconnected {
|
||||
reason,
|
||||
from_server,
|
||||
} => {
|
||||
log::info!("Horizon: disconnected: {reason}");
|
||||
return self.leave_server(Some(reason));
|
||||
let retry = self.reconnect_after(&reason, from_server);
|
||||
self.leave_server(Some(reason))?;
|
||||
self.offer_reconnect(retry);
|
||||
return Ok(());
|
||||
}
|
||||
Event::Packet(packet) => self.handle_packet(*packet)?,
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ pub mod raid;
|
||||
pub mod random_sequences;
|
||||
pub mod recipe_book;
|
||||
pub mod recipe_book_screen;
|
||||
pub mod reconnect;
|
||||
pub mod save;
|
||||
pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
|
||||
@@ -47,6 +47,8 @@ pub enum Screen {
|
||||
},
|
||||
Disconnected {
|
||||
reason: String,
|
||||
/// Auto-reconnect's next attempt, until it is cancelled.
|
||||
retry: Option<crate::reconnect::Retry>,
|
||||
},
|
||||
}
|
||||
/// What a click asks the title screen to do.
|
||||
@@ -205,14 +207,27 @@ impl Screen {
|
||||
53,
|
||||
),
|
||||
],
|
||||
Self::Disconnected { .. } => vec![b(
|
||||
w / 2.0 - 100.0,
|
||||
h / 2.0 + 30.0,
|
||||
200.0,
|
||||
"Back to Server List",
|
||||
true,
|
||||
54,
|
||||
)],
|
||||
Self::Disconnected { retry, .. } => {
|
||||
let mut v = vec![b(
|
||||
w / 2.0 - 100.0,
|
||||
h / 2.0 + 30.0,
|
||||
200.0,
|
||||
"Back to Server List",
|
||||
true,
|
||||
54,
|
||||
)];
|
||||
if retry.is_some() {
|
||||
v.push(b(
|
||||
w / 2.0 - 100.0,
|
||||
h / 2.0 + 54.0,
|
||||
200.0,
|
||||
"Cancel Reconnecting",
|
||||
true,
|
||||
55,
|
||||
));
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
}
|
||||
fn field(
|
||||
@@ -427,7 +442,7 @@ impl Screen {
|
||||
blink,
|
||||
);
|
||||
}
|
||||
Self::Disconnected { reason } => {
|
||||
Self::Disconnected { reason, retry } => {
|
||||
centered(
|
||||
batch,
|
||||
"Connection Lost",
|
||||
@@ -437,6 +452,10 @@ impl Screen {
|
||||
for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() {
|
||||
centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX);
|
||||
}
|
||||
if let Some(r) = retry {
|
||||
let text = r.text(std::time::Instant::now());
|
||||
centered(batch, &text, h / 2.0 + 16.0, rgba(170, 170, 170, 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,6 +571,7 @@ impl Screen {
|
||||
Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. },
|
||||
Some(51 | 53 | 54),
|
||||
) => *self = Self::list(saves),
|
||||
(Self::Disconnected { retry, .. }, Some(55)) => *retry = None,
|
||||
(Self::Direct { address }, Some(52)) => {
|
||||
return Outcome::Connect(address.trim().to_owned());
|
||||
}
|
||||
@@ -578,6 +598,16 @@ impl Screen {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Auto-reconnect's attempt, once its countdown is over.
|
||||
pub fn due_retry(&mut self) -> Option<crate::reconnect::Retry> {
|
||||
let Self::Disconnected { retry, .. } = self else {
|
||||
return None;
|
||||
};
|
||||
if !retry.as_ref()?.due(std::time::Instant::now()) {
|
||||
return None;
|
||||
}
|
||||
retry.take()
|
||||
}
|
||||
/// The focused text field, its id and maximum length (copy and paste).
|
||||
pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> {
|
||||
let id = match self {
|
||||
|
||||
@@ -40,7 +40,13 @@ pub enum Event {
|
||||
DecodeError(String),
|
||||
/// The server sent us back to configuration and finished it again.
|
||||
Reconfigured(Arc<Dynamic>),
|
||||
Disconnected(String),
|
||||
/// The connection ended. `from_server`: the server gave the reason (or
|
||||
/// the connection was refused for good), rather than the connection
|
||||
/// failing (auto-reconnect retries only failures and shutdowns).
|
||||
Disconnected {
|
||||
reason: String,
|
||||
from_server: bool,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
@@ -70,7 +76,7 @@ impl Session {
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("horizon-net".into())
|
||||
.spawn(move || {
|
||||
let reason = match run(
|
||||
let result = run(
|
||||
&address_owned,
|
||||
&name_owned,
|
||||
auth.as_deref(),
|
||||
@@ -79,14 +85,16 @@ impl Session {
|
||||
&send,
|
||||
&thread_writer,
|
||||
&thread_counters,
|
||||
) {
|
||||
Ok(reason) => reason,
|
||||
Err(e) => e,
|
||||
};
|
||||
);
|
||||
let from_server = result.is_ok();
|
||||
let reason = result.unwrap_or_else(|e| e);
|
||||
if let Some(w) = thread_writer.lock().unwrap().take() {
|
||||
w.shutdown();
|
||||
}
|
||||
let _ = send.send(Event::Disconnected(reason));
|
||||
let _ = send.send(Event::Disconnected {
|
||||
reason,
|
||||
from_server,
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some();
|
||||
@@ -149,7 +157,8 @@ fn tr(lang: &Language, key: &str) -> String {
|
||||
lang.get(key).cloned().unwrap_or_else(|| key.to_owned())
|
||||
}
|
||||
|
||||
/// The whole connection; returns the disconnect reason.
|
||||
/// The whole connection. Ok: why it ended for good (the server's reason, or
|
||||
/// a refusal no retry fixes); Err: the connection failed.
|
||||
fn run(
|
||||
address: &str,
|
||||
name: &str,
|
||||
@@ -160,8 +169,9 @@ fn run(
|
||||
shared_writer: &Mutex<Option<ConnWriter>>,
|
||||
shared_counters: &Mutex<Option<Arc<Counters>>>,
|
||||
) -> Result<String, String> {
|
||||
let (host, port) =
|
||||
parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?;
|
||||
let Some((host, port)) = parse_address(address) else {
|
||||
return Ok(format!("Invalid server address: {address}"));
|
||||
};
|
||||
status(send, "Connecting to the server...");
|
||||
let mut c =
|
||||
Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?;
|
||||
@@ -200,7 +210,7 @@ fn run(
|
||||
let reason = serde_json::from_str::<serde_json::Value>(&p.reason_json)
|
||||
.map(|v| json_text(&v, lang))
|
||||
.unwrap_or(p.reason_json);
|
||||
return Err(reason);
|
||||
return Ok(reason);
|
||||
}
|
||||
login::Clientbound::Hello(hello) => {
|
||||
status(send, &tr(lang, "connect.authorizing"));
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! The auto-reconnect extra (`docs/extras.md`): whether a lost multiplayer
|
||||
//! connection may be retried, and when. Only lost connections and the
|
||||
//! server's own shutdown or restart are retried, never kicks, bans or
|
||||
//! refusals; attempts back off and stop after a few.
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Seconds before each attempt; there are no more after the last.
|
||||
pub const DELAYS: [u64; 5] = [5, 10, 20, 40, 60];
|
||||
/// Staying connected this long counts the next drop as a fresh one.
|
||||
pub const STABLE: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Whether a disconnect may be retried. `from_server`: the server (or a
|
||||
/// permanent refusal) gave `reason`, rather than the connection failing.
|
||||
pub fn allowed(reason: &str, from_server: bool) -> bool {
|
||||
let r = reason.to_lowercase();
|
||||
// Kicks, bans, whitelists, version refusals and the account's session
|
||||
// refusals (`disconnect.loginFailedInfo.*` but the unreachable session
|
||||
// servers, the server's failed username check, joining an online-mode
|
||||
// server without an account): never.
|
||||
const NEVER: [&str; 13] = [
|
||||
"ban",
|
||||
"kick",
|
||||
"white-list",
|
||||
"whitelist",
|
||||
"incompatible",
|
||||
"outdated",
|
||||
"another location",
|
||||
"online mode",
|
||||
"invalid server address",
|
||||
"invalid session",
|
||||
"multiplayer is disabled",
|
||||
"failed to verify username",
|
||||
"microsoft account",
|
||||
];
|
||||
if NEVER.iter().any(|w| r.contains(w)) {
|
||||
return false;
|
||||
}
|
||||
if !from_server {
|
||||
return true;
|
||||
}
|
||||
// The server going away for a while: vanilla's shutdown and time-out
|
||||
// reasons, a full server, a slow login, the server's own session
|
||||
// servers being down, and restart messages.
|
||||
const RETRY: [&str; 6] = [
|
||||
"server closed",
|
||||
"timed out",
|
||||
"the server is full",
|
||||
"took too long to log in",
|
||||
"authentication servers",
|
||||
"restart",
|
||||
];
|
||||
RETRY.iter().any(|w| r.contains(w))
|
||||
}
|
||||
|
||||
/// Attempts at one address.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Tracker {
|
||||
address: Option<String>,
|
||||
/// The player name the connection used.
|
||||
name: String,
|
||||
/// Attempts already made since the last stable connection.
|
||||
attempts: usize,
|
||||
joined: Option<Instant>,
|
||||
}
|
||||
/// A planned attempt.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Retry {
|
||||
pub address: String,
|
||||
pub name: String,
|
||||
pub at: Instant,
|
||||
/// 1-based, of `DELAYS.len()`.
|
||||
pub attempt: usize,
|
||||
}
|
||||
impl Retry {
|
||||
/// Whole seconds left, rounded up.
|
||||
pub fn seconds_left(&self, now: Instant) -> u64 {
|
||||
let left = self.at.saturating_duration_since(now);
|
||||
left.as_secs() + u64::from(left.subsec_nanos() > 0)
|
||||
}
|
||||
pub fn due(&self, now: Instant) -> bool {
|
||||
now >= self.at
|
||||
}
|
||||
pub fn text(&self, now: Instant) -> String {
|
||||
format!(
|
||||
"Reconnecting in {} s (attempt {} of {})",
|
||||
self.seconds_left(now),
|
||||
self.attempt,
|
||||
DELAYS.len()
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Tracker {
|
||||
/// A connection to `address` as `name` starts: a new address starts
|
||||
/// counting anew.
|
||||
pub fn connecting(&mut self, address: &str, name: &str) {
|
||||
if self.address.as_deref() != Some(address) {
|
||||
self.address = Some(address.to_owned());
|
||||
self.attempts = 0;
|
||||
}
|
||||
self.name = name.to_owned();
|
||||
self.joined = None;
|
||||
}
|
||||
/// The server let the player in.
|
||||
pub fn joined(&mut self, now: Instant) {
|
||||
self.joined = Some(now);
|
||||
}
|
||||
/// The player left on purpose, or cancelled: nothing to retry.
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
/// The connection ended: the next attempt, or None (not allowed, or
|
||||
/// out of attempts).
|
||||
pub fn ended(&mut self, reason: &str, from_server: bool, now: Instant) -> Option<Retry> {
|
||||
if self
|
||||
.joined
|
||||
.take()
|
||||
.is_some_and(|t| now.saturating_duration_since(t) >= STABLE)
|
||||
{
|
||||
self.attempts = 0;
|
||||
}
|
||||
let address = self.address.clone()?;
|
||||
if !allowed(reason, from_server) || self.attempts >= DELAYS.len() {
|
||||
self.reset();
|
||||
return None;
|
||||
}
|
||||
let delay = Duration::from_secs(DELAYS[self.attempts]);
|
||||
self.attempts += 1;
|
||||
Some(Retry {
|
||||
address,
|
||||
name: self.name.clone(),
|
||||
at: now + delay,
|
||||
attempt: self.attempts,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_lost_connections_and_shutdowns_are_retried() {
|
||||
assert!(allowed("Connection reset by peer (os error 104)", false));
|
||||
assert!(allowed("Connection refused (os error 111)", false));
|
||||
assert!(allowed("Server closed", true));
|
||||
assert!(allowed("Timed out", true));
|
||||
assert!(allowed("The server is full!", true));
|
||||
assert!(allowed("Server is restarting, back soon", true));
|
||||
assert!(!allowed("Kicked by an operator", true));
|
||||
assert!(!allowed(
|
||||
"You are banned from this server.\nReason: griefing",
|
||||
true
|
||||
));
|
||||
assert!(!allowed("You are not white-listed on this server!", true));
|
||||
assert!(!allowed("You logged in from another location", true));
|
||||
assert!(!allowed("Incompatible client! Please use 26.3", true));
|
||||
assert!(!allowed("You have been idle for too long!", true));
|
||||
assert!(
|
||||
!allowed("Go away", true),
|
||||
"unknown server reasons are not retried"
|
||||
);
|
||||
assert!(!allowed(
|
||||
"This server is in online mode. Horizon only joins offline-mode servers.",
|
||||
true
|
||||
));
|
||||
assert!(!allowed("Kicked for spamming", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn online_mode_login_failures() {
|
||||
// The client's join with the session service (net.rs: Err, with
|
||||
// vanilla's disconnect.loginFailedInfo texts).
|
||||
let failed = |why: &str| format!("Failed to log in: {why}");
|
||||
assert!(!allowed(
|
||||
&failed("Invalid session (Try restarting your game and the launcher)"),
|
||||
false
|
||||
));
|
||||
assert!(!allowed(
|
||||
&failed("You are banned from playing online"),
|
||||
false
|
||||
));
|
||||
assert!(!allowed(
|
||||
&failed("Multiplayer is disabled. Please check your Microsoft account settings."),
|
||||
false
|
||||
));
|
||||
assert!(!allowed(crate::net::NOT_SIGNED_IN, false));
|
||||
// Unreachable session servers are worth another try.
|
||||
assert!(allowed(
|
||||
&failed("The authentication servers are currently not reachable. Please try again."),
|
||||
false
|
||||
));
|
||||
assert!(allowed(&failed("Connection timed out"), false));
|
||||
// The server's side: its username check failed, or its session
|
||||
// servers are down.
|
||||
assert!(!allowed("Failed to verify username!", true));
|
||||
assert!(allowed(
|
||||
"Authentication servers are down. Please try again later. Sorry!",
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attempts_back_off_and_stop() {
|
||||
let mut t = Tracker::default();
|
||||
let now = Instant::now();
|
||||
t.connecting("localhost:25565", "Tester");
|
||||
let mut delays = Vec::new();
|
||||
while let Some(r) = t.ended("Connection refused", false, now) {
|
||||
assert_eq!(
|
||||
(r.address.as_str(), r.name.as_str()),
|
||||
("localhost:25565", "Tester")
|
||||
);
|
||||
assert_eq!(r.attempt, delays.len() + 1);
|
||||
delays.push(r.at.duration_since(now).as_secs());
|
||||
t.connecting(&r.address, &r.name);
|
||||
}
|
||||
assert_eq!(delays, DELAYS);
|
||||
// Out of attempts, the tracker forgets the address.
|
||||
assert_eq!(t.ended("Connection refused", false, now), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_stay_does_not_reset_the_count() {
|
||||
let mut t = Tracker::default();
|
||||
let now = Instant::now();
|
||||
t.connecting("a", "P");
|
||||
for _ in 0..DELAYS.len() {
|
||||
t.connecting("a", "P");
|
||||
t.joined(now);
|
||||
assert!(
|
||||
t.ended("Server closed", true, now + Duration::from_secs(5))
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
t.connecting("a", "P");
|
||||
t.joined(now);
|
||||
assert_eq!(
|
||||
t.ended("Server closed", true, now + Duration::from_secs(5)),
|
||||
None
|
||||
);
|
||||
// A minute connected starts over.
|
||||
t.connecting("a", "P");
|
||||
for _ in 0..3 {
|
||||
t.ended("Timed out", true, now);
|
||||
t.connecting("a", "P");
|
||||
}
|
||||
t.joined(now);
|
||||
let r = t.ended("Timed out", true, now + STABLE).unwrap();
|
||||
assert_eq!(r.attempt, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kicks_and_leaving_reset_and_new_addresses_start_over() {
|
||||
let mut t = Tracker::default();
|
||||
let now = Instant::now();
|
||||
t.connecting("a", "P");
|
||||
assert!(t.ended("Server closed", true, now).is_some());
|
||||
assert_eq!(t.ended("Kicked by an operator", true, now), None);
|
||||
assert_eq!(
|
||||
t.ended("Server closed", true, now),
|
||||
None,
|
||||
"forgotten after a kick"
|
||||
);
|
||||
t.connecting("a", "P");
|
||||
t.ended("Server closed", true, now);
|
||||
t.connecting("b", "P");
|
||||
assert_eq!(t.ended("Server closed", true, now).unwrap().attempt, 1);
|
||||
let mut t = Tracker::default();
|
||||
assert_eq!(t.ended("Server closed", true, now), None, "never connected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_countdown_rounds_up() {
|
||||
let now = Instant::now();
|
||||
let r = Retry {
|
||||
address: "a".into(),
|
||||
name: "P".into(),
|
||||
at: now + Duration::from_millis(4200),
|
||||
attempt: 2,
|
||||
};
|
||||
assert_eq!(r.seconds_left(now), 5);
|
||||
assert_eq!(r.text(now), "Reconnecting in 5 s (attempt 2 of 5)");
|
||||
assert!(!r.due(now));
|
||||
assert!(r.due(now + Duration::from_secs(5)));
|
||||
assert_eq!(r.seconds_left(now + Duration::from_secs(9)), 0);
|
||||
}
|
||||
}
|
||||
@@ -593,6 +593,13 @@ impl Title {
|
||||
*focus = (*focus + 1) % 2;
|
||||
}
|
||||
}
|
||||
/// The server auto-reconnect retries now, once its countdown is over.
|
||||
pub fn due_retry(&mut self) -> Option<crate::reconnect::Retry> {
|
||||
match &mut self.mode {
|
||||
Mode::Multiplayer(screen) => screen.due_retry(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn escape(&mut self) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode
|
||||
&& !screen.escape(&self.saves)
|
||||
|
||||
+8
-4
@@ -85,10 +85,14 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int
|
||||
- Backoff 5, 10, 20, 40, 60 s; at most 5 attempts, then it stops. The count
|
||||
only resets after staying connected for a minute, so a server that drops
|
||||
players at once never causes an endless loop.
|
||||
- Never after a kick, a ban, a whitelist or version refusal, a duplicate login
|
||||
or an online-mode refusal: only lost connections (errors, time-outs, refused
|
||||
connections while the server restarts) and the server's own "Server closed"
|
||||
shutdown reason.
|
||||
- Never after a kick, a ban, a whitelist or version refusal, a duplicate login,
|
||||
an online-mode refusal (no account signed in), or a session refusal from the
|
||||
account's login (invalid session, banned from playing online, multiplayer
|
||||
disabled, the server failing to verify the username). Unreachable session
|
||||
servers, on either side, are retried with the same backoff.
|
||||
- Online-mode servers: the retry joins with the account the game signed in
|
||||
with, held in memory for the whole run (`auth::current()`); nothing is
|
||||
written to disk.
|
||||
|
||||
## Shared rules
|
||||
|
||||
|
||||
Reference in New Issue
Block a user