using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Hubs;
///
/// Thread-safe in-memory implementation of .
/// Keyed by (DriverInstanceId, HostName); last write wins.
///
public sealed class InMemoryDriverResilienceStatusStore : IDriverResilienceStatusStore
{
private readonly ConcurrentDictionary<(string Instance, string Host), DriverResilienceStatusChanged> _byPair = new();
private readonly ILogger? _logger;
private readonly FailureLogThrottle _failureLog = new();
/// Creates the store.
/// Optional logger for a subscriber that throws during a raise.
public InMemoryDriverResilienceStatusStore(ILogger? logger = null)
=> _logger = logger;
/// Raised after every with the just-stored snapshot.
public event Action? SnapshotChanged;
///
public void Upsert(DriverResilienceStatusChanged snapshot)
{
_byPair[(snapshot.DriverInstanceId, snapshot.HostName)] = snapshot;
// Capture-then-invoke so a concurrent unsubscribe can't null the delegate mid-raise; one
// subscriber at a time so a throwing one cannot starve the rest (or escape onto the bridge actor).
SafeMulticast.Invoke(SnapshotChanged, snapshot,
ex => _logger?.Log(_failureLog.NextLevel(), ex, "Driver resilience subscriber threw for {DriverInstanceId}", snapshot.DriverInstanceId));
}
///
public int EvictUnconfiguredStale(IReadOnlySet configuredInstanceIds, DateTime olderThanUtc)
{
var removed = 0;
foreach (var (key, snapshot) in _byPair)
{
if (configuredInstanceIds.Contains(key.Instance) || snapshot.PublishedUtc >= olderThanUtc) continue;
// Remove only the exact snapshot inspected: a fresh publish that raced in is kept.
if (_byPair.TryRemove(new KeyValuePair<(string Instance, string Host), DriverResilienceStatusChanged>(key, snapshot))) removed++;
}
return removed;
}
///
public IReadOnlyList GetForInstance(string driverInstanceId) =>
_byPair.Values
.Where(s => string.Equals(s.DriverInstanceId, driverInstanceId, StringComparison.Ordinal))
.ToList();
///
public IReadOnlyCollection GetAll() => _byPair.Values.ToArray();
}