Files
tuliprox/backend/src/api/model/active_user_manager.rs
T

596 lines
24 KiB
Rust
Raw Normal View History

use crate::api::model::{CustomVideoStreamType, EventManager, EventMessage};
2025-11-04 18:01:44 +01:00
use crate::auth::Fingerprint;
2025-05-04 10:59:08 +02:00
use crate::model::Config;
2025-07-19 15:32:30 +02:00
use crate::model::ProxyUserCredentials;
2025-11-04 18:01:44 +01:00
use crate::utils::GeoIp;
use arc_swap::ArcSwapOption;
use jsonwebtoken::get_current_timestamp;
2025-11-04 21:46:44 +01:00
use log::{debug, info};
2025-12-12 20:32:46 +01:00
use shared::model::{ActiveUserConnectionChange, StreamChannel, StreamInfo, UserConnectionPermission, VirtualId};
2026-01-20 10:09:58 +01:00
use shared::utils::{current_time_secs, default_grace_period_millis, default_grace_period_timeout_secs,
sanitize_sensitive_info, strip_port, Internable};
2025-11-04 18:01:44 +01:00
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
2025-11-04 18:01:44 +01:00
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
2025-06-09 13:23:27 +02:00
use std::sync::Arc;
2025-07-27 20:47:35 +02:00
use tokio::sync::RwLock;
2025-12-15 17:54:19 +01:00
use crate::utils::debug_if_enabled;
2025-10-11 16:28:07 +02:00
const USER_GC_TTL: u64 = 900; // 15 Min
const USER_CON_TTL: u64 = 10_800; // 3 hours
const USER_SESSION_LIMIT: usize = 50;
2025-06-24 12:31:38 +02:00
fn get_grace_options(config: &Config) -> (u64, u64) {
let (grace_period_millis, grace_period_timeout_secs) = config.reverse_proxy.as_ref()
.and_then(|r| r.stream.as_ref())
.map_or_else(|| (default_grace_period_millis(), default_grace_period_timeout_secs()), |s| (s.grace_period_millis, s.grace_period_timeout_secs));
(grace_period_millis, grace_period_timeout_secs)
}
#[derive(Clone, Debug)]
pub struct UserSession {
2025-06-05 17:51:03 +02:00
pub token: String,
pub virtual_id: u32,
2026-01-20 10:09:58 +01:00
pub provider: Arc<str>,
pub stream_url: Arc<str>,
2025-11-04 18:01:44 +01:00
pub addr: SocketAddr,
pub ts: u64,
pub permission: UserConnectionPermission,
}
#[derive(Debug)]
struct UserConnectionData {
2025-04-28 19:52:59 +02:00
max_connections: u32,
connections: u32,
2025-04-27 13:26:21 +02:00
granted_grace: bool,
grace_ts: u64,
sessions: Vec<UserSession>,
2025-10-24 18:36:13 +02:00
streams: Vec<StreamInfo>,
2025-10-11 16:28:07 +02:00
ts: u64,
}
impl UserConnectionData {
2025-04-30 11:04:01 +02:00
fn new(connections: u32, max_connections: u32) -> Self {
Self {
max_connections,
2025-04-30 11:04:01 +02:00
connections,
2025-04-27 13:26:21 +02:00
granted_grace: false,
grace_ts: 0,
sessions: Vec::new(),
2025-10-24 18:36:13 +02:00
streams: Vec::new(),
2025-10-11 16:28:07 +02:00
ts: current_time_secs(),
}
}
2025-06-09 13:23:27 +02:00
fn add_session(&mut self, session: UserSession) {
self.gc();
self.sessions.push(session);
}
fn gc(&mut self) {
if self.sessions.len() > USER_SESSION_LIMIT {
self.sessions.sort_by_key(|e| std::cmp::Reverse(e.ts));
self.sessions.truncate(USER_SESSION_LIMIT);
}
}
}
2025-11-05 11:50:05 +01:00
#[derive(Debug, Default)]
struct UserConnections {
2025-12-12 20:32:46 +01:00
kicked: HashMap<String, (u64, VirtualId)>,
2025-11-05 11:50:05 +01:00
by_key: HashMap<String, UserConnectionData>,
key_by_addr: HashMap<SocketAddr, String>,
}
2025-02-06 20:31:51 +01:00
pub struct ActiveUserManager {
2025-06-24 12:31:38 +02:00
grace_period_millis: AtomicU64,
grace_period_timeout_secs: AtomicU64,
log_active_user: AtomicBool,
2025-04-30 11:04:01 +02:00
gc_ts: Option<AtomicU64>,
2025-11-05 11:50:05 +01:00
connections: RwLock<UserConnections>,
2025-11-04 22:56:27 +01:00
event_manager: Arc<EventManager>,
geo_ip: Arc<ArcSwapOption<GeoIp>>,
last_logged_user_count: AtomicUsize,
last_logged_user_connection_count: AtomicUsize,
2025-02-06 20:31:51 +01:00
}
impl ActiveUserManager {
2025-11-04 21:46:44 +01:00
pub fn new(config: &Config,
2025-11-04 22:56:27 +01:00
geoip: &Arc<ArcSwapOption<GeoIp>>,
event_manager: &Arc<EventManager>, ) -> Self {
2025-10-27 13:58:55 +01:00
let log_active_user: bool = config.log.as_ref().is_some_and(|l| l.log_active_user);
2025-06-24 12:31:38 +02:00
let (grace_period_millis, grace_period_timeout_secs) = get_grace_options(config);
2025-10-27 13:58:55 +01:00
2025-11-04 21:46:44 +01:00
Self {
2025-07-19 15:32:30 +02:00
grace_period_millis: AtomicU64::new(grace_period_millis),
2025-06-24 12:31:38 +02:00
grace_period_timeout_secs: AtomicU64::new(grace_period_timeout_secs),
log_active_user: AtomicBool::new(log_active_user),
2025-11-05 11:50:05 +01:00
connections: RwLock::new(UserConnections::default()),
2025-04-30 11:04:01 +02:00
gc_ts: Some(AtomicU64::new(current_time_secs())),
geo_ip: Arc::clone(geoip),
2025-11-04 22:56:27 +01:00
event_manager: Arc::clone(event_manager),
last_logged_user_count: AtomicUsize::new(0),
last_logged_user_connection_count: AtomicUsize::new(0),
2025-11-04 21:46:44 +01:00
}
}
2025-11-04 18:01:44 +01:00
async fn log_active_user(&self) {
let is_log_user_enabled = self.is_log_user_enabled();
2025-11-05 11:50:05 +01:00
let (user_count, user_connection_count) = {
self.active_users_and_connections().await
2025-11-05 11:50:05 +01:00
};
2025-11-04 22:56:27 +01:00
self.event_manager.send_event(EventMessage::ActiveUser(ActiveUserConnectionChange::Connections(user_count, user_connection_count)));
2025-11-04 18:01:44 +01:00
if is_log_user_enabled {
let last_user_count = self.last_logged_user_count.load(Ordering::Relaxed);
let last_connection_count = self.last_logged_user_connection_count.load(Ordering::Relaxed);
if last_user_count != user_count || last_connection_count != user_connection_count {
self.last_logged_user_count.store(user_count, Ordering::Relaxed);
self.last_logged_user_connection_count.store(user_connection_count, Ordering::Relaxed);
info!("Active Users: {user_count}, Active User Connections: {user_connection_count}");
}
2025-11-04 18:01:44 +01:00
}
}
2025-11-04 21:46:44 +01:00
pub async fn release_connection(&self, addr: &SocketAddr) {
2025-11-17 08:06:28 -06:00
let (log_active_user, disconnected_user) = {
2025-11-05 11:50:05 +01:00
let mut user_connections = self.connections.write().await;
2025-11-04 18:01:44 +01:00
if let Some(username) = user_connections.key_by_addr.remove(addr) {
if let Some(connection_data) = user_connections.by_key.get_mut(&username) {
if connection_data.connections > 0 {
connection_data.connections -= 1;
2025-11-04 18:01:44 +01:00
}
if connection_data.connections < connection_data.max_connections {
connection_data.granted_grace = false;
connection_data.grace_ts = 0;
}
connection_data.streams.retain(|c| c.addr != *addr);
2025-11-04 18:01:44 +01:00
}
2025-11-17 08:06:28 -06:00
(true, Some(username))
2025-11-05 11:50:05 +01:00
} else {
2025-11-17 08:06:28 -06:00
(false, None)
2025-11-04 18:01:44 +01:00
}
};
2025-11-04 18:01:44 +01:00
2025-11-17 08:06:28 -06:00
if let Some(username) = disconnected_user {
2025-11-20 13:00:01 +01:00
if !username.is_empty() {
2025-12-15 17:54:19 +01:00
debug_if_enabled!("Released connection for user {username} at {}", sanitize_sensitive_info(&addr.to_string()));
2025-11-20 13:00:01 +01:00
}
2025-11-17 08:06:28 -06:00
}
2025-11-05 11:50:05 +01:00
if log_active_user {
2025-11-04 18:01:44 +01:00
self.log_active_user().await;
}
}
2025-07-19 15:32:30 +02:00
2025-06-24 12:31:38 +02:00
pub fn update_config(&self, config: &Config) {
let log_active_user = config.log.as_ref().is_some_and(|l| l.log_active_user);
let (grace_period_millis, grace_period_timeout_secs) = get_grace_options(config);
self.grace_period_millis.store(grace_period_millis, Ordering::Relaxed);
self.grace_period_timeout_secs.store(grace_period_timeout_secs, Ordering::Relaxed);
self.log_active_user.store(log_active_user, Ordering::Relaxed);
}
2025-07-27 20:47:35 +02:00
pub async fn user_connections(&self, username: &str) -> u32 {
2025-11-05 11:50:05 +01:00
if let Some(connection_data) = self.connections.read().await.by_key.get(username) {
return connection_data.connections;
2025-02-06 20:31:51 +01:00
}
0
}
2025-04-30 11:04:01 +02:00
fn check_connection_permission(&self, username: &str, connection_data: &mut UserConnectionData) -> UserConnectionPermission {
let current_connections = connection_data.connections;
2025-04-30 11:04:01 +02:00
if current_connections < connection_data.max_connections {
2025-07-15 12:28:25 +02:00
// Reset grace period because the user is back under max_connections
2025-04-30 11:04:01 +02:00
connection_data.granted_grace = false;
connection_data.grace_ts = 0;
return UserConnectionPermission::Allowed;
}
2025-04-30 11:04:01 +02:00
let now = get_current_timestamp();
2025-07-15 12:28:25 +02:00
// Check if user already used a grace period
2025-04-30 11:04:01 +02:00
if connection_data.granted_grace {
2025-06-24 12:31:38 +02:00
if current_connections > connection_data.max_connections && now - connection_data.grace_ts <= self.grace_period_timeout_secs.load(Ordering::Relaxed) {
2025-07-15 12:28:25 +02:00
// Grace timeout, still active, deny connection
2025-04-30 11:04:01 +02:00
debug!("User access denied, grace exhausted, too many connections: {username}");
return UserConnectionPermission::Exhausted;
}
2025-04-30 11:04:01 +02:00
// Grace timeout expired, reset grace counters
connection_data.granted_grace = false;
connection_data.grace_ts = 0;
}
2025-06-24 12:31:38 +02:00
if self.grace_period_millis.load(Ordering::Relaxed) > 0 && current_connections == connection_data.max_connections {
2025-07-15 12:28:25 +02:00
// Allow a grace period once
2025-04-30 11:04:01 +02:00
connection_data.granted_grace = true;
connection_data.grace_ts = now;
2025-07-15 12:28:25 +02:00
debug!("Granted a grace period for user access: {username}");
2025-04-30 11:04:01 +02:00
return UserConnectionPermission::GracePeriod;
}
2025-04-30 11:04:01 +02:00
// Too many connections, no grace allowed
debug!("User access denied, too many connections: {username}");
UserConnectionPermission::Exhausted
}
2025-07-27 20:47:35 +02:00
pub async fn connection_permission(
2025-04-27 13:26:21 +02:00
&self,
username: &str,
max_connections: u32,
) -> UserConnectionPermission {
2025-04-27 15:23:22 +02:00
if max_connections > 0 {
2025-11-05 11:50:05 +01:00
if let Some(connection_data) = self.connections.write().await.by_key.get_mut(username) {
2025-07-27 20:47:35 +02:00
return self.check_connection_permission(username, connection_data);
2025-04-27 15:23:22 +02:00
}
}
UserConnectionPermission::Allowed
}
pub async fn active_users_and_connections(&self) -> (usize, usize) {
let user_connections = self.connections.read().await;
user_connections
.by_key
.values()
.filter(|c| c.connections > 0)
.fold((0usize, 0usize), |(user_count, conn_count), c| {
2025-11-06 12:50:10 +01:00
(user_count + 1, conn_count + c.connections as usize)
})
2025-02-06 20:31:51 +01:00
}
2025-11-10 01:04:13 +01:00
pub async fn update_stream_detail(&self, addr: &SocketAddr, video_type: CustomVideoStreamType) -> Option<StreamInfo> {
let mut user_connections = self.connections.write().await;
2025-11-10 01:04:13 +01:00
let username = {
match user_connections.key_by_addr.get(addr) {
Some(username) => username.clone(),
None => return None,
}
};
if let Some(connection_data) = user_connections.by_key.get_mut(&username) {
for stream in &mut connection_data.streams {
2025-11-10 01:04:13 +01:00
if &stream.addr == addr {
stream.provider = String::from("tuliprox");
2026-01-20 10:09:58 +01:00
stream.channel.title = video_type.to_string().into();
stream.channel.group = "".intern();
return Some(stream.clone());
}
}
}
None
2025-05-06 12:19:37 +02:00
}
#[allow(clippy::too_many_arguments)]
2025-11-10 01:04:13 +01:00
pub async fn add_connection(&self, addr: &SocketAddr) {
let mut user_connections = self.connections.write().await;
if !user_connections.key_by_addr.contains_key(addr) {
user_connections.key_by_addr.insert(*addr, String::new());
}
}
#[allow(clippy::too_many_arguments)]
pub async fn update_connection(&self, username: &str, max_connections: u32, fingerprint: &Fingerprint,
2025-11-19 23:00:25 -06:00
provider: &str, stream_channel: StreamChannel, user_agent: Cow<'_, str>, session_token: Option<&str>) -> Option<StreamInfo> {
let stream_info = {
let mut user_connections = self.connections.write().await;
2025-11-10 01:04:13 +01:00
// needs to be registered through socket connection to avoid race time conditions through short disconnect
if !user_connections.key_by_addr.contains_key(&fingerprint.addr) {
2025-11-10 01:04:13 +01:00
return None;
}
user_connections.key_by_addr.insert(fingerprint.addr, username.to_string());
let connection_data = user_connections.by_key
.entry(username.to_string())
.or_insert_with(|| UserConnectionData::new(0, max_connections));
connection_data.max_connections = max_connections;
2025-11-19 23:00:25 -06:00
let user_agent_string = user_agent.to_string();
let existing_stream_info = connection_data
.streams
.iter_mut()
.find(|s| s.addr == fingerprint.addr)
.map(|stream_info| {
stream_info.channel = stream_channel.clone();
stream_info.provider = provider.to_string();
stream_info.user_agent.clone_from(&user_agent_string);
stream_info.ts = current_time_secs();
if let Some(token) = session_token {
stream_info.session_token = Some(token.to_string());
}
stream_info.clone()
});
if let Some(stream_info) = existing_stream_info { stream_info } else {
let country = {
let geoip = self.geo_ip.load();
if let Some(geoip_db) = (*geoip).as_ref() {
geoip_db.lookup(&strip_port(&fingerprint.client_ip))
} else {
None
}
};
let stream_info = StreamInfo::new(
username,
&fingerprint.addr,
&fingerprint.client_ip,
provider,
stream_channel,
2025-11-19 23:00:25 -06:00
user_agent_string,
country,
2025-11-19 23:00:25 -06:00
session_token,
);
let total_active = user_connections.key_by_addr.len();
if let Some(connection_data) = user_connections.by_key.get_mut(username) {
connection_data.connections += 1;
connection_data.streams.push(stream_info.clone());
Self::log_connection_added(username, &fingerprint.addr, connection_data, total_active);
}
stream_info
}
};
2025-04-13 16:02:55 +02:00
2025-10-11 16:28:07 +02:00
self.log_active_user().await;
2025-04-13 16:02:55 +02:00
2025-11-10 01:04:13 +01:00
Some(stream_info)
2025-02-06 20:31:51 +01:00
}
2025-07-19 15:32:30 +02:00
fn is_log_user_enabled(&self) -> bool {
2025-06-24 12:31:38 +02:00
self.log_active_user.load(Ordering::Relaxed)
2025-04-13 16:02:55 +02:00
}
2025-11-04 18:01:44 +01:00
fn new_user_session(session_token: &str, virtual_id: u32, provider: &str, stream_url: &str, addr: &SocketAddr,
connection_permission: UserConnectionPermission) -> UserSession {
2025-04-30 11:04:01 +02:00
UserSession {
2025-06-05 17:51:03 +02:00
token: session_token.to_string(),
2025-04-30 11:04:01 +02:00
virtual_id,
2026-01-20 10:09:58 +01:00
provider: provider.intern(),
stream_url: stream_url.intern(),
2025-11-04 21:46:44 +01:00
addr: *addr,
2025-04-30 11:04:01 +02:00
ts: current_time_secs(),
permission: connection_permission,
}
}
#[allow(clippy::too_many_arguments)]
2025-07-27 20:47:35 +02:00
pub async fn create_user_session(&self, user: &ProxyUserCredentials, session_token: &str, virtual_id: u32,
2025-11-04 18:01:44 +01:00
provider: &str, stream_url: &str, addr: &SocketAddr,
2025-10-11 16:28:07 +02:00
connection_permission: UserConnectionPermission) -> String {
self.gc();
2025-07-27 20:47:35 +02:00
let username = user.username.clone();
2025-11-05 11:50:05 +01:00
let mut user_connections = self.connections.write().await;
let connection_data = user_connections.by_key.entry(username.clone()).or_insert_with(|| {
2025-12-15 21:10:45 +01:00
debug_if_enabled!("Creating first session for user {username} {}", sanitize_sensitive_info(stream_url));
2025-07-19 15:32:30 +02:00
let mut data = UserConnectionData::new(0, user.max_connections);
let session = Self::new_user_session(session_token, virtual_id, provider, stream_url, addr, connection_permission);
2025-07-19 15:32:30 +02:00
data.add_session(session);
data
});
// If a session exists, update it
for session in &mut connection_data.sessions {
if session.token == session_token {
session.ts = current_time_secs();
2026-01-20 10:09:58 +01:00
if &*session.stream_url != stream_url {
session.stream_url = stream_url.intern();
2025-07-19 15:32:30 +02:00
}
2026-01-20 10:09:58 +01:00
if &*session.provider != provider {
session.provider = provider.intern();
2025-07-19 15:32:30 +02:00
}
session.permission = connection_permission;
2025-12-15 21:10:45 +01:00
debug_if_enabled!("Using session for user {} with url: {}", user.username, sanitize_sensitive_info(stream_url));
2025-07-19 15:32:30 +02:00
return session.token.clone();
}
2025-04-28 19:52:59 +02:00
}
2025-07-19 15:32:30 +02:00
2025-10-24 18:36:13 +02:00
// If no session exists, create one
2025-12-15 21:10:45 +01:00
debug_if_enabled!("Creating session for user {} with url: {}",
2025-11-18 21:01:42 +01:00
user.username, sanitize_sensitive_info(stream_url));
2025-07-19 15:32:30 +02:00
let session = Self::new_user_session(session_token, virtual_id, provider, stream_url, addr, connection_permission);
let token = session.token.clone();
connection_data.add_session(session);
token
}
2025-11-04 18:01:44 +01:00
pub async fn update_session_addr(&self, username: &str, token: &str, addr: &SocketAddr) {
2025-11-05 11:50:05 +01:00
let mut user_connections = self.connections.write().await;
if let Some(connection_data) = user_connections.by_key.get_mut(username) {
if let Some(session) = connection_data.sessions.iter_mut().find(|s| s.token == token) {
let previous_addr = session.addr;
session.addr = *addr;
for stream in &mut connection_data.streams {
if stream.addr == previous_addr {
stream.addr = *addr;
2025-11-04 22:56:27 +01:00
}
2025-10-11 17:07:39 +02:00
}
2025-12-15 17:54:19 +01:00
debug_if_enabled!("Updated session {token} for {username} address {} -> {}",
sanitize_sensitive_info(&previous_addr.to_string()),
sanitize_sensitive_info(&addr.to_string()));
2025-11-04 22:56:27 +01:00
}
}
}
2025-10-11 16:28:07 +02:00
pub async fn get_and_update_user_session(&self, username: &str, token: &str) -> Option<UserSession> {
2025-07-27 20:47:35 +02:00
self.update_user_session(username, token).await
2025-04-28 19:52:59 +02:00
}
2025-07-27 20:47:35 +02:00
async fn update_user_session(&self, username: &str, token: &str) -> Option<UserSession> {
2025-11-05 11:50:05 +01:00
let mut user_connections = self.connections.write().await;
let connection_data = user_connections.by_key.get_mut(username)?;
let now = current_time_secs();
connection_data.ts = now;
let session_index = connection_data.sessions.iter().position(|s| s.token == token)?;
connection_data.sessions[session_index].ts = now;
if connection_data.max_connections > 0
&& connection_data.sessions[session_index].permission == UserConnectionPermission::GracePeriod
{
let new_permission = self.check_connection_permission(username, connection_data);
connection_data.sessions[session_index].permission = new_permission;
2025-04-28 19:52:59 +02:00
}
2025-11-05 11:50:05 +01:00
Some(connection_data.sessions[session_index].clone())
2025-04-28 19:52:59 +02:00
}
2025-10-24 18:36:13 +02:00
pub async fn active_streams(&self) -> Vec<StreamInfo> {
2025-11-05 11:50:05 +01:00
let user_connections = self.connections.read().await;
2025-10-24 18:36:13 +02:00
let mut streams = Vec::new();
2025-11-05 12:07:02 +01:00
for connection_data in user_connections.by_key.values() {
2025-10-24 18:36:13 +02:00
for stream in &connection_data.streams {
streams.push(stream.clone());
}
}
streams
}
fn log_connection_added(
username: &str,
addr: &SocketAddr,
connection_data: &UserConnectionData,
total_active_sockets: usize,
) {
if log::log_enabled!(log::Level::Debug) {
let active_for_user = connection_data.connections;
if connection_data.max_connections > 0 && active_for_user > connection_data.max_connections {
let recent_sockets = connection_data
.streams
.iter()
.rev()
.take(3)
.map(|stream| stream.addr.to_string())
.collect::<Vec<_>>()
.join(", ");
let recent_sockets = if recent_sockets.is_empty() {
String::from("n/a")
} else {
recent_sockets
};
let unique_clients = connection_data
.streams
.iter()
.map(|stream| &stream.client_ip)
.collect::<HashSet<_>>()
.len();
debug!(
"User {username} exceeded configured max connections ({}/{}). Unique clients: {}, recent sockets [{}]",
active_for_user,
connection_data.max_connections,
unique_clients,
recent_sockets
);
} else {
2025-12-15 17:54:19 +01:00
debug_if_enabled!(
"Added new connection for {username} at {} (active user connections={active_for_user}, total connections={total_active_sockets})",
sanitize_sensitive_info(&addr.to_string())
);
}
}
}
2025-12-12 20:32:46 +01:00
pub async fn is_user_blocked_for_stream(&self, username: &str, virtual_id: VirtualId) -> bool {
let connections = self.connections.read().await;
let now = current_time_secs();
matches!(connections.kicked.get(username), Some((expires_at, vid)) if *vid == virtual_id && *expires_at > now)
}
pub async fn block_user_for_stream(&self, addr: &SocketAddr, virtual_id: VirtualId, blocked_secs: u64) {
let block_for_secs = blocked_secs.clamp(0, 86_400); // max 1 day;
if block_for_secs > 0 {
let mut connections = self.connections.write().await;
let now = current_time_secs();
connections.kicked.retain(|_, (expires_at, _)| *expires_at > now);
if let Some(username) = connections.key_by_addr.get(addr).cloned() {
let expires_at = now + block_for_secs;
connections.kicked.insert(username, (expires_at, virtual_id));
}
2025-12-12 20:32:46 +01:00
}
}
pub async fn get_username_for_addr(&self, addr: &SocketAddr) -> Option<String> {
2025-12-13 11:32:55 +01:00
self.connections.read().await.key_by_addr.get(addr).cloned()
}
2025-10-11 16:28:07 +02:00
fn gc(&self) {
2025-04-30 11:04:01 +02:00
if let Some(gc_ts) = &self.gc_ts {
2025-06-09 13:23:27 +02:00
let ts = gc_ts.load(Ordering::Acquire);
2025-05-06 12:19:37 +02:00
let now = current_time_secs();
2025-07-27 20:47:35 +02:00
if now.saturating_sub(ts) > USER_GC_TTL
&& gc_ts
.compare_exchange(ts, now, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
2025-11-05 11:50:05 +01:00
if let Ok(mut user_connections) = self.connections.try_write() {
2025-12-12 21:25:18 +01:00
user_connections.kicked.retain(|_, (expires_at, _)| *expires_at > now);
user_connections
.by_key
.retain(|_k, v| now.saturating_sub(v.ts) < USER_CON_TTL && v.connections > 0);
for connection_data in user_connections.by_key.values_mut() {
connection_data.sessions.retain(|s| now.saturating_sub(s.ts) < USER_CON_TTL);
2025-10-11 16:28:07 +02:00
}
} else {
// Lock contention: release the GC claim so a subsequent caller can retry immediately.
let _ = gc_ts.compare_exchange(now, ts, Ordering::AcqRel, Ordering::Relaxed);
2025-04-30 11:04:01 +02:00
}
}
}
}
}
//
// mod tests {
// use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
// use std::time::Instant;
// use std::thread;
//
// fn benchmark(ordering: Ordering, iterations: usize) -> u128 {
// let counter = Arc::new(AtomicUsize::new(0));
// let start = Instant::now();
//
// let handles: Vec<_> = (0..32)
// .map(|_| {
// let counter_ref = Arc::clone(&counter);
// thread::spawn(move || {
// for _ in 0..iterations {
// counter_ref.fetch_add(1, ordering);
// }
// })
// })
// .collect();
//
2025-04-28 20:28:33 +02:00
// for handle in handles {
// handle.join().unwrap();
// }
//
// let duration = start.elapsed();
// duration.as_millis()
// }
//
// #[test]
// fn test_ordering() {
// let iterations = 1_000_000;
//
// let time_acqrel = benchmark(Ordering::SeqCst, iterations);
// println!("AcqRel: {} ms", time_acqrel);
//
// let time_seqcst = benchmark(Ordering::SeqCst, iterations);
// println!("SeqCst: {} ms", time_seqcst);
// }
//
// }