using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using AttendanceHub.Sync.Configuration;
using AttendanceHub.Sync.Oversight;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Host;
///
/// What the reporter says about one device. A plain record with plain values so the mapping from
/// worker health to the wire can be tested without a device, a thread, or a network.
///
public sealed record DeviceHeartbeat(
string DeviceIp,
int DevicePort,
string Status,
string? FirmwareVersion,
int? UserCount,
int? LogCount,
DateTimeOffset? LastSuccessfulReadAt,
DateTimeOffset? LastReadErrorAt,
string? LastReadError,
int ConsecutiveReadFailures,
int ReadSuccessCount,
int ReconnectCount)
{
/// Serialize to the JSON body Laravel validates. Snake case, nulls omitted —
/// a nullable field that is absent is honest; one sent as a zero is a lie.
public string ToJson()
{
var payload = new Dictionary
{
["device_ip"] = DeviceIp,
["device_port"] = DevicePort,
["status"] = Status,
["firmware_version"] = FirmwareVersion,
["user_count"] = UserCount,
["log_count"] = LogCount,
// Local wall clock, NOT ToString("o") on a UTC value. See LocalWallClock.
["last_successful_read_at"] = LocalWallClock(LastSuccessfulReadAt),
["last_read_error_at"] = LocalWallClock(LastReadErrorAt),
["last_read_error"] = LastReadError,
["consecutive_read_failures"] = ConsecutiveReadFailures,
["read_success_count"] = ReadSuccessCount,
["reconnect_count"] = ReconnectCount,
};
// Absent beats zero: Laravel treats a missing field as "unknown" and keeps the last known
// value, while a zero would overwrite real firmware/count data with a placeholder.
var kept = payload
.Where(kv => kv.Value switch
{
null => false,
string s => s.Length > 0,
_ => true
})
.ToDictionary(kv => kv.Key, kv => kv.Value);
return JsonSerializer.Serialize(kept, Serial);
}
///
/// Serialize an instant as this host's local wall clock with an explicit offset.
///
/// Load bearing, not cosmetic: the backend boundary throughout this system speaks site-local
/// wall clock (punch_time is defined the same way). Measured 2026-10-15 — sending
/// ToString("o") on a UTC-offset value (…T09:22:57+00:00) made the backend record
/// the digits 09:22:57 where it reads site-local time back, so a read that had just succeeded
/// was reported as 210 minutes old and /api/v1/health answered
/// status=critical healthy=0 for all five devices. Stored digits, reported staleness and
/// the UTC-to-local difference were all exactly 210 minutes — three independent numbers that
/// only line up if the digits, not the instant, are what crossed the boundary.
///
/// The offset is still explicit, so the receiver has the information it needs rather than an
/// ambiguity it must guess at.
///
private static string? LocalWallClock(DateTimeOffset? value)
=> value?.ToLocalTime().ToString("o");
private static readonly JsonSerializerOptions Serial = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false,
};
}
///
/// Reports device liveness to Laravel's existing POST /api/v1/sync/heartbeat, which updates
/// devices.last_seen_at / connection_status and the read-health telemetry.
///
/// Why it exists: that endpoint, that table column set and ProductionMonitorService were all
/// built and documented for "heartbeat from C# Service" — and the service never sent one. The
/// consequence is not cosmetic: Device::isOnline() is a 120s test on last_seen_at, so
/// with no heartbeat every device reads as offline in the panel and the monitoring service has no
/// live signal at all. Acquisition was healthy the whole time; it was simply invisible.
///
/// Design rules, in the order they matter:
/// 1. Best effort, always. It never throws out of the loop, never touches the outbox, never
/// performs a COM/SDK call, and cannot delay or fail acquisition or delivery.
/// 2. It borrows health, it does not compute it. Status is derived only from the worker's own
/// snapshot, so it can never report a device as online that the acquisition layer does not
/// believe is connected.
/// 3. Own HttpClient with a short timeout, so a slow or hung endpoint cannot hold a connection
/// pool that punch delivery also uses.
/// 4. Failure logging is rate limited: the first failure per device is logged, then every 20th,
/// plus the recovery. A dead Laravel must not bury the log.
///
public sealed class HeartbeatReporter : IAsyncDisposable
{
/// Log the first failure for a device, then one line every Nth, so an outage is visible
/// without being 5 lines per minute per device.
private const int FailureLogEveryNth = 20;
private static readonly JsonSerializerOptions Serial = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private readonly Func> _supervisors;
private readonly Uri _baseAddress;
private readonly Uri _uri;
private readonly TimeSpan _interval;
private readonly TimeSpan _timeout;
private readonly ILogger _log;
private readonly HttpClient _http;
private readonly bool _ownsHttp;
///
/// Build the beat URI by concatenating, never with new Uri(base, path).
///
/// .NET treats a second argument that begins with '/' as host-absolute, so a base of
/// http://host/AttendanceHub/public silently becomes http://host/api/... — the application
/// prefix is dropped and every beat 404s against the web server while looking completely
/// correct from this side. Measured on 2026-10-14: the first version of this reporter did
/// exactly that, and the only visible symptom was five 404s per cycle.
/// HttpUploadApiClient.BuildUploadUri exists for the same reason and says so.
///
public static Uri BuildBeatUri(Uri baseAddress)
{
const string path = "/api/v1/sync/heartbeat";
return new Uri(baseAddress.AbsoluteUri.TrimEnd('/') + path);
}
/// Per-device consecutive failure counter: powers rate-limited logging and recovery lines.
private readonly Dictionary _failures = new(StringComparer.OrdinalIgnoreCase);
private readonly object _failureGate = new();
public HeartbeatReporter(
Func> supervisors,
Uri baseAddress,
string apiToken,
int intervalSeconds,
ILogger? log = null,
HttpClient? http = null,
TimeSpan? timeout = null)
{
_supervisors = supervisors;
_baseAddress = baseAddress;
_uri = BuildBeatUri(baseAddress);
_interval = TimeSpan.FromSeconds(Math.Max(1, intervalSeconds));
_timeout = timeout ?? TimeSpan.FromSeconds(10);
_log = log ?? NullLogger.Instance;
_ownsHttp = http is null;
_http = http ?? new HttpClient();
if (_http.BaseAddress is null)
_http.BaseAddress = baseAddress;
_http.Timeout = _timeout;
if (!string.IsNullOrEmpty(apiToken))
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
/// Immediate first beat, then one beat per interval, until the host is cancelled.
/// Failures never escape: the loop outlives any single device or any single request.
public async Task RunAsync(CancellationToken ct)
{
_log.LogInformation(
"HEARTBEAT_START endpoint={Endpoint} intervalSec={I} timeoutSec={T} (liveness reporting only — "
+ "acquisition and delivery are unaffected if this stops)",
_uri, (int)_interval.TotalSeconds, (int)_timeout.TotalSeconds);
while (!ct.IsCancellationRequested)
{
IReadOnlyList snapshot = Array.Empty();
try
{
snapshot = _supervisors() ?? Array.Empty();
}
catch (Exception ex)
{
_log.LogWarning(ex, "HEARTBEAT_SUPERVISOR_LIST_FAILED — beat skipped");
}
var sent = 0;
var failed = 0;
foreach (var supervisor in snapshot)
{
if (ct.IsCancellationRequested) break;
try
{
if (await BeatAsync(supervisor, ct).ConfigureAwait(false)) sent++;
else failed++;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
// A single device must never end the beat for the others.
failed++;
_log.LogWarning(ex, "HEARTBEAT_BEAT_FAILED device={Device}", supervisor.WorkerId);
}
}
// One line per cycle, at Information. This is the reporter's own liveness signal: the
// per-device success line is deliberately Debug (silent in production), so without this
// a healthy reporter and a dead one would look identical in the log — the exact
// flat-line blind spot the delivery watchdog exists to avoid.
if (snapshot.Count > 0)
_log.LogInformation("HEARTBEAT_CYCLE devices={N} sent={Ok} failed={F}",
snapshot.Count, sent, failed);
try
{
await Task.Delay(_interval, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
_log.LogInformation("HEARTBEAT_STOP reason=cancelled");
}
/// One device, one request. Returns true when the backend accepted the beat.
/// Never rethrows anything but cancellation.
private async Task BeatAsync(Supervisor supervisor, CancellationToken ct)
{
var beat = Build(supervisor);
var key = beat.DeviceIp;
using var request = new HttpRequestMessage(HttpMethod.Post, _uri)
{
Content = new StringContent(beat.ToJson(), Encoding.UTF8, "application/json")
};
using var response = await _http.SendAsync(request, ct).ConfigureAwait(false);
var status = (int)response.StatusCode;
if (response.IsSuccessStatusCode)
{
var recovered = false;
lock (_failureGate)
{
recovered = _failures.TryGetValue(key, out var seen) && seen > 0;
_failures.Remove(key);
}
if (recovered)
_log.LogInformation("HEARTBEAT_RECOVERED device={Device} status={Status}", key, beat.Status);
else
_log.LogDebug("HEARTBEAT_OK device={Device} status={Status}", key, beat.Status);
return true;
}
var count = 0;
lock (_failureGate)
{
count = _failures.TryGetValue(key, out var seen) ? seen + 1 : 1;
_failures[key] = count;
}
// 404 is not a network problem: Laravel could not find this ip+port in the tenant's device
// list, so no amount of retrying will start working. Say so instead of retrying quietly.
if (status == (int)HttpStatusCode.NotFound)
{
_log.LogWarning(
"HEARTBEAT_DEVICE_UNKNOWN device={Device} http=404 — the backend has no device with this "
+ "ip+port for the token's tenant. Telemetry will be dropped until the device list agrees.",
key);
return false;
}
if (count == 1 || count % FailureLogEveryNth == 0)
_log.LogWarning("HEARTBEAT_FAIL device={Device} http={Http} consecutive={N}", key, status, count);
return false;
}
/// Map the acquisition snapshot to what the wire says. Public and pure so the mapping —
/// the part that can lie — is unit tested rather than trusted.
public static DeviceHeartbeat Build(Supervisor supervisor)
{
var worker = supervisor.Worker;
var health = worker?.Health;
return Build(
ip: supervisor.Ip,
port: supervisor.Port,
workerPresent: worker is not null,
connected: health?.Connected ?? false,
firmwareVersion: health?.Capability?.Firmware,
userCount: health?.Capability?.UserCount,
logCount: health?.Capability?.AttCount,
lastSuccessfulReadAt: health?.LastReadSuccessAt,
lastReadErrorAt: health?.LastReadFailureAt,
lastReadError: health?.LastReadFailureError,
consecutiveReadFailures: health?.ConsecutiveReadFailures ?? 0,
reconnectCount: supervisor.SessionRecreateCount,
readSuccessCount: health?.ReadsCompleted ?? 0);
}
///
/// Pure mapping. "error" is reserved for the device that accepts a connection but cannot be
/// read — the shape that a plain online/offline pair would hide, and the one real device
/// (172.30.70.5) actually exhibits.
///
public static DeviceHeartbeat Build(
string ip,
int port,
bool workerPresent,
bool connected,
string? firmwareVersion,
int? userCount,
int? logCount,
DateTimeOffset? lastSuccessfulReadAt,
DateTimeOffset? lastReadErrorAt,
string? lastReadError,
int consecutiveReadFailures,
int reconnectCount,
long readSuccessCount)
{
return new DeviceHeartbeat(
DeviceIp: ip,
DevicePort: port,
Status: DeriveStatus(workerPresent, connected, consecutiveReadFailures),
FirmwareVersion: string.IsNullOrWhiteSpace(firmwareVersion) ? null : firmwareVersion,
UserCount: userCount,
LogCount: logCount,
LastSuccessfulReadAt: lastSuccessfulReadAt,
LastReadErrorAt: lastReadErrorAt,
LastReadError: string.IsNullOrWhiteSpace(lastReadError)
? null
: (lastReadError.Length > 500 ? lastReadError[..500] : lastReadError),
ConsecutiveReadFailures: consecutiveReadFailures,
ReadSuccessCount: checked((int)Math.Min(readSuccessCount, int.MaxValue)),
ReconnectCount: reconnectCount);
}
/// Status derivation, isolated so it can be tested against every shape of worker state.
public static string DeriveStatus(bool workerPresent, bool connected, int consecutiveReadFailures)
{
if (!workerPresent || !connected) return "offline";
return consecutiveReadFailures > 0 ? "error" : "online";
}
public ValueTask DisposeAsync()
{
if (_ownsHttp)
_http.Dispose();
return ValueTask.CompletedTask;
}
}