using System.Threading.Channels;
using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Persistence;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Ingestion;
///
/// Lightweight realtime ingress: COM callback only enqueues; this class persists off the COM thread.
/// NEVER writes SQLite inside the COM callback.
///
public sealed class LivePunchIngress : IAsyncDisposable
{
private readonly ISyncStore _store;
private readonly string _deviceId;
private readonly TimeSpan _futureTolerance;
private readonly TimeSpan _ingestRetention;
private readonly Channel _channel;
private readonly ILogger _log;
private readonly CancellationTokenSource _cts = new();
private readonly Task _pump;
private long _received;
private long _persisted;
private long _duplicates;
private long _rejected;
private long _expired;
public LivePunchIngress(
ISyncStore store,
string deviceId,
TimeSpan futureTolerance,
int capacity = 1024,
ILogger? log = null,
TimeSpan? ingestRetention = null)
{
_store = store;
_deviceId = deviceId;
_futureTolerance = futureTolerance;
_ingestRetention = ingestRetention ?? RetentionPolicy.PunchRetention;
_log = log ?? NullLogger.Instance;
_channel = Channel.CreateBounded(new BoundedChannelOptions(capacity)
{
SingleReader = true,
SingleWriter = false,
FullMode = BoundedChannelFullMode.DropOldest
});
_pump = Task.Run(PumpAsync);
}
public long Received => Interlocked.Read(ref _received);
public long Persisted => Interlocked.Read(ref _persisted);
public long Duplicates => Interlocked.Read(ref _duplicates);
public long Rejected => Interlocked.Read(ref _rejected);
public long Expired => Interlocked.Read(ref _expired);
///
/// Safe to call from COM event handler: normalize + enqueue only. No I/O.
///
public void EnqueueFromCom(RawAttendanceEvent raw, int sessionGeneration)
{
try
{
var punch = PunchNormalizer.FromRaw(
raw with { Generation = sessionGeneration },
_deviceId,
PunchSource.Realtime,
DateTimeOffset.UtcNow,
_futureTolerance,
_ingestRetention);
Interlocked.Increment(ref _received);
if (!_channel.Writer.TryWrite(punch))
_log.LogWarning("LIVE_INGRESS_DROP device={Device} pin={Pin}", _deviceId, punch.PersonnelCode);
}
catch (Exception ex)
{
// Callback must not throw into COM.
_log.LogError(ex, "LIVE_INGRESS_ENQUEUE_FAILURE device={Device}", _deviceId);
}
}
private async Task PumpAsync()
{
var reader = _channel.Reader;
try
{
while (await reader.WaitToReadAsync(_cts.Token).ConfigureAwait(false))
{
while (reader.TryRead(out var punch))
{
try
{
var swWrite = System.Diagnostics.Stopwatch.StartNew();
var result = await _store.UpsertPunchAsync(punch, _cts.Token).ConfigureAwait(false);
swWrite.Stop();
// Service-quality telemetry. FirstSeenAt is stamped INSIDE the COM callback
// (LivePunchIngress.EnqueueFromCom), so (write time - FirstSeenAt) is exactly
// the callback -> durable-SQLite latency, which is the only number that can
// answer "is the live path actually live?". Without it the ingress queue and
// the SQLite upsert cost are invisible, and any latency claim has to be
// inferred from unrelated timestamps (which produced a wrong 12-34s claim
// that was really per-device clock skew).
_log.LogInformation(
"INGRESS_WRITE device={Device} src={Src} pin={Pin} punch={Punch} firstSeenAt={FS} persistMs={Ms} kind={Kind} queued={Q}",
_deviceId, punch.Source, punch.PersonnelCode, punch.PunchTime,
punch.FirstSeenAt, swWrite.ElapsedMilliseconds, result.Kind,
_channel.Reader.Count);
switch (result.Kind)
{
case PunchUpsertKind.Inserted:
Interlocked.Increment(ref _persisted);
break;
case PunchUpsertKind.Duplicate:
Interlocked.Increment(ref _duplicates);
break;
case PunchUpsertKind.Expired:
// Older than ingest retention — intentionally dropped, not an error.
Interlocked.Increment(ref _expired);
break;
default:
Interlocked.Increment(ref _rejected);
_log.LogWarning("LIVE_INGRESS_REJECTED device={Device} reason={R}", _deviceId, result.Reason);
break;
}
}
catch (Exception ex)
{
_log.LogError(ex, "LIVE_INGRESS_PERSIST_FAILURE device={Device}", _deviceId);
}
}
}
}
catch (OperationCanceledException)
{
// shutdown
}
}
/// Drain pending queue (best effort) before dispose.
public async Task FlushAsync(TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (_channel.Reader.Count == 0 && Received == Persisted + Duplicates + Rejected)
return;
await Task.Delay(25).ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
_channel.Writer.TryComplete();
await _cts.CancelAsync().ConfigureAwait(false);
try { await _pump.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); }
catch { /* best effort */ }
_cts.Dispose();
}
}