using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Host;
using AttendanceHub.Sync.Persistence;
using AttendanceHub.Sync.Persistence.Sqlite;
using AttendanceHub.Sync.Upload;
using Microsoft.Extensions.Logging;
using Xunit;
namespace AttendanceHub.Sync.Tests;
///
/// Delivery watchdog tests. These exist because no test in this suite could catch the 2026-10-11
/// outage: upload was disabled by a config copy, the host stayed healthy in every observable way,
/// 530 punches stopped reaching MySQL for ten hours, and all 105 tests stayed green. Nothing in the
/// suite asserted that a punch actually reaches a destination.
///
/// The watchdog is tested by driving SampleAsync directly rather than waiting on the 30s timer, so
/// these are deterministic and fast.
///
public class DeliveryWatchdogTests : IAsyncLifetime
{
private string _dbPath = null!;
private SQLiteSyncStore _store = null!;
private const string Device = "watch-dev";
public async Task InitializeAsync()
{
_dbPath = Path.Combine(Path.GetTempPath(), "ahub-watchdog", Guid.NewGuid().ToString("N") + ".db");
Directory.CreateDirectory(Path.GetDirectoryName(_dbPath)!);
_store = new SQLiteSyncStore(_dbPath);
await _store.InitializeAsync();
}
public async Task DisposeAsync()
{
await _store.DisposeAsync();
try { Directory.Delete(Path.GetDirectoryName(_dbPath)!, true); } catch { /* temp */ }
}
/// Minimal capturing logger. The watchdog's entire contract is "it says something",
/// so asserting on emitted levels/messages is asserting on behaviour, not on internals.
private sealed class CapturingLogger : ILogger
{
public readonly List<(LogLevel Level, string Message)> Entries = new();
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
=> Entries.Add((logLevel, formatter(state, exception)));
public bool Has(LogLevel level, string fragment)
=> Entries.Any(e => e.Level == level && e.Message.Contains(fragment, StringComparison.Ordinal));
}
/// Unique punch: distinct pin and instant so every call inserts a genuinely new row.
private async Task SeedAsync(int count, int startSecond)
{
for (var i = 0; i < count; i++)
{
var t = new DateTimeOffset(2026, 9, 23, 8, 0, startSecond + i, TimeSpan.Zero);
var p = new NormalizedPunch(
new PunchIdentity(Device, "pin-" + startSecond + "-" + i, t),
PunchSource.Realtime, 0, 1, 0, false, 1, "SSR",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, PunchTimeStatus.Acceptable,
2026, 9, 23, 8, 0, startSecond + i);
await _store.UpsertPunchAsync(p);
}
}
private static IReadOnlyList Devices() => new[] { Device };
///
/// Drains every Pending row to Sent using the real outbox path (claim lease -> ack state), the
/// same two calls the uploader makes. Loops until the claim returns nothing, with a hard bound
/// so a broken state machine fails the test instead of hanging it.
///
private async Task DrainAsync()
{
var now = DateTimeOffset.UtcNow;
for (var guard = 0; guard < 1000; guard++)
{
var batch = await _store.ClaimPendingBatchAsync(Device, 200, TimeSpan.FromMinutes(5), now);
if (batch.Count == 0)
return;
foreach (var record in batch)
await _store.SetUploadStateAsync(record.LocalId, OutboxUploadState.Sent);
}
Assert.Fail("drain never emptied the outbox — outbox state machine is stuck");
}
// ---------- 1) the outage shape: backlog climbs, nothing drains it ----------
[Fact]
public async Task Growing_Backlog_With_No_Delivery_Raises_Upload_Stall()
{
var log = new CapturingLogger();
await using var watchdog = new DeliveryWatchdog(_store, Devices, log);
// Nothing ever calls the uploader, so every row stays Pending - exactly the 2026-10-11 shape.
var second = 0;
for (var i = 0; i < DeliveryWatchdog.StallThreshold + 2; i++)
{
await SeedAsync(3, second);
second += 3;
await watchdog.SampleAsync();
}
Assert.True(log.Has(LogLevel.Warning, "UPLOAD_STALL"),
"a backlog that grows every sample with nothing delivered must raise UPLOAD_STALL. "
+ "Captured: " + string.Join(" | ", log.Entries.Select(e => e.Level + ":" + e.Message)));
}
// ---------- 2) the false-positive trap: occupancy is not a stall ----------
[Fact]
public async Task Constant_Backlog_Never_Alarms()
{
var log = new CapturingLogger();
await using var watchdog = new DeliveryWatchdog(_store, Devices, log);
// Seed once, then never grow and never deliver. This is the shape of the ledger's permanent
// residents: device-clock garbage dated 2033 sits Pending forever and is correctly withheld.
// A watchdog keyed on "pending > 0" would alarm on a perfectly healthy host forever.
await SeedAsync(27, 0);
for (var i = 0; i < DeliveryWatchdog.StallThreshold * 4; i++)
await watchdog.SampleAsync();
Assert.False(log.Has(LogLevel.Warning, "UPLOAD_STALL"),
"a fixed backlog is not a stall; only growth is. Alarmed on: "
+ string.Join(" | ", log.Entries.Where(e => e.Level == LogLevel.Warning).Select(e => e.Message)));
}
// ---------- 3) recovery is reported, and the alarm does not stick ----------
[Fact]
public async Task Draining_Backlog_Clears_The_Alarm()
{
var log = new CapturingLogger();
await using var watchdog = new DeliveryWatchdog(_store, Devices, log);
var second = 0;
for (var i = 0; i < DeliveryWatchdog.StallThreshold + 2; i++)
{
await SeedAsync(2, second);
second += 2;
await watchdog.SampleAsync();
}
Assert.True(log.Has(LogLevel.Warning, "UPLOAD_STALL"), "precondition: stall must have fired");
// "Delivery resumes": drain the backlog through the same claim/ack path the uploader uses,
// then keep sampling with a flat, empty outbox. Deliberately no test-only store helper —
// if this drain drifted from the real path the test would prove nothing.
await DrainAsync();
for (var i = 0; i < DeliveryWatchdog.StallThreshold + 2; i++)
await watchdog.SampleAsync();
Assert.True(log.Has(LogLevel.Information, "UPLOAD_STALL_CLEARED"),
"clearing must be reported so an operator knows the incident ended. Captured: "
+ string.Join(" | ", log.Entries.Select(e => e.Level + ":" + e.Message)));
}
/// What a broken endpoint produces: the cycle claims Pending and fails, parking rows in Retry.
/// This is the shape the old Pending-only metric could not see.
private async Task FailDeliveryAsync()
{
var batch = await _store.ClaimPendingBatchAsync(Device, 200, TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow);
foreach (var record in batch)
await _store.SetUploadStateAsync(record.LocalId, OutboxUploadState.Retry);
}
// ---------- 4) the shape a Pending-only metric is blind to ----------
[Fact]
public async Task Backlog_Stuck_In_Retry_Still_Alarms()
{
var log = new CapturingLogger();
await using var watchdog = new DeliveryWatchdog(_store, Devices, log);
// Every cycle: new punches arrive, then delivery CLAIMS them and fails, so they land in Retry.
// Pending is therefore drained back to ~0 each sample and never grows, while the real
// undelivered backlog climbs without bound. This is an unreachable endpoint or a revoked
// token — the most likely genuine delivery failure there is.
var second = 0;
for (var i = 0; i < DeliveryWatchdog.StallThreshold + 2; i++)
{
await SeedAsync(3, second);
second += 3;
await FailDeliveryAsync();
await watchdog.SampleAsync();
}
Assert.True(log.Has(LogLevel.Warning, "UPLOAD_STALL"),
"rows parked in Retry are undelivered work and must alarm; a watchdog counting only Pending "
+ "would report a draining backlog while attendance piled up. Captured: "
+ string.Join(" | ", log.Entries.Select(e => e.Level + ":" + e.Message)));
Assert.True(log.Has(LogLevel.Warning, "RETRY_DOMINATED"),
"a Retry-dominated stall must name its own shape, so the operator can tell 'endpoint refused' "
+ "from 'uploader not running' without opening the database.");
}
// ---------- 5) the watchdog must not depend on the uploader existing ----------
[Fact]
public void Watchdog_Has_No_Com_Dependency()
{
// Same guarantee UploadRuntime/UploadWorker make: delivery telemetry never touches COM, so
// it can keep reporting while acquisition is completely wedged.
foreach (var m in typeof(DeliveryWatchdog).GetMethods()
.Where(m => m.DeclaringType == typeof(DeliveryWatchdog)))
{
Assert.DoesNotContain("ZkCom", m.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("ComSession", m.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
}
}
}