using System.Text.Json; using AttendanceHub.Sync.Configuration; using AttendanceHub.Sync.Host; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Heartbeat reporting tests. /// /// The heartbeat is the only subsystem that can be perfectly healthy on its own side and still be /// useless: Laravel judges a device online purely from devices.last_seen_at (a 120s window), so a /// reporter that is too slow, that reports the wrong identity, or that cannot reach the endpoint /// produces the same visible result — every device showing offline — while every local log line /// looks fine. That is the exact shape of the 2026-10-11 outage, which is why each of those three /// ways of being silently useless gets its own test here. /// public class HeartbeatReporterTests { // ---------- 1) status derivation: the value that decides what an operator believes ---------- [Theory] // No worker at all (device removed or not yet started) must never read as online, even if a // stale health snapshot would say connected. [InlineData(false, true, 0, "offline")] [InlineData(false, false, 0, "offline")] // Worker present but the session is down: offline, not "error" — nothing is malfunctioning, // the device simply is not answering. [InlineData(true, false, 0, "offline")] [InlineData(true, false, 9, "offline")] // Healthy: connected, and the most recent read succeeded. [InlineData(true, true, 0, "online")] // The case online/offline alone would hide: the device accepts a connection but cannot be read // (172.30.70.5 behaves exactly like this — firmware rejects ReadTimeGLogData). [InlineData(true, true, 1, "error")] [InlineData(true, true, 6, "error")] public void Status_Comes_From_The_Acquisition_Snapshot_Not_From_Hope( bool workerPresent, bool connected, int consecutiveFailures, string expected) { Assert.Equal(expected, HeartbeatReporter.DeriveStatus(workerPresent, connected, consecutiveFailures)); } // ---------- 2) the wire: what the backend is told ---------- private static DeviceHeartbeat FullBeat() => HeartbeatReporter.Build( ip: "172.24.30.9", port: 4370, workerPresent: true, connected: true, firmwareVersion: "Ver 6.60 Aug 18 2018", userCount: 466, logCount: 49084, lastSuccessfulReadAt: new DateTimeOffset(2026, 10, 14, 3, 45, 12, TimeSpan.Zero), lastReadErrorAt: null, lastReadError: null, consecutiveReadFailures: 0, reconnectCount: 2, readSuccessCount: 1234); private static JsonElement AsJson(DeviceHeartbeat beat) { using var doc = JsonDocument.Parse(beat.ToJson()); return doc.RootElement.Clone(); } [Fact] public void Json_Carries_The_Identity_Laravel_Looks_Up() { var json = AsJson(FullBeat()); // findDevice() matches on ip + port + tenant. A wrong identity does not fail loudly here: // the backend answers 404 and the beat is dropped for as long as it keeps being wrong. Assert.Equal("172.24.30.9", json.GetProperty("device_ip").GetString()); Assert.Equal(4370, json.GetProperty("device_port").GetInt32()); Assert.Equal("online", json.GetProperty("status").GetString()); } [Fact] public void Json_Omits_Unknown_Optional_Fields_Instead_Of_Faking_Them() { var json = AsJson(FullBeat()); // Absent, not zero: the backend treats a missing field as "unknown, keep the last value", // while a zero would overwrite real firmware and counter data with a placeholder forever. Assert.False(json.TryGetProperty("last_read_error", out _)); Assert.False(json.TryGetProperty("last_read_error_at", out _)); } [Fact] public void Json_Sends_Telemetry_The_Panel_Displays() { var json = AsJson(FullBeat()); Assert.Equal("Ver 6.60 Aug 18 2018", json.GetProperty("firmware_version").GetString()); Assert.Equal(466, json.GetProperty("user_count").GetInt32()); Assert.Equal(49084, json.GetProperty("log_count").GetInt32()); Assert.Equal(0, json.GetProperty("consecutive_read_failures").GetInt32()); Assert.Equal(1234, json.GetProperty("read_success_count").GetInt32()); Assert.Equal(2, json.GetProperty("reconnect_count").GetInt32()); } [Fact] public void Json_Sends_The_Last_Successful_Read_As_Parseable_DateTime() { // The backend validates these with Laravel's "date" rule; anything it cannot parse is a // 422, which would reject the whole beat and hide every other field with it. var json = AsJson(FullBeat()); Assert.True( DateTime.TryParse(json.GetProperty("last_successful_read_at").GetString(), null, System.Globalization.DateTimeStyles.RoundtripKind, out _), "last_successful_read_at must be a string the backend can parse as a date"); } [Fact] public void Dates_Cross_The_Boundary_As_Local_Wall_Clock_Not_Utc() { // Measured 2026-10-15: sending UTC digits made the backend read them back as site-local // time, so a read that had just succeeded was reported 210 minutes old and /v1/health // answered status=critical healthy=0 for all five devices. The digits, not the instant, // are what that column round-trips. var utcInstant = new DateTimeOffset(2026, 10, 15, 9, 22, 57, TimeSpan.Zero); var beat = HeartbeatReporter.Build( "172.24.30.9", 4370, true, true, null, null, null, utcInstant, null, null, 0, 0, 0); var sent = AsJson(beat).GetProperty("last_successful_read_at").GetString()!; var parsed = DateTimeOffset.Parse(sent, null, System.Globalization.DateTimeStyles.RoundtripKind); // Must carry the local offset. On a UTC-hosted machine this is vacuous by construction — // there is no shift to avoid there — but on the production host it is the whole fix. Assert.Equal(TimeZoneInfo.Local.GetUtcOffset(DateTime.Now), parsed.Offset); // And the instant itself must survive the conversion: only the spelling changed. Assert.Equal(utcInstant.ToUniversalTime(), parsed.ToUniversalTime()); } [Fact] public void An_Empty_Read_Error_Is_Omitted_But_A_Real_One_Is_Kept() { var empty = HeartbeatReporter.Build( "172.24.30.9", 4370, true, true, null, null, null, null, null, " ", 0, 0, 0); Assert.False(AsJson(empty).TryGetProperty("last_read_error", out _)); var failing = HeartbeatReporter.Build( "172.30.70.5", 4370, true, true, null, null, null, null, new DateTimeOffset(2026, 10, 14, 3, 0, 0, TimeSpan.Zero), "ReadTimeGLogData not supported by firmware", 4, 0, 0); var json = AsJson(failing); Assert.Equal("error", json.GetProperty("status").GetString()); Assert.Equal("ReadTimeGLogData not supported by firmware", json.GetProperty("last_read_error").GetString()); } [Fact] public void A_Very_Long_Read_Error_Is_Truncated_Rather_Than_Unbounded() { var beat = HeartbeatReporter.Build( "172.24.30.9", 4370, true, false, null, null, null, null, null, new string('x', 5000), 1, 0, 0); var json = AsJson(beat); Assert.Equal(500, json.GetProperty("last_read_error").GetString()!.Length); } // ---------- 3) activation: configured or not, and never silently ---------- private static string WriteConfig(string json) { var path = Path.Combine(Path.GetTempPath(), "ahub-heartbeat", Guid.NewGuid().ToString("N") + ".json"); Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, json); return path; } [Fact] public void A_Missing_Heartbeat_Section_Means_Disabled_Not_Default_On() { var path = WriteConfig("""{ "upload": { "enabled": true } }"""); try { var cfg = HeartbeatConfig.ParseFromFile(path); Assert.False(cfg.Enabled, "absent configuration must not enable reporting on its own"); Assert.Equal(HeartbeatConfig.DefaultIntervalSeconds, cfg.IntervalSeconds); } finally { try { File.Delete(path); } catch { /* temp */ } } } [Fact] public void An_Enabled_Section_Is_Parsed_With_Its_Exact_Cadence() { var path = WriteConfig("""{ "heartbeat": { "enabled": true, "intervalSeconds": 45 } }"""); try { var cfg = HeartbeatConfig.ParseFromFile(path); Assert.True(cfg.Enabled); Assert.Equal(45, cfg.IntervalSeconds); } finally { try { File.Delete(path); } catch { /* temp */ } } } [Fact] public void An_Enabled_Section_Without_A_Cadence_Falls_Back_To_60s() { // 60s is what keeps a device inside the backend's 120s online window with a full beat of // headroom, so the default is part of the contract rather than a placeholder. var path = WriteConfig("""{ "heartbeat": { "enabled": true } }"""); try { Assert.Equal(60, HeartbeatConfig.ParseFromFile(path).IntervalSeconds); } finally { try { File.Delete(path); } catch { /* temp */ } } } [Fact] public void An_Explicitly_Disabled_Section_Stays_Disabled() { var path = WriteConfig("""{ "heartbeat": { "enabled": false, "intervalSeconds": 30 } }"""); try { Assert.False(HeartbeatConfig.ParseFromFile(path).Enabled); } finally { try { File.Delete(path); } catch { /* temp */ } } } [Fact] public void An_Unreadable_File_Does_Not_Throw_Or_Enable_Itself() { var path = WriteConfig("this is not json {{{"); try { var cfg = HeartbeatConfig.ParseFromFile(path); Assert.False(cfg.Enabled); } finally { try { File.Delete(path); } catch { /* temp */ } } } // ---------- 4) the address: a bug that actually shipped, and what stops it returning ---------- [Theory] // The production base address is .../AttendanceHub/public. Losing that prefix sends the beat // to the web server root, which answers 404 — so the reporter is running, the backend is // healthy, and nothing is being recorded. [InlineData("http://localhost/AttendanceHub/public", "http://localhost/AttendanceHub/public/api/v1/sync/heartbeat")] [InlineData("http://localhost/AttendanceHub/public/", "http://localhost/AttendanceHub/public/api/v1/sync/heartbeat")] [InlineData("http://localhost", "http://localhost/api/v1/sync/heartbeat")] [InlineData("http://localhost:8080", "http://localhost:8080/api/v1/sync/heartbeat")] [InlineData("https://sync.example.com/tenant/a/", "https://sync.example.com/tenant/a/api/v1/sync/heartbeat")] public void The_Beat_Uri_Keeps_The_Application_Prefix(string baseAddress, string expected) { // Measured 2026-10-14: the first version used new Uri(base, "/api/..."), and .NET treats a // second argument beginning with '/' as host-absolute, so the base path was dropped. Every // beat 404'd for five devices while this side looked entirely healthy. HttpUploadApiClient // carries the same warning and the same fix. Assert.Equal(expected, HeartbeatReporter.BuildBeatUri(new Uri(baseAddress)).AbsoluteUri); } [Fact] public void The_Beat_Uri_Points_At_The_Route_The_Backend_Actually_Serves() { // If this constant drifts from routes/api.php the beat 404s for the same quiet reason. // AbsolutePath includes the application prefix, which is the whole point of the fix above. var uri = HeartbeatReporter.BuildBeatUri(new Uri("http://localhost/AttendanceHub/public")); Assert.Equal("/AttendanceHub/public/api/v1/sync/heartbeat", uri.AbsolutePath); } }