using System.Collections.Concurrent; using System.Threading.Channels; using ZKTecoSyncService.Models; using ZKTecoSyncService.Protocol; namespace ZKTecoSyncService.Services; public class DeviceConnectionService : IDisposable { private readonly LaravelApiService _apiService; private readonly OfflineBufferService _bufferService; private readonly ConcurrentDictionary _connections = new(); private readonly ILogger _logger; private readonly FileLogger? _fileLogger; private readonly int _pollingInterval; private readonly int _maxRetryAttempts; private readonly int _offlineBufferSize; private readonly int _connectTimeoutMs; private readonly int _readTimeoutMs; private readonly int _watchdogReadStaleMinutes; private readonly ProtocolLogger? _protocolLogger; private readonly DeviceCursorService? _cursorService; private readonly DeviceTimeNormalizer _deviceTimeNormalizer; private readonly bool _pilotMode; private readonly int _autoRestartThreshold; private readonly HashSet _pilotDeviceIps; private readonly ConcurrentDictionary _deviceTasks = new(); private CancellationTokenSource? _cts; public DeviceConnectionService(LaravelApiService apiService, OfflineBufferService bufferService, ILogger logger, FileLogger? fileLogger = null, ProtocolLogger? protocolLogger = null, DeviceCursorService? cursorService = null, DeviceTimeNormalizer? deviceTimeNormalizer = null, int pollingIntervalSeconds = 30, int maxRetryAttempts = 3, int offlineBufferSize = 10000, int connectTimeoutMs = 10000, int readTimeoutMs = 15000, int watchdogReadStaleMinutes = 5, bool pilotMode = false, string[]? pilotDeviceIps = null, int autoRestartThreshold = 50) { _apiService = apiService; _bufferService = bufferService; _logger = logger; _fileLogger = fileLogger; _protocolLogger = protocolLogger; _cursorService = cursorService; _deviceTimeNormalizer = deviceTimeNormalizer ?? new DeviceTimeNormalizer("Local", null); _pilotMode = pilotMode; _autoRestartThreshold = autoRestartThreshold; _pilotDeviceIps = new HashSet(pilotDeviceIps ?? Array.Empty(), StringComparer.OrdinalIgnoreCase); _pollingInterval = pollingIntervalSeconds; _maxRetryAttempts = maxRetryAttempts; _offlineBufferSize = offlineBufferSize; _connectTimeoutMs = connectTimeoutMs; _readTimeoutMs = readTimeoutMs; _watchdogReadStaleMinutes = watchdogReadStaleMinutes; } public async Task StartAsync(CancellationToken ct) { _cts = CancellationTokenSource.CreateLinkedTokenSource(ct); var allDevices = await _apiService.GetDevicesAsync(); if (!allDevices.Any()) { _logger.LogWarning("No devices found"); return; } var devices = FilterDevicesForPilot(allDevices); _logger.LogInformation("Starting {Count} devices (pilot={Pilot}, total from API={Total})", devices.Count, _pilotMode, allDevices.Count); // Stagger device startups to avoid API/network burst var deviceIndex = 0; foreach (var device in devices) { var key = $"{device.Ip}:{device.Port}"; if (!_connections.ContainsKey(key)) { var conn = new DeviceConnection(device, _apiService, _bufferService, _logger, _fileLogger, _protocolLogger, _cursorService, _deviceTimeNormalizer, _pollingInterval, _maxRetryAttempts, _offlineBufferSize, _connectTimeoutMs, _readTimeoutMs, _watchdogReadStaleMinutes, _autoRestartThreshold); _connections[key] = conn; var delayMs = deviceIndex * 200; _deviceTasks[key] = Task.Run(async () => { try { if (delayMs > 0) await Task.Delay(delayMs, _cts.Token); await conn.StartAsync(_cts.Token); } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Connection task crashed", device.Ip); } }, _cts.Token); deviceIndex++; } } } public async Task RefreshDevicesAsync() { var devices = await _apiService.GetDevicesAsync(); var currentKeys = _connections.Keys.ToHashSet(); var newKeys = devices.Select(d => $"{d.Ip}:{d.Port}").ToHashSet(); foreach (var key in currentKeys.Except(newKeys)) { if (_connections.TryRemove(key, out var c)) { c.Stop(); } _deviceTasks.TryRemove(key, out _); } // Check for faulted device tasks and restart them (self-healing) foreach (var key in currentKeys.Intersect(newKeys)) { if (_deviceTasks.TryGetValue(key, out var task) && task.IsFaulted) { _logger.LogWarning("[{Key}] Device task is faulted — restarting", key); _deviceTasks.TryRemove(key, out _); _connections.TryRemove(key, out var oldConn); oldConn?.Dispose(); var device = devices.First(d => $"{d.Ip}:{d.Port}" == key); var conn = new DeviceConnection(device, _apiService, _bufferService, _logger, _fileLogger, _protocolLogger, _cursorService, _deviceTimeNormalizer, _pollingInterval, _maxRetryAttempts, _offlineBufferSize, _connectTimeoutMs, _readTimeoutMs, _watchdogReadStaleMinutes, _autoRestartThreshold); _connections[key] = conn; var token = _cts?.Token ?? CancellationToken.None; _deviceTasks[key] = Task.Run(async () => { try { await conn.StartAsync(token); } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Connection task crashed", device.Ip); } }, token); } } foreach (var device in devices.Where(d => !currentKeys.Contains($"{d.Ip}:{d.Port}"))) { var key = $"{device.Ip}:{device.Port}"; var conn = new DeviceConnection(device, _apiService, _bufferService, _logger, _fileLogger, _protocolLogger, _cursorService, _deviceTimeNormalizer, _pollingInterval, _maxRetryAttempts, _offlineBufferSize, _connectTimeoutMs, _readTimeoutMs, _watchdogReadStaleMinutes, _autoRestartThreshold); _connections[key] = conn; var token = _cts?.Token ?? CancellationToken.None; _deviceTasks[key] = Task.Run(async () => { try { await conn.StartAsync(token); } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Connection task crashed", device.Ip); } }, token); } } public int GetActiveConnectionCount() => _connections.Values.Count(c => c.IsOnline); private List FilterDevicesForPilot(List devices) { if (!_pilotMode || _pilotDeviceIps.Count == 0) return devices; return devices.Where(d => _pilotDeviceIps.Contains(d.Ip)).ToList(); } public async Task StopAsync(CancellationToken ct = default) { _cts?.Cancel(); // Stop all device loops foreach (var c in _connections.Values) c.Stop(); // Await all tasks with timeout to observe exceptions var allTasks = _deviceTasks.Values.ToArray(); if (allTasks.Length > 0) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(10)); try { await Task.WhenAll(allTasks); } catch (OperationCanceledException) { } catch { /* exceptions observed in Task.Run */ } } foreach (var c in _connections.Values) c.Dispose(); _connections.Clear(); _deviceTasks.Clear(); } public void Stop() { StopAsync().GetAwaiter().GetResult(); } public void Dispose() { Stop(); } } public class DeviceConnection : IDisposable { private readonly DeviceConfig _device; private readonly LaravelApiService _apiService; private readonly OfflineBufferService _bufferService; private readonly ILogger _logger; private readonly FileLogger? _fileLogger; private readonly ProtocolLogger? _protocolLogger; private readonly DeviceCursorService? _cursorService; private readonly DeviceTimeNormalizer _deviceTimeNormalizer; private readonly int _pollingInterval; private readonly int _maxRetryAttempts; private readonly int _offlineBufferSize; private readonly int _connectTimeoutMs; private readonly int _readTimeoutMs; private readonly int _watchdogReadStaleMinutes; private readonly int _autoRestartThreshold; private static readonly int ResendWindowHours = 72; private static readonly int FullResyncMinutes = 3; private const int LogCountTolerance = 0; private readonly DateTime _syncCutoff; private ZKTecoProtocol? _protocol; private CancellationTokenSource? _cts; private volatile bool _isOnline; private int _retryCount; private bool _manualRecoveryLogged; private DateTime? _lastSentMaxPunch; private DeviceStateMachine? _state; private int _lastKnownLogCount = -1; private long _consecutiveParseFailures; private int _totalDroppedCapacityFull; private DeviceSyncCursor? _cursor; private bool _stateSeeded; private DateTime _lastStateRefreshUtc = DateTime.MinValue; private static readonly int StateRefreshMinutes = 5; private string? _lastError; private DateTime? _lastSuccessfulSync; private string? _lastPunchTime; // ─── Read health telemetry ──────────────────────────────────────────── private DateTime? _lastSuccessfulReadAt; private DateTime? _lastSuccessfulReadPunchTime; private long _readSuccessCount; private long _readFailureCount; private long _consecutiveReadFailures; private string? _lastReadError; private DateTime? _lastReadErrorAt; // ─── Connection telemetry ───────────────────────────────────────────── private long _connectionAttempts; private long _successfulConnections; private long _failedConnections; private long _reconnectCount; private DateTime? _lastSuccessfulConnection; private DateTime? _lastConnectionFailure; // ─── Watchdog ───────────────────────────────────────────────────────── private DateTime _lastWatchdogCheckUtc = DateTime.MinValue; private bool _initialReadPending = true; // skip watchdog until first successful read private readonly Channel _liveQueue = Channel.CreateBounded(new BoundedChannelOptions(10000) { FullMode = BoundedChannelFullMode.Wait, SingleReader = false, SingleWriter = false }); private readonly Channel _overflowQueue = Channel.CreateBounded(new BoundedChannelOptions(1000) { FullMode = BoundedChannelFullMode.Wait, SingleReader = false, SingleWriter = false }); private volatile bool _eventsActive; // ─── Overflow telemetry (Interlocked — no I/O in COM callback) ──────── private long _overflowEnqueued; private long _overflowDropped; private long _primaryWriteCount; // ─── Per-device read lock: prevents overlapping reads on same device ── private readonly SemaphoreSlim _deviceReadLock = new(1, 1); // ─── Background drain/telemetry tasks (observed on shutdown) ───────── private Task? _liveDrainTask; private Task? _overflowDrainTask; private Task? _uploadTask; private Task? _telemetryTask; // ─── Per-batch crash detection (replaces global ResetStuckSending) ─── private DateTime _lastUploadBatchStartUtc = DateTime.MinValue; private const int UploadBatchStuckSeconds = 120; private int _consecutiveEventFailures; private DateTime _eventCooldownUntil = DateTime.MinValue; // ─── Global read lock: max 5 concurrent bulk reads across all devices ── private static readonly SemaphoreSlim _globalReadLock = new(5, 5); private static readonly TimeSpan[] _backoffSchedule = [ TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(300), TimeSpan.FromSeconds(300) ]; public bool IsOnline => _isOnline; public DeviceConnection(DeviceConfig device, LaravelApiService apiService, OfflineBufferService bufferService, ILogger logger, FileLogger? fileLogger, ProtocolLogger? protocolLogger, DeviceCursorService? cursorService, DeviceTimeNormalizer deviceTimeNormalizer, int pollingIntervalSeconds, int maxRetryAttempts, int offlineBufferSize, int connectTimeoutMs, int readTimeoutMs, int watchdogReadStaleMinutes, int autoRestartThreshold = 50, DateTime? syncCutoff = null) { _device = device; _apiService = apiService; _bufferService = bufferService; _logger = logger; _fileLogger = fileLogger; _protocolLogger = protocolLogger; _cursorService = cursorService; _deviceTimeNormalizer = deviceTimeNormalizer; _pollingInterval = pollingIntervalSeconds; _maxRetryAttempts = maxRetryAttempts; _offlineBufferSize = offlineBufferSize; _connectTimeoutMs = connectTimeoutMs; _readTimeoutMs = readTimeoutMs; _watchdogReadStaleMinutes = watchdogReadStaleMinutes; _autoRestartThreshold = autoRestartThreshold; _syncCutoff = syncCutoff ?? new DateTime(2026, 7, 23, 0, 0, 0, DateTimeKind.Utc); } public async Task StartAsync(CancellationToken ct) { _cts = CancellationTokenSource.CreateLinkedTokenSource(ct); _state = new DeviceStateMachine(_device.Ip, _device.Port, msg => LogEvent("STATE", msg)); _state.TransitionTo(DeviceState.Disconnected, "service start"); // Load cursor from SQLite — source of truth for resume if (_cursorService != null) { _cursor = await _cursorService.GetOrCreateAsync(_device.Ip, _device.Port); // Restore in-memory state from cursor — not just from server API if (_cursor.LastSeenTimestamp.HasValue) _lastSentMaxPunch = _cursor.LastSeenTimestamp.Value; // Reset watchdog state — start fresh, no stale timestamps from previous session _lastSuccessfulReadAt = null; _initialReadPending = true; LogEvent("CURSOR_LOAD", $"lastSeen={_cursor.LastSeenTimestamp?.ToString("o") ?? "null"} " + $"pulls={_cursor.TotalPulls} events={_cursor.TotalEvents} uploads={_cursor.TotalUploaded}"); } _liveDrainTask = Task.Run(() => DrainLiveQueueAsync(_cts.Token), _cts.Token); _overflowDrainTask = Task.Run(() => DrainOverflowQueueAsync(_cts.Token), _cts.Token); _uploadTask = Task.Run(() => UploadBufferedLogsAsync(_cts.Token), _cts.Token); _telemetryTask = Task.Run(() => TelemetryFlushAsync(_cts.Token), _cts.Token); while (!_cts.Token.IsCancellationRequested) { try { if (_protocol == null || !_protocol.IsConnected) { await ConnectToDeviceAsync(_cts.Token); } // COM SDK stuck — manual recovery required (do NOT auto-restart, do NOT retry) if (_protocol?.IsConnected != true && _retryCount >= _autoRestartThreshold) { if (!_manualRecoveryLogged) { _manualRecoveryLogged = true; LogEvent("MANUAL_RECOVERY_REQUIRED", $"COM SDK retry threshold reached ({_retryCount} failures) for {_device.Ip}:{_device.Port}. " + $"Process PID={Environment.ProcessId}. Device connection halted. Manual intervention required.", LogLevel.Critical); } break; } if (_protocol?.IsConnected == true) { _isOnline = true; _retryCount = 0; _lastError = null; _lastFullReadAtUtc = DateTime.MinValue; // Force read after reconnect if (!_stateSeeded || DateTime.UtcNow - _lastStateRefreshUtc > TimeSpan.FromMinutes(StateRefreshMinutes)) { var serverState = await _apiService.GetSyncStateAsync(_device.Id); if (serverState.HasValue) { var newMaxPunch = serverState.Value.AddHours(-ResendWindowHours); if (_lastSentMaxPunch == null || serverState.Value > _lastSentMaxPunch) { _lastSentMaxPunch = newMaxPunch; _logger.LogInformation("[{Ip}] Refreshed sync state from server: {Time}", _device.Ip, serverState.Value); } } _stateSeeded = true; _lastStateRefreshUtc = DateTime.UtcNow; } // ─── COM Event: detect silently dead listener ───────── // If events are active but no callback received for 10+ minutes, listener is dead if (_eventsActive && _protocol.IsEventListenerRunning && _protocol.LastEventReceivedAt.HasValue && (DateTime.UtcNow - _protocol.LastEventReceivedAt.Value).TotalMinutes > 10) { _eventsActive = false; _consecutiveEventFailures++; LogEvent("LIVE_LISTENER_STALE", $"No events received for {(DateTime.UtcNow - _protocol.LastEventReceivedAt.Value).TotalMinutes:F0} min — listener assumed dead (fail #{_consecutiveEventFailures})", LogLevel.Warning); } // ─── COM Event: "2 consecutive fails = stop" ───────── if (!_eventsActive || !_protocol.IsEventListenerRunning) { // Reset if listener died silently if (_eventsActive && !_protocol.IsEventListenerRunning) { _eventsActive = false; _consecutiveEventFailures++; LogEvent("LIVE_LISTENER_STOPPED", $"Event listener died (fail #{_consecutiveEventFailures})", LogLevel.Warning); } // After 2 consecutive failures, apply cooldown (5 minutes) if (_consecutiveEventFailures >= 2) { if (DateTime.UtcNow < _eventCooldownUntil) continue; // still in cooldown if (_consecutiveEventFailures == 2) { _eventCooldownUntil = DateTime.UtcNow.AddMinutes(15); LogEvent("LIVE_LISTENER_COOLDOWN", "Event listener on 5-minute cooldown after 2 failures — periodic read active", LogLevel.Warning); } else { LogEvent("LIVE_LISTENER_RETRY", $"Retrying event listener after cooldown (fail count: {_consecutiveEventFailures})"); } } else { _protocol.SetEventListenerStoppedCallback(() => { _eventsActive = false; _consecutiveEventFailures++; LogEvent("LIVE_LISTENER_FAILED", $"Event listener terminated (fail #{_consecutiveEventFailures})", LogLevel.Warning); }); _eventsActive = await _protocol.EnableRealTimeEventsAsync(l => { if (_liveQueue.Writer.TryWrite(l)) { Interlocked.Increment(ref _primaryWriteCount); return; } if (_overflowQueue.Writer.TryWrite(l)) { Interlocked.Increment(ref _overflowEnqueued); return; } Interlocked.Increment(ref _overflowDropped); }, _cts.Token); if (_eventsActive) { _consecutiveEventFailures = 0; // Reset on success _state?.TransitionTo(DeviceState.Live, "events registered"); LogEvent("EVENTS_ENABLED", "Real-Time events registered via RegEvent(65535)"); } } } // ─── Watchdog: check if read is stale ──────────────── // Skip during initial read — wait for first successful read before enforcing staleness LogEvent("WATCHDOG_DEBUG", $"initialReadPending={_initialReadPending} lastRead={_lastSuccessfulReadAt?.ToString("o") ?? "null"} threshold={_watchdogReadStaleMinutes}min"); if (_watchdogReadStaleMinutes > 0 && !_initialReadPending && _lastSuccessfulReadAt.HasValue && DateTime.UtcNow - _lastSuccessfulReadAt.Value > TimeSpan.FromMinutes(_watchdogReadStaleMinutes)) { var staleMinutes = (DateTime.UtcNow - _lastSuccessfulReadAt.Value).TotalMinutes; LogEvent("WATCHDOG_TRIGGER", $"read stale for {staleMinutes:F1}min (threshold={_watchdogReadStaleMinutes}min) — forcing reconnect", LogLevel.Warning); _state?.TransitionTo(DeviceState.Reconnecting, $"watchdog: stale {staleMinutes:F0}min"); await _protocol.StopEventListenerAsync(); _protocol?.ResetSession(); _protocol = null; _isOnline = false; _eventsActive = false; _reconnectCount++; await Task.Delay(TimeSpan.FromSeconds(2), _cts.Token); continue; } // Read logs every 3 minutes — NO dependency on GetLogCount bool hasNewLogs = IsFullResyncDue(); // GetLogCount is optional — just for telemetry, NOT for deciding whether to read var logCount = _protocol.GetLogCount(); if (logCount >= 0) { LogEvent("GET_LOG_COUNT_SUCCESS", $"count={logCount}"); if (logCount > _lastKnownLogCount) hasNewLogs = true; _lastKnownLogCount = logCount; } if (logCount >= 0 && !hasNewLogs) _lastKnownLogCount = Math.Max(_lastKnownLogCount, logCount); // ─── Phase 3: READ LOGS (incremental buffering) ── bool readTimedOut = false; bool readSkipped = false; if (hasNewLogs) { if (!_deviceReadLock.Wait(0)) { readSkipped = true; LogEvent("READ_SKIPPED", "Read already in progress on this device — skipping cycle"); } else { try { var readStart = DateTime.UtcNow; LogEvent("READ_ALL_LOGS_START", "ReadGeneralLogData + SSR_GetGeneralLogData (incremental)"); var inserted = 0; var duplicates = 0; var capacityFull = 0; DateTime? lastPunchInBatch = null; await _globalReadLock.WaitAsync(_cts.Token); try { var totalCount = _protocol!.ReadAllLogsIncremental(batch => { // Filter + Buffer each batch as it arrives var filtered = FilterForSend(batch); foreach (var log in filtered) { var bufResult = _bufferService.BufferLog(log); switch (bufResult) { case BufferResult.Inserted: inserted++; break; case BufferResult.Duplicate: duplicates++; break; case BufferResult.CapacityFull: capacityFull++; Interlocked.Increment(ref _totalDroppedCapacityFull); LogEvent("BUFFER_FULL", $"capacity full — record REJECTED: {log.PersonnelCode} @ {log.PunchTime:O}", LogLevel.Warning); break; } if (lastPunchInBatch == null || log.PunchTime > lastPunchInBatch) lastPunchInBatch = log.PunchTime; } }, _cts.Token); } finally { _globalReadLock.Release(); } var readDuration = DateTime.UtcNow - readStart; _lastFullReadAtUtc = DateTime.UtcNow; if (inserted > 0 || duplicates > 0) { _readSuccessCount++; _lastSuccessfulReadAt = DateTime.UtcNow; _initialReadPending = false; // watchdog can now enforce staleness if (lastPunchInBatch.HasValue) _lastSuccessfulReadPunchTime = lastPunchInBatch.Value; _consecutiveReadFailures = 0; _lastReadError = null; LogEvent("READ_ALL_LOGS_SUCCESS", $"count={inserted} inserted, {duplicates} dupes, {capacityFull} capacity_full, duration={readDuration.TotalMilliseconds:F0}ms"); if (_cursorService != null) await _cursorService.UpdateAfterPullAsync(_device.Ip, _device.Port); // NOTE: CleanLogData is handled by UploadBufferedLogsAsync // after ALL records are confirmed uploaded (durable ACK) } else if (_protocol?.IsConnected == false) { readTimedOut = true; _readFailureCount++; _consecutiveReadFailures++; _lastReadError = _protocol?.LastError ?? "ReadAllLogs failed"; _lastReadErrorAt = DateTime.UtcNow; LogEvent("READ_ALL_LOGS_TIMEOUT", $"duration={readDuration.TotalMilliseconds:F0}ms error={_lastReadError} — session invalidated", LogLevel.Warning); } else { LogEvent("READ_ALL_LOGS_EMPTY", $"0 new logs duration={readDuration.TotalMilliseconds:F0}ms"); _lastSuccessfulReadAt = DateTime.UtcNow; _initialReadPending = false; } if (inserted > 0 || duplicates > 0) LogEvent("BUFFER_RESULT", $"inserted={inserted} duplicate={duplicates} capacity_full={capacityFull}"); if (lastPunchInBatch.HasValue) _lastPunchTime = lastPunchInBatch.Value.ToString("yyyy-MM-dd HH:mm:ss"); } finally { _deviceReadLock.Release(); } } } // ─── Phase 4: RECONNECT if session was invalidated by read ── if (readTimedOut) { LogEvent("READ_RECONNECT", "reconnecting after read timeout to send heartbeat"); await ConnectToDeviceAsync(_cts.Token); } // ─── Phase 5: HEARTBEAT (always on valid session) ───────── if (_protocol?.IsConnected == true) { LogEvent("GET_DEVICE_INFO_START", "fetching device info for heartbeat"); var deviceInfo = _protocol.GetDeviceInfo(); if (deviceInfo != null) { LogEvent("GET_DEVICE_INFO_SUCCESS", $"firmware={deviceInfo.FirmwareVersion} users={deviceInfo.UserCount} logs={deviceInfo.LogCount}"); deviceInfo.BufferCount = _bufferService.GetPendingCount(); deviceInfo.OldestBufferedAt = _bufferService.GetOldestPendingAt()?.ToString("yyyy-MM-dd HH:mm:ss"); deviceInfo.DroppedRecords = _bufferService.TotalDroppedUnsynced; deviceInfo.DeadLetterCount = _bufferService.GetDeadLetterCount(); deviceInfo.StaleBufferCount = _bufferService.GetStaleBufferCount(_device.Ip, _device.Port, 30); deviceInfo.LastError = _lastError; deviceInfo.LastSuccessfulSync = _lastSuccessfulSync?.ToString("yyyy-MM-dd HH:mm:ss"); deviceInfo.LastPunchTime = _lastPunchTime; deviceInfo.DeviceState = _state?.CurrentState.ToString(); deviceInfo.ParseFailureCount = _protocol?.ParseFailureCount ?? 0; // Capacity alert: if log count exceeds 80% of estimated capacity if (deviceInfo.LogCount is > 150000) { LogEvent("HIGH_LOG_COUNT", $"Device log count high: {deviceInfo.LogCount} records — investigate capacity", LogLevel.Warning); } // Buffer age alert: if oldest buffered record is older than 30 minutes var oldestBuffered = _bufferService.GetOldestPendingAt(); if (oldestBuffered.HasValue) { var bufferAge = DateTime.UtcNow - oldestBuffered.Value; if (bufferAge.TotalMinutes > 30) { LogEvent("BUFFER_STALE", $"Oldest buffered record is {bufferAge.TotalMinutes:F0} minutes old ({oldestBuffered.Value:O}) — records stuck in queue, possible backend issue", LogLevel.Warning); } } // Read health deviceInfo.LastSuccessfulReadAt = _lastSuccessfulReadAt?.ToString("yyyy-MM-dd HH:mm:ss"); deviceInfo.LastSuccessfulReadPunchTime = _lastSuccessfulReadPunchTime?.ToString("yyyy-MM-dd HH:mm:ss"); deviceInfo.ReadSuccessCount = _readSuccessCount; deviceInfo.ReadFailureCount = _readFailureCount; deviceInfo.ConsecutiveReadFailures = _consecutiveReadFailures; deviceInfo.LastReadError = _lastReadError; deviceInfo.LastReadErrorAt = _lastReadErrorAt?.ToString("yyyy-MM-dd HH:mm:ss"); // Connection deviceInfo.ConnectionAttempts = _connectionAttempts; deviceInfo.SuccessfulConnections = _successfulConnections; deviceInfo.FailedConnections = _failedConnections; deviceInfo.ReconnectCount = _reconnectCount; deviceInfo.LastSuccessfulConnection = _lastSuccessfulConnection?.ToString("yyyy-MM-dd HH:mm:ss"); deviceInfo.LastConnectionFailure = _lastConnectionFailure?.ToString("yyyy-MM-dd HH:mm:ss"); // Overflow / live telemetry deviceInfo.OverflowEnqueued = _overflowEnqueued; deviceInfo.OverflowDropped = _overflowDropped; deviceInfo.PrimaryWriteCount = _primaryWriteCount; await _apiService.SendHeartbeatAsync(deviceInfo); if (deviceInfo.LogCount is >= 0) _lastKnownLogCount = deviceInfo.LogCount.Value; } else { LogEvent("GET_DEVICE_INFO_FAILED", $"error={_protocol.LastError} — heartbeat skipped", LogLevel.Warning); } } } // Stable jitter per device to prevent poll storms var jitterMs = (Math.Abs(_device.Ip.GetHashCode()) % 5000); await Task.Delay(TimeSpan.FromSeconds(_pollingInterval) + TimeSpan.FromMilliseconds(jitterMs), _cts.Token); } catch (OperationCanceledException) { break; } catch (Exception ex) { _isOnline = false; _retryCount++; await _protocol.StopEventListenerAsync(); _eventsActive = false; _state?.TransitionTo(DeviceState.Reconnecting, $"error: {ex.Message}"); _lastError = ex.Message; _readFailureCount++; _consecutiveReadFailures++; _lastReadError = ex.Message; _lastReadErrorAt = DateTime.UtcNow; _protocol?.Dispose(); _protocol = null; LogEvent("UNHANDLED_ERROR", $"error={ex.Message} retry={_retryCount}/{_maxRetryAttempts}", LogLevel.Error); await _apiService.SendHeartbeatAsync(new DeviceStatus { DeviceIp = _device.Ip, DevicePort = _device.Port, Status = "error", BufferCount = _bufferService.GetPendingCount(), DroppedRecords = _bufferService.TotalDroppedUnsynced, DeadLetterCount = _bufferService.GetDeadLetterCount(), LastError = ex.Message, }); var delay = _retryCount <= _backoffSchedule.Length ? _backoffSchedule[_retryCount - 1] : _backoffSchedule[^1]; await Task.Delay(delay, _cts.Token); } } _protocol?.Dispose(); // Complete writers so drain tasks unblock and exit their loops _liveQueue.Writer.TryComplete(); _overflowQueue.Writer.TryComplete(); // Observe background tasks so exceptions are not unobserved var bgTasks = new[] { _liveDrainTask, _overflowDrainTask, _uploadTask, _telemetryTask } .Where(t => t != null).Cast().ToArray(); if (bgTasks.Length > 0) { try { await Task.WhenAll(bgTasks); } catch { /* exceptions already observed inside each task */ } } } private async Task UploadBufferedLogsAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { var rowIds = new List(); // Hoist for exception recovery try { // Stale SENDING recovery: runs when no active batch, or active batch exceeded timeout. // ResetStuckSending uses last_attempt_at < now-2min guard, so live batches are safe. if (_lastUploadBatchStartUtc == DateTime.MinValue || (DateTime.UtcNow - _lastUploadBatchStartUtc).TotalSeconds > UploadBatchStuckSeconds) { var resetCount = _bufferService.ResetStuckSending(_device.Ip, _device.Port); if (resetCount > 0) LogEvent("RESET_STUCK_SENDING", $"Reset {resetCount} stuck SENDING records to PENDING (stale >2min)"); _lastUploadBatchStartUtc = DateTime.MinValue; } var (pending, poisonCount) = _bufferService.GetPendingLogs(_device.Ip, _device.Port, 200); if (poisonCount > 0) LogEvent("POISON_RECORDS", $"Dead-lettered {poisonCount} malformed records, continuing with {pending.Count} valid", LogLevel.Warning); if (pending.Count == 0) { await Task.Delay(TimeSpan.FromSeconds(5), ct); continue; } var logs = pending.Select(p => p.Log).ToList(); rowIds = pending.Select(p => p.RowId).ToList(); _lastUploadBatchStartUtc = DateTime.UtcNow; _logger.LogInformation("[{Ip}] Uploading {Count} buffered logs (device-isolated)", _device.Ip, logs.Count); var result = await _apiService.SendBatchLogsAsync(logs); if (result.IsValidAck) { // Handle partial success: quarantine rejected records, mark rest as sent var rejectedIndices = result.RejectedRecords? .Select(r => r.Index) .ToHashSet() ?? new HashSet(); if (rejectedIndices.Count > 0) { // Separate valid vs rejected row IDs by index var validRowIds = new List(); var quarantinedRowIds = new List(); for (int i = 0; i < rowIds.Count; i++) { if (rejectedIndices.Contains(i)) quarantinedRowIds.Add(rowIds[i]); else validRowIds.Add(rowIds[i]); } if (validRowIds.Count > 0) _bufferService.MarkAsSent(validRowIds); if (quarantinedRowIds.Count > 0) _bufferService.MoveToDeadLetter(quarantinedRowIds, "permanent_rejection"); LogEvent("PARTIAL_ACK", $"imported={result.Imported} quarantined={quarantinedRowIds.Count} sent={validRowIds.Count}"); rowIds = validRowIds; // Only advance cursor for valid records } else { _bufferService.MarkAsSent(rowIds); } _lastSuccessfulSync = DateTime.UtcNow; _lastError = null; _lastUploadBatchStartUtc = DateTime.MinValue; var maxTime = MaxValidPunchTime(logs); if (maxTime.HasValue) { if (_lastSentMaxPunch == null || maxTime > _lastSentMaxPunch) _lastSentMaxPunch = maxTime.Value; await _apiService.UpdateSyncStateAsync(_device.Id, maxTime.Value, logs.Count); } // CRITICAL: Advance cursor ONLY after confirmed MarkAsSent + ACK if (_cursorService != null && maxTime.HasValue && rowIds.Count > 0) { var recordHash = ComputeRecordHash(logs[^1]); await _cursorService.UpdateAfterUploadAsync(_device.Ip, _device.Port, rowIds.Count); await _cursorService.AdvanceCursorPositionAsync(_device.Ip, _device.Port, maxTime.Value.ToUniversalTime(), recordHash); LogEvent("CURSOR_ADVANCED", $"upload confirmed: {rowIds.Count} records, cursor advanced to {maxTime.Value:O}"); } // ╔═══════════════════════════════════════════════════════════╗ // ║ DISABLED: Automatic CleanLogData for Production ║ // ║ Reason: TOCTOU race between GetLogCount and ClearData. ║ // ║ A punch can arrive in the ms window and be permanently ║ // ║ lost. Safe manual CleanLogData will be designed later. ║ // ║ Device can hold records without impacting live sync. ║ // ╚═══════════════════════════════════════════════════════════╝ _logger.LogInformation("[{Ip}] {Count} buffered logs uploaded successfully", _device.Ip, logs.Count); } else { // Distinguish between: (a) server returned rejected records // vs (b) network/server error — full retry var rejectedIndices = result.RejectedRecords? .Select(r => r.Index) .ToHashSet() ?? new HashSet(); if (rejectedIndices.Count > 0) { // Case A: Server returned rejected records → dead-letter rejected, mark rest sent // Handles both partial (imported > 0) and all-rejected (imported == 0) cases var validRowIds = new List(); var deadLetterRowIds = new List(); for (int i = 0; i < rowIds.Count; i++) { if (rejectedIndices.Contains(i)) deadLetterRowIds.Add(rowIds[i]); else validRowIds.Add(rowIds[i]); } if (validRowIds.Count > 0) _bufferService.MarkAsSent(validRowIds); if (deadLetterRowIds.Count > 0) _bufferService.MoveToDeadLetter(deadLetterRowIds, "server_rejected"); LogEvent("PARTIAL_ACK", $"imported={result.Imported} dead_letter={deadLetterRowIds.Count} sent={validRowIds.Count}"); rowIds = validRowIds; // Don't backoff — partial success means we should continue } else { // Case B: Full failure — distinguish transient vs permanent if (result.IsTransient) { // Transient failure (5xx, timeout, connection error): // Reset attempt_count so these records don't accumulate towards DLQ. // Use longer backoff since backend is likely down. _bufferService.ResetAttemptCount(rowIds); _lastError = result.ErrorMessage; _logger.LogWarning("[{Ip}] Transient upload failure (records preserved): {Error}", _device.Ip, result.ErrorMessage); _lastUploadBatchStartUtc = DateTime.MinValue; await Task.Delay(TimeSpan.FromSeconds(30), ct); } else { // Permanent failure (4xx, validation error): // Check for records exceeding max retries → move to DLQ var overRetry = _bufferService.GetRecordsOverMaxRetry(rowIds, 5); if (overRetry.Count > 0) { _bufferService.MoveToDeadLetter(overRetry, "max_retries_exceeded"); var remaining = rowIds.Except(overRetry).ToList(); if (remaining.Count > 0) _bufferService.MarkAsFailed(remaining, result.ErrorMessage); LogEvent("DLQ_MOVE", $"Moved {overRetry.Count} records to DLQ after max retries, {remaining.Count} remaining for retry"); } else { _bufferService.MarkAsFailed(rowIds, result.ErrorMessage); } _lastError = result.ErrorMessage; _logger.LogWarning("[{Ip}] Permanent upload failure: {Error}", _device.Ip, result.ErrorMessage); _lastUploadBatchStartUtc = DateTime.MinValue; var backoff = Math.Min(30, 5 * (int)Math.Pow(2, Math.Min(_retryCount, 4))); await Task.Delay(TimeSpan.FromSeconds(backoff), ct); } } } } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Upload worker error", _device.Ip); _lastError = ex.Message; // Immediately recover any records claimed into SENDING before the exception if (rowIds.Count > 0) { var resetCount = _bufferService.ResetAttemptCount(rowIds); if (resetCount > 0) LogEvent("UPLOAD_EXCEPTION_RECOVERY", $"Reset {resetCount} SENDING records to PENDING after upload exception: {ex.GetType().Name}"); } _lastUploadBatchStartUtc = DateTime.MinValue; await Task.Delay(TimeSpan.FromSeconds(10), ct); } } } private List FilterForSend(List logs) { // Filter by sync cutoff only — dedup is handled by unique index in SQLite/MySQL // The 72h window is removed to prevent data loss when device clock is wrong var filtered = logs.Where(l => l.PunchTime.ToUniversalTime() >= _syncCutoff).ToList(); var dropped = logs.Count - filtered.Count; if (dropped > 0) _logger.LogInformation("[{Ip}] {Dropped} old logs skipped (before {Cutoff})", _device.Ip, dropped, _syncCutoff); return filtered; } private static DateTime? MaxValidPunchTime(List logs) { DateTime? max = null; foreach (var l in logs) { if (l.PunchTime > DateTime.UtcNow.AddMinutes(30)) continue; if (max == null || l.PunchTime > max) max = l.PunchTime; } return max; } private DateTime _lastFullReadAtUtc = DateTime.MinValue; private bool IsFullResyncDue() => DateTime.UtcNow - _lastFullReadAtUtc > TimeSpan.FromMinutes(FullResyncMinutes); private async Task DrainLiveQueueAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { try { // Wait for at least one event (bounded backpressure) await _liveQueue.Reader.WaitToReadAsync(ct); // Drain up to 500 events in a batch var batch = new List(); while (batch.Count < 500 && _liveQueue.Reader.TryRead(out var item)) batch.Add(item); if (batch.Count == 0) continue; var validBatch = batch.Where(l => l.PunchTime.ToUniversalTime() >= _syncCutoff).ToList(); if (validBatch.Count == 0) continue; _logger.LogInformation("[{Ip}] {Count} LIVE punch(es) buffered", _device.Ip, validBatch.Count); foreach (var log in validBatch) { var bufResult = _bufferService.BufferLog(log, priority: 1); if (bufResult == BufferResult.CapacityFull) { Interlocked.Increment(ref _totalDroppedCapacityFull); LogEvent("BUFFER_FULL", $"LIVE event REJECTED (capacity): {log.PersonnelCode} @ {log.PunchTime:O}", LogLevel.Warning); } } // Update event cursor after successful buffering if (_cursorService != null && validBatch.Count > 0) await _cursorService.UpdateAfterEventAsync(_device.Ip, _device.Port); _lastPunchTime = validBatch.Max(l => l.PunchTime).ToString("yyyy-MM-dd HH:mm:ss"); } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Live queue drain error", _device.Ip); await Task.Delay(TimeSpan.FromSeconds(1), ct); } } } private async Task DrainOverflowQueueAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { try { await _overflowQueue.Reader.WaitToReadAsync(ct); var batch = new List(); while (batch.Count < 500 && _overflowQueue.Reader.TryRead(out var item)) batch.Add(item); if (batch.Count == 0) continue; var validBatch = batch.Where(l => l.PunchTime.ToUniversalTime() >= _syncCutoff).ToList(); if (validBatch.Count == 0) continue; _logger.LogInformation("[{Ip}] {Count} OVERFLOW punch(es) buffered", _device.Ip, validBatch.Count); foreach (var log in validBatch) { var bufResult = _bufferService.BufferLog(log, priority: 1); if (bufResult == BufferResult.CapacityFull) { Interlocked.Increment(ref _totalDroppedCapacityFull); LogEvent("BUFFER_FULL", $"OVERFLOW event REJECTED (capacity): {log.PersonnelCode} @ {log.PunchTime:O}", LogLevel.Warning); } } if (_cursorService != null && validBatch.Count > 0) await _cursorService.UpdateAfterEventAsync(_device.Ip, _device.Port); _lastPunchTime = validBatch.Max(l => l.PunchTime).ToString("yyyy-MM-dd HH:mm:ss"); } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "[{Ip}] Overflow queue drain error", _device.Ip); await Task.Delay(TimeSpan.FromSeconds(1), ct); } } } private async Task TelemetryFlushAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { try { await Task.Delay(TimeSpan.FromSeconds(30), ct); var enqueued = Interlocked.Exchange(ref _overflowEnqueued, 0); var dropped = Interlocked.Exchange(ref _overflowDropped, 0); var primary = Interlocked.Exchange(ref _primaryWriteCount, 0); if (enqueued > 0 || dropped > 0) { LogEvent("LIVE_TELEMETRY", $"primary={primary} overflow={enqueued} dropped={dropped}", dropped > 0 ? LogLevel.Warning : LogLevel.Information); } } catch (OperationCanceledException) { break; } catch { /* telemetry flush failure is non-critical */ } } } private async Task ConnectToDeviceAsync(CancellationToken ct) { if (_protocol != null) _protocol.Dispose(); _protocol = null; _state?.TransitionTo(DeviceState.Connecting, $"attempt #{_connectionAttempts + 1}"); _connectionAttempts++; LogEvent("CONNECT_START", $"attempt #{_connectionAttempts} to {_device.Ip}:{_device.Port}"); var sw = System.Diagnostics.Stopwatch.StartNew(); var p = new ZKTecoProtocol(_device.Ip, _device.Port, _device.CommKey ?? 0, connectTimeoutMs: _connectTimeoutMs, readTimeoutMs: _readTimeoutMs, logger: _protocolLogger, deviceTimeNormalizer: _deviceTimeNormalizer); if (await p.ConnectAsync(ct)) { sw.Stop(); _protocol = p; _protocol.OnReaderEnumerationFailure = OnReaderEnumerationFailure; _successfulConnections++; _lastSuccessfulConnection = DateTime.UtcNow; _isOnline = true; _state?.TransitionTo(DeviceState.CatchingUp, "connected, starting catch-up read"); LogEvent("CONNECT_SUCCESS", $"Connected ({_device.Model}) duration={sw.ElapsedMilliseconds}ms"); } else { sw.Stop(); _failedConnections++; _lastConnectionFailure = DateTime.UtcNow; _retryCount++; p.Dispose(); _isOnline = false; _state?.TransitionTo(DeviceState.Reconnecting, $"connect failed: {p.LastError}"); LogEvent("CONNECT_FAILED", $"duration={sw.ElapsedMilliseconds}ms error={p.LastError} retry={_retryCount}", LogLevel.Warning); } } private void Log(string operation, string message) { try { _fileLogger?.LogInformation($"[{{{_device.Ip}:{_device.Port}}}] [{operation}] {message}"); } catch { /* FileLogger failure is non-critical — never propagate */ } } /// /// Structured diagnostic log — writes to BOTH FileLogger and ILogger (EventLog). /// Use for SDK boundary events: connect, read, timeout, watchdog, reconnect. /// private static string ComputeRecordHash(AttendanceLog log) { var key = $"{log.DeviceIp}:{log.DevicePort}:{log.PersonnelCode}:{log.PunchTime:O}:{log.PunchType}:{log.VerifyMode}:{log.WorkCode}"; return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(key)))[..16]; } private void LogEvent(string operation, string message, LogLevel level = LogLevel.Information) { try { _fileLogger?.LogInformation($"[{{{_device.Ip}:{_device.Port}}}] [{operation}] {message}"); } catch { } _logger.Log(level, "[{Ip}:{Port}] [{Operation}] {Message}", _device.Ip, _device.Port, operation, message); } // ═════════════════════════════════════════════════════════════════════ // READER ENUMERATION FAILURE TRAP — Evidence Capture // // Invoked by ZKTecoProtocol.ReadAllLogsIncremental() when: // ReadGeneralLogData=TRUE + SSR_FIRST=FALSE + GetLogCount>0 // // Uses the EXISTING COM instance — no new session created. // Saves JSON snapshot. Does NOT reconnect/retry/restart. // ═════════════════════════════════════════════════════════════════════ private void OnReaderEnumerationFailure(ReaderFailureSnapshot snapshot) { try { LogEvent("READER_ENUMERATION_FAILURE", $"TRAP={snapshot.TrapId} GetLogCount={snapshot.Failure.GetLogCount} " + $"ReadErr={snapshot.Failure.ReadGeneralGetLastError} SSR_FIRST_ERR={snapshot.Failure.SsrFirstGetLastError} " + $"COM={snapshot.ComSession.ComInstanceId}", LogLevel.Critical); // Save JSON snapshot var snapshotDir = Path.Combine(AppContext.BaseDirectory, "failure_snapshots"); if (!Directory.Exists(snapshotDir)) Directory.CreateDirectory(snapshotDir); string fileName = $"reader_failure_snapshot_{_device.Ip.Replace(".", "_")}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.json"; string filePath = Path.Combine(snapshotDir, fileName); var jsonOpts = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; string json = System.Text.Json.JsonSerializer.Serialize(snapshot, jsonOpts); File.WriteAllText(filePath, json); LogEvent("FAILURE_SNAPSHOT_SAVED", $"path={filePath}", LogLevel.Critical); // CRITICAL: Do NOT reconnect, retry, or restart. // Session stays broken — operator runs RecoverE1 or RecoverE2 manually. } catch (Exception ex) { LogEvent("FAILURE_SNAPSHOT_ERROR", $"Failed to save snapshot: {ex.Message}", LogLevel.Error); } } // ═════════════════════════════════════════════════════════════════════ // OPERATOR RECOVERY COMMANDS — Manual only, never auto-triggered // ═════════════════════════════════════════════════════════════════════ /// /// RECOVER_E1: Same COM instance Disconnect → Connect → Read → SSR. /// Operator-initiated only. Uses existing _protocol instance. /// public async Task RecoverE1Async(CancellationToken ct = default) { if (_protocol == null) { LogEvent("RECOVER_E1", "No protocol instance", LogLevel.Warning); return false; } LogEvent("RECOVER_E1", "Starting same-instance recovery (Disconnect → Connect → Read → SSR)", LogLevel.Information); try { _protocol.Disconnect(); await Task.Delay(1000, ct); if (!await _protocol.ConnectAsync(ct)) { LogEvent("RECOVER_E1", $"Connect failed: {_protocol.LastError}", LogLevel.Warning); return false; } var count = _protocol.ReadAllLogsIncremental(_ => { }, ct); bool ssrOk = count > 0; LogEvent("RECOVER_E1", $"Result: connected={_protocol.IsConnected} read={count} ssr_ok={ssrOk}", LogLevel.Information); return ssrOk; } catch (Exception ex) { LogEvent("RECOVER_E1", $"Exception: {ex.Message}", LogLevel.Warning); return false; } } /// /// RECOVER_E2: Dispose current COM → create new CZKEMClass → Connect → Read → SSR. /// Operator-initiated only. Fully releases old COM instance. /// public async Task RecoverE2Async(CancellationToken ct = default) { LogEvent("RECOVER_E2", "Starting dispose/recreate recovery (new COM → Connect → Read → SSR)", LogLevel.Information); try { _protocol?.Dispose(); _protocol = null; await Task.Delay(1000, ct); var p = new ZKTecoProtocol(_device.Ip, _device.Port, _device.CommKey ?? 0, connectTimeoutMs: _connectTimeoutMs, readTimeoutMs: _readTimeoutMs, logger: _protocolLogger, deviceTimeNormalizer: _deviceTimeNormalizer); p.OnReaderEnumerationFailure = OnReaderEnumerationFailure; if (!await p.ConnectAsync(ct)) { LogEvent("RECOVER_E2", $"Connect failed: {p.LastError}", LogLevel.Warning); p.Dispose(); return false; } _protocol = p; var count = _protocol.ReadAllLogsIncremental(_ => { }, ct); bool ssrOk = count > 0; LogEvent("RECOVER_E2", $"Result: connected={_protocol.IsConnected} read={count} ssr_ok={ssrOk}", LogLevel.Information); return ssrOk; } catch (Exception ex) { LogEvent("RECOVER_E2", $"Exception: {ex.Message}", LogLevel.Warning); return false; } } public void Stop() { _cts?.Cancel(); _protocol?.Disconnect(); _isOnline = false; // Complete writers so drain tasks unblock immediately on Stop (not just on StartAsync exit) _liveQueue.Writer.TryComplete(); _overflowQueue.Writer.TryComplete(); } public void Dispose() { Stop(); _protocol?.Dispose(); _deviceReadLock.Dispose(); } }