From 2d6c1c33e3de3aa95fe26fb704f9d2e834dc76e4 Mon Sep 17 00:00:00 2001 From: JonatanRek Date: Sun, 8 Nov 2026 00:05:55 +0100 Subject: [PATCH 1/2] Add association_to_pool mapping for client slots Added mapping from AssociationId to game pool slot, allowing tracking of client slots even without an active tunnel. --- src/services/tunnel/mappings.rs | 70 +++------------------------------ 1 file changed, 6 insertions(+), 64 deletions(-) diff --git a/src/services/tunnel/mappings.rs b/src/services/tunnel/mappings.rs index 2ee7e3d..3ce1a90 100644 --- a/src/services/tunnel/mappings.rs +++ b/src/services/tunnel/mappings.rs @@ -75,6 +75,11 @@ pub struct TunnelMappings { /// Mapping from [AssociationId] (Client association) to [TunnelHandle] association_to_tunnel: HashMap, + /// Mapping from [AssociationId] to the game pool slot the client is in, + /// kept even if the client doesn't have a tunnel yet so a tunnel created + /// (or re-created) later on is still connected to the right slot + association_to_pool: HashMap, + pool: TunnelPoolMap, } @@ -138,7 +143,7 @@ impl TunnelMappings { // Retain all now expired tunnels self.id_to_tunnel.retain(|tunnel_id, data| { // Initial dead check based on keep alive timeout - let mut dead = data.last_alive.duration_since(now) > keep_alive_timeout; + let mut dead = now.duration_since(data.last_alive) > keep_alive_timeout; // Check for closed http tunnels if let TunnelHandle::Http(handle) = &data.handle @@ -160,66 +165,3 @@ impl TunnelMappings { /// Inserts a new tunnel into the mappings and associates it to the /// provided association token - /// - /// Creates and returns a tunnel ID if [None] is returned no tunnel ID could be created - pub fn insert_tunnel( - &mut self, - association: AssociationId, - tunnel: TunnelData, - ) -> Option { - let tunnel_id = self.acquire_tunnel_id()?; - - // Insert the tunnel into the mappings - self.id_to_tunnel.insert(tunnel_id, tunnel); - self.association_to_tunnel.insert(association, tunnel_id); - - Some(tunnel_id) - } - - pub fn update_tunnel_handle(&mut self, tunnel_id: TunnelId, handle: TunnelHandle) { - if let Some(tunnel_data) = self.id_to_tunnel.get_mut(&tunnel_id) { - tunnel_data.handle = handle; - } - } - - /// Updates the last-alive instant for the tunnel - pub fn update_tunnel_last_alive(&mut self, tunnel_id: TunnelId, last_alive: Instant) { - if let Some(tunnel_data) = self.id_to_tunnel.get_mut(&tunnel_id) { - tunnel_data.last_alive = last_alive; - } - } - - pub fn get_association_tunnel(&self, association: &AssociationId) -> Option { - self.association_to_tunnel.get(association).copied() - } - - /// Attempts to associate the tunnel from `address` to the provided - /// `pool_id` and `pool_index` if there is a tunnel connected to - /// `address` - pub fn associate_pool(&mut self, tunnel_id: TunnelId, pool_id: PoolId, pool_index: PoolIndex) { - let key = PoolKey::new(pool_id, pool_index); - self.pool.insert(tunnel_id, key); - } - - /// Removes the association between a [PoolKey] and a [TunnelId] if - /// one is present - pub fn dissociate_pool(&mut self, pool_id: PoolId, pool_index: PoolIndex) { - self.pool - .remove_by_pool_key(&PoolKey::new(pool_id, pool_index)); - } - - /// Get the pool key of a tunnel - pub fn get_tunnel_pool_key(&self, tunnel_id: TunnelId) -> Option<(PoolId, PoolIndex)> { - self.pool - .get_by_tunnel(&tunnel_id) - .map(|pool_key| pool_key.parts()) - } - - /// Get a tunnel using a pool key - pub fn get_tunnel_by_pool_key(&self, pool_key: &PoolKey) -> Option<&TunnelHandle> { - let tunnel_id = self.pool.get_by_pool_key(pool_key)?; - self.id_to_tunnel - .get(tunnel_id) - .map(|tunnel| &tunnel.handle) - } -} From 67b761d5aa815f01f078dedbde32ef1190b08278 Mon Sep 17 00:00:00 2001 From: Jonatan Rek Date: Sun, 8 Nov 2026 09:37:16 +0100 Subject: [PATCH 2/2] Addition tweaks for match making --- .gitignore | 3 +- src/services/game/matchmaking.rs | 25 +++++++++++++++-- src/services/game/mod.rs | 43 +++++++++++++++++++++++++++-- src/services/tunnel/mod.rs | 19 +++++++------ src/session/routes/game_manager.rs | 44 +++++++++++++++++++++++++----- src/utils/logging.rs | 18 +++++++++++- 6 files changed, 130 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index 89438de..4ed97da 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ tools/target /src/resources/public/* !/src/resources/public/content -*.exe \ No newline at end of file +*.exe +.megamemory/* diff --git a/src/services/game/matchmaking.rs b/src/services/game/matchmaking.rs index 7bbabb2..fde0e56 100644 --- a/src/services/game/matchmaking.rs +++ b/src/services/game/matchmaking.rs @@ -62,16 +62,32 @@ impl Matchmaking { ) { let queue = &mut *self.queue.lock(); - while let Some(entry) = queue.front() { - let join_state = { link.read().joinable_state(Some(&entry.rule_set)) }; + // Index of the queue entry currently being checked. Entries that don't + // match this game are skipped instead of being re-checked forever + let mut index = 0; + + while let Some(entry) = queue.get(index) { + let (join_state, tunnel_ready) = { + let game = link.read(); + ( + game.joinable_state(Some(&entry.rule_set)), + game.is_tunnel_ready(config, tunnel_service, &entry.player), + ) + }; // TODO: If player has been in queue long enough create // a game matching their specifics match join_state { + GameJoinableState::Joinable if !tunnel_ready => { + // Player doesn't have a connected tunnel yet so they wouldn't + // be able to communicate with the game, keep them queued + index += 1; + } GameJoinableState::Joinable => { + // Index is not advanced, the next entry moves into this position let entry = queue - .pop_front() + .remove(index) .expect("Expecting matchmaking entry but nothing was present"); debug!("Found player from queue adding them to the game (GID: {game_id})"); @@ -92,6 +108,9 @@ impl Matchmaking { GameJoinableState::NotMatch => { // TODO: Check started time and timeout // player if they've been waiting too long + + // Skip this entry and check the next one + index += 1; } } } diff --git a/src/services/game/mod.rs b/src/services/game/mod.rs index 65dfdd6..cb335f3 100644 --- a/src/services/game/mod.rs +++ b/src/services/game/mod.rs @@ -1,12 +1,12 @@ use self::rules::RuleSet; use crate::{ - config::Config, + config::{Config, TunnelConfig}, database::entities::Player, session::{ SessionLink, WeakSessionLink, data::NetData, models::{ - NetworkAddress, + NatType, NetworkAddress, game_manager::{ AdminListChange, AdminListOperation, AttributesChange, GameSettings, GameSetupContext, GameSetupResponse, GameState, GetGameDetails, @@ -449,6 +449,45 @@ impl Game { self.games_store.remove_by_id(self.id); } + /// Whether players joining this game must have a connected tunnel + /// (Mirrors the tunnel decision used when sending the game setup) + pub fn requires_tunnel(&self, config: &Config) -> bool { + match config.tunnel { + TunnelConfig::Always => true, + TunnelConfig::Disabled => false, + TunnelConfig::Stricter => { + let host_net = self + .players + .first() + .and_then(|host| host.net()) + .unwrap_or_default(); + !matches!(host_net.qos.natt, NatType::Open) + } + } + } + + /// Whether the player is able to communicate with this game, players + /// without a connected tunnel can't join games that require one + pub fn is_tunnel_ready( + &self, + config: &Config, + tunnel_service: &TunnelService, + player: &GamePlayer, + ) -> bool { + if !self.requires_tunnel(config) { + return true; + } + + let Some(session) = player.link.upgrade() else { + return false; + }; + + session + .data + .get_association() + .is_some_and(|association| tunnel_service.has_tunnel(&association)) + } + pub fn joinable_state(&self, rule_set: Option<&RuleSet>) -> GameJoinableState { if let GameState::Destructing = self.state { return GameJoinableState::Stopping; diff --git a/src/services/tunnel/mod.rs b/src/services/tunnel/mod.rs index c374312..0d0465e 100644 --- a/src/services/tunnel/mod.rs +++ b/src/services/tunnel/mod.rs @@ -62,15 +62,18 @@ impl TunnelService { pool_id: PoolId, pool_index: PoolIndex, ) { - let mappings = &mut *self.mappings.write(); - let tunnel_id = { - match mappings.get_association_tunnel(&association) { - Some(value) => value, - None => return, - } - }; + self.mappings + .write() + .associate_pool(association, pool_id, pool_index); + } - mappings.associate_pool(tunnel_id, pool_id, pool_index); + /// Checks whether the client with the provided association + /// currently has a connected tunnel + pub fn has_tunnel(&self, association: &AssociationId) -> bool { + self.mappings + .read() + .get_association_tunnel(association) + .is_some() } pub fn dissociate_pool(&self, pool_id: PoolId, pool_index: PoolIndex) { diff --git a/src/session/routes/game_manager.rs b/src/session/routes/game_manager.rs index c425d9f..a80b38b 100644 --- a/src/session/routes/game_manager.rs +++ b/src/session/routes/game_manager.rs @@ -24,7 +24,7 @@ use crate::{ utils::parsing::player_character::PlayerCharacter, }; use chrono::Utc; -use log::{debug, error, info}; +use log::{debug, error, info, warn}; use std::{collections::HashMap, sync::Arc}; pub async fn handle_join_game( @@ -46,13 +46,27 @@ pub async fn handle_join_game( .get_game() .ok_or(GameManagerError::InvalidGameId)?; - // Check the game is joinable - let join_state = { game_ref.read().joinable_state(None) }; + // Check the game is joinable and the player is able to communicate with it + let (join_state, tunnel_ready) = { + let game = game_ref.read(); + ( + game.joinable_state(None), + game.is_tunnel_ready(&config, &tunnel_service, &player), + ) + }; if !matches!(join_state, GameJoinableState::Joinable) { return Err(GameManagerError::GameFull.into()); } + if !tunnel_ready { + warn!( + "Player {} has no connected tunnel, unable to join game (GID: {game_id})", + player.player.display_name + ); + return Err(GameManagerError::JoinPlayerFailed.into()); + } + // Join the game debug!("Joining game from invite (GID: {game_id})"); @@ -721,10 +735,26 @@ pub async fn handle_start_matchmaking( // Find a game thats currently joinable and matches the required rules match games.get_by_rule_set(&rules) { Some((game_id, game_ref)) => { - debug!("Found matching game (GID: {game_id})"); - - // Add the player to the game - matchmaking.add_from_matchmaking(&tunnel_service, &config, game_ref, player); + let tunnel_ready = { + game_ref + .read() + .is_tunnel_ready(&config, &tunnel_service, &player) + }; + + if tunnel_ready { + debug!("Found matching game (GID: {game_id})"); + + // Add the player to the game + matchmaking.add_from_matchmaking(&tunnel_service, &config, game_ref, player); + } else { + warn!( + "Player {} has no connected tunnel, queueing instead of joining game (GID: {game_id})", + player.player.display_name + ); + + // Queue the player until their tunnel is connected + matchmaking.queue(player, rules); + } } None => { matchmaking.queue(player, rules); diff --git a/src/utils/logging.rs b/src/utils/logging.rs index f61040d..80709e3 100644 --- a/src/utils/logging.rs +++ b/src/utils/logging.rs @@ -97,7 +97,12 @@ pub async fn log_connection_urls(http_port: u16) { /// value if its not expired or fetching the new value from the API using /// `fetch_public_addr` pub async fn public_address() -> Option { - // Try fetch from cloudflare first + // Try fetch from ifconfig.me first + if let Some(addr) = public_address_ifconfig().await { + return Some(addr); + } + + // Fallback to cloudflare if let Some(addr) = public_address_cloudflare().await { return Some(addr); } @@ -130,6 +135,17 @@ pub async fn public_address() -> Option { None } +/// Retrieves the public address of the server using the ifconfig.me API +pub async fn public_address_ifconfig() -> Option { + let response = reqwest::get("https://ifconfig.me/ip") + .and_then(reqwest::Response::text) + .await + .ok()?; + + // Trim whitespace and attempt to parse as an IPv4 address + response.trim().parse::().ok() +} + /// Retrieves the public address of the server using the cloudflare API pub async fn public_address_cloudflare() -> Option { let response = match reqwest::get("https://cloudflare.com/cdn-cgi/trace")