using System.Collections.Concurrent;
using AttendanceHub.Sync.Configuration;
using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Persistence;
using AttendanceHub.Sync.Workers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Oversight;
///
/// Multi-device orchestration: one (= one dual-session DeviceWorker with
/// its own STA owners, gates, watermark and ingress) per device, all running concurrently and
/// independently. The device set can change at runtime (dynamic list): new devices are started,
/// removed devices are stopped — never affecting the other devices.
/// Device count is NOT hardcoded: it always reflects the resolved device list (Laravel-driven).
///
public sealed class SyncHub : IAsyncDisposable
{
private readonly ConcurrentDictionary _supervisors = new(StringComparer.OrdinalIgnoreCase);
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly Phase1DeviceConfig _base;
private readonly ILoggerFactory _loggerFactory;
private readonly ISyncStore? _store;
private readonly TimeSpan _futureTolerance;
private readonly TimeSpan _ingestRetention;
private readonly ILogger _log;
private int _disposed;
public SyncHub(
Phase1DeviceConfig baseConfig,
ILoggerFactory? loggerFactory = null,
ISyncStore? store = null,
TimeSpan? persistenceFutureTolerance = null,
TimeSpan? ingestRetention = null)
{
_base = baseConfig;
_loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_log = _loggerFactory.CreateLogger();
_store = store;
_futureTolerance = persistenceFutureTolerance ?? TimeSpan.FromMinutes(5);
_ingestRetention = ingestRetention ?? RetentionPolicy.PunchRetention;
}
public IReadOnlyList DeviceIds => _supervisors.Keys.ToArray();
public IReadOnlyList Supervisors => _supervisors.Values.ToArray();
/// Reconcile the running supervisors with the resolved device list.
/// The number of devices running after the change.
public async Task ApplyAsync(IReadOnlyList devices, CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var added = 0;
var removed = 0;
foreach (var device in devices)
{
if (_supervisors.ContainsKey(device.DeviceId))
continue;
var cfg = _base with { Device = device };
var supervisor = new Supervisor(cfg, _loggerFactory, _store, _futureTolerance, _ingestRetention);
await supervisor.StartAsync(cancellationToken).ConfigureAwait(false);
_supervisors[device.DeviceId] = supervisor;
added++;
_log.LogInformation(
"DEVICE_SUPERVISOR_STARTED device={Device} ip={Ip}:{Port} machineNumber={Mn} commKey={Ck} total={T}",
device.DeviceId, device.Ip, device.Port, device.MachineNumber, device.CommKey, _supervisors.Count);
}
var expected = devices.Select(d => d.DeviceId)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var key in _supervisors.Keys.ToList())
{
if (expected.Contains(key))
continue;
if (!_supervisors.TryRemove(key, out var supervisor))
continue;
try
{
await supervisor.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogWarning(ex, "DEVICE_SUPERVISOR_STOP_FAILED device={Device}", key);
}
removed++;
_log.LogWarning("DEVICE_SUPERVISOR_STOPPED device={Device} reason=removed_from_device_list", key);
}
if (added > 0 || removed > 0)
_log.LogInformation("DEVICE_LIST_APPLIED total={T} added={A} removed={R}", _supervisors.Count, added, removed);
return _supervisors.Count;
}
finally
{
_gate.Release();
}
}
/// Run an action against every worker (operator commands).
public async Task ForEachAsync(Func action, CancellationToken cancellationToken = default)
{
foreach (var supervisor in Supervisors)
{
cancellationToken.ThrowIfCancellationRequested();
await action(supervisor).ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
await _gate.WaitAsync().ConfigureAwait(false);
try
{
foreach (var key in _supervisors.Keys.ToList())
{
if (!_supervisors.TryRemove(key, out var supervisor))
continue;
try
{
await supervisor.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogWarning(ex, "DEVICE_SUPERVISOR_DISPOSE_FAILED device={Device}", key);
}
}
}
finally
{
_gate.Release();
}
_gate.Dispose();
}
}