using AttendanceHub.Sync.Com;
using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Ingestion;
using AttendanceHub.Sync.Persistence;
using AttendanceHub.Sync.Workers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Oversight;
///
/// Supervises exactly one Production V2 DeviceWorker.
/// Creates the dual-session (LIVE + READ, independent owner/RCW/generation)
/// and optionally wires persistence: LivePunchIngress (LIVE) + ReconciliationPersistence (READ),
/// both funnelling into the same ISyncStore canonical-identity upsert path.
/// Per-device recovery only — never restarts the process for one device fault.
///
public sealed class Supervisor : IAsyncDisposable
{
private readonly Phase1DeviceConfig _config;
private readonly ILogger _log;
private readonly ILoggerFactory _loggerFactory;
private readonly ISyncStore? _store;
private readonly TimeSpan _futureTolerance;
private readonly TimeSpan _ingestRetention;
private DeviceWorker? _worker;
private LivePunchIngress? _ingress;
private int _recreateCount;
public string WorkerId => _config.Device.DeviceId;
public DeviceWorker? Worker => _worker;
public int SessionRecreateCount => _recreateCount;
///
/// Endpoint identity, NOT the worker id. These are deliberately distinct: the local id is
/// overridable per device (172.24.30.9 is supervised as "phase1-test-01"), while Laravel
/// identifies a device by devices.ip+port. Anything reported to Laravel must use these two —
/// reporting the worker id instead would silently resolve to "device not found" for exactly
/// the overridden device and nowhere else.
///
public string Ip => _config.Device.Ip;
public int Port => _config.Device.Port;
public Supervisor(
Phase1DeviceConfig config,
ILoggerFactory? loggerFactory = null,
ISyncStore? store = null,
TimeSpan? persistenceFutureTolerance = null,
TimeSpan? ingestRetention = null)
{
_config = config;
_loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_log = _loggerFactory.CreateLogger();
_store = store;
_futureTolerance = persistenceFutureTolerance ?? TimeSpan.FromMinutes(5);
_ingestRetention = ingestRetention ?? RetentionPolicy.PunchRetention;
}
public async Task StartAsync(CancellationToken cancellationToken = default)
{
_log.LogInformation(
"SUPERVISOR_START worker={Worker} device={Ip}:{Port} machineNumber={Mn} expectedSdk={Sdk} persistence={P}",
WorkerId, _config.Device.Ip, _config.Device.Port, _config.Device.MachineNumber, _config.Sdk.ExpectedSdkVersion,
_store is null ? "off" : "on");
// Production V2 dual-session runtime: independent LIVE and READ sessions/owners/RCWs/generations.
var runtime = DeviceRuntime.Create(_config, _loggerFactory);
ReconciliationPersistence? recon = null;
if (_store is not null)
{
// LIVE path: OnAttTransactionEx -> LivePunchIngress (enqueue-only) -> existing store/outbox.
_ingress = new LivePunchIngress(
_store, WorkerId, _futureTolerance, 2048,
_loggerFactory.CreateLogger("LiveIngress:" + WorkerId), _ingestRetention);
// READ path: full-buffer read -> same store via idempotent batch upsert + watermark.
recon = new ReconciliationPersistence(
_store, _futureTolerance, _loggerFactory.CreateLogger("Recon:" + WorkerId), _ingestRetention);
_log.LogInformation(
"SUPERVISOR_PERSISTENCE_WIRED worker={Worker} futureToleranceMin={Tol} ingestRetentionDays={Ret} canonicalIdentity=device_id|personnel_code|punch_time_device_local",
WorkerId, _futureTolerance.TotalMinutes, _ingestRetention.TotalDays);
}
_worker = new DeviceWorker(
runtime.LiveSession,
runtime.ReadSession,
_config,
_loggerFactory.CreateLogger(),
recon,
_ingress);
await _worker.StartAsync().ConfigureAwait(false);
}
public async Task ForceRecreateAsync()
{
if (_worker is null) return;
await _worker.RecreateAsync().ConfigureAwait(false);
_recreateCount++;
_log.LogInformation("SUPERVISOR_RECREATE worker={Worker} count={N} scope=BOTH reason=operator_forced", WorkerId, _recreateCount);
}
public async ValueTask DisposeAsync()
{
if (_worker is not null)
await _worker.DisposeAsync().ConfigureAwait(false);
if (_ingress is not null)
{
// Flush remaining LIVE enqueues after the worker stopped producing events.
await _ingress.DisposeAsync().ConfigureAwait(false);
_ingress = null;
}
}
}