using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Server.Sessions;
///
/// Thread-safe registry of active gateway sessions.
///
public sealed class SessionRegistry : ISessionRegistry
{
private readonly ConcurrentDictionary _sessions = new(StringComparer.Ordinal);
///
/// Gets the total count of sessions in the registry.
///
public int Count => _sessions.Count;
///
/// Gets the count of non-closed sessions.
///
public int ActiveCount => _sessions.Values.Count(session => session.State is not SessionState.Closed);
///
/// Adds a session to the registry.
///
/// Gateway session to add.
public bool TryAdd(GatewaySession session)
{
ArgumentNullException.ThrowIfNull(session);
return _sessions.TryAdd(session.SessionId, session);
}
///
/// Retrieves a session by identifier.
///
/// Identifier of the session.
/// The retrieved session if found.
public bool TryGet(
string sessionId,
[MaybeNullWhen(false)] out GatewaySession session)
{
return _sessions.TryGetValue(sessionId, out session);
}
///
/// Removes a session from the registry by identifier.
///
/// Identifier of the session.
/// The removed session if found.
public bool TryRemove(
string sessionId,
[MaybeNullWhen(false)] out GatewaySession session)
{
return _sessions.TryRemove(sessionId, out session);
}
///
/// Returns a snapshot of all sessions in the registry.
///
public IReadOnlyCollection Snapshot()
{
return _sessions.Values.ToArray();
}
}