using System.Text.Json;
namespace AttendanceHub.Sync.Configuration;
/// One problem found in the config file. IsError means the host refuses to start.
public sealed record ConfigFinding(bool IsError, string Code, string Message);
///
/// Startup validation for phase1.device.json.
///
/// Why this exists: System.Text.Json silently IGNORES properties that are not modelled, and
/// DeviceWorker silently maps an unknown read.mode to Auto. Every one of those defaults is a
/// way for a typo to be absorbed without a sound. The 2026-10-11 outage was precisely that shape —
/// upload.enabled stopped being honoured and nothing objected — so "the file parsed" is not
/// evidence that the file means what its author thinks it means.
///
/// The validator reads the RAW JSON, not the typed model, because the typed model is the thing
/// that throws information away. Anything it does not recognise is reported, with the nearest
/// known key suggested, so the error tells the operator how to fix it rather than only that
/// something is wrong.
///
/// Keys beginning with '$' are treated as annotations and always allowed: the shipped config uses
/// "$comment" for documentation, and documentation must never fail a deploy.
///
public static class ConfigValidator
{
/// Case-insensitive comparer for key names. Named Cmp, not OrdinalIgnoreCase, so it can
/// never be mistaken for the StringComparison overload that string.Equals takes.
private static readonly StringComparer Cmp = StringComparer.OrdinalIgnoreCase;
private static readonly HashSet RootKeys = NewSet(
"device", "devices", "sdk", "session", "realtime", "read", "supervisor", "persistence",
"upload", "heartbeat");
private static readonly Dictionary> SectionKeys = new(Cmp)
{
["device"] = NewSet("deviceId", "displayName", "ip", "port", "machineNumber", "commKey"),
["devices"] = NewSet("source", "baseAddress", "listPath", "apiToken", "refreshSeconds",
"fallbackToStatic", "machineNumber", "idOverrides"),
["sdk"] = NewSet("commTimeoutSeconds", "expectedSdkVersion"),
["session"] = NewSet("operationTimeoutMs", "connectTimeoutMs"),
["realtime"] = NewSet("eventMask", "channelCapacity"),
["read"] = NewSet("mode", "lookbackMinutes", "maxRecordsPerRead", "failureRetryLimit",
"failureRetryBackoffMs", "tryTimeWindow", "windowedIntervalMs",
"fullReconcileMinutes", "overlapMinutes"),
["supervisor"] = NewSet("reconnectDelayMs", "healthIntervalMs", "readIntervalMs",
"maxReconnectDelayMs", "pingFailThreshold", "readRecreateThreshold",
"liveStaleMinutes"),
["persistence"] = NewSet("dedupeLogEnabled"),
["upload"] = NewSet("enabled", "baseAddress", "batchPath", "apiToken", "deviceId",
"timeoutSeconds", "batchSize", "maxConcurrency", "pollingIntervalMs"),
["heartbeat"] = NewSet("enabled", "intervalSeconds"),
};
/// Accepted values of read.mode. DeviceWorker maps anything else to Auto silently.
private static readonly string[] ReadModes = { "Auto", "TimeWindow", "NewOnly", "LegacyFull" };
private static HashSet NewSet(params string[] keys) => new(keys, Cmp);
public static IReadOnlyList Validate(string json)
{
var findings = new List();
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json, new JsonDocumentOptions
{
CommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
});
}
catch (JsonException ex)
{
findings.Add(new ConfigFinding(true, "JSON_INVALID", $"the file is not valid JSON: {ex.Message}"));
return findings;
}
using (doc)
{
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{
findings.Add(new ConfigFinding(true, "JSON_NOT_OBJECT", "the top level must be a JSON object"));
return findings;
}
CheckUnknownKeys(root, RootKeys, "", findings);
CheckDevice(root, findings);
CheckDevices(root, findings);
CheckSdkSession(root, findings);
CheckRead(root, findings);
CheckSupervisor(root, findings);
CheckUpload(root, findings);
CheckHeartbeat(root, findings);
}
return findings;
}
// ---------- unknown keys ----------
private static void CheckUnknownKeys(JsonElement section, HashSet known, string prefix, List out_findings)
{
foreach (var prop in section.EnumerateObject())
{
if (prop.Name.StartsWith("$", StringComparison.Ordinal))
continue; // $comment and friends are documentation
if (known.Contains(prop.Name))
continue;
var hint = NearestKnown(prop.Name, known);
out_findings.Add(new ConfigFinding(true, "KEY_UNKNOWN",
$"{prefix}{prop.Name} is not a recognised key and will be IGNORED silently."
+ (hint is null ? "" : $" Did you mean \"{hint}\"?")));
}
}
// ---------- sections ----------
private static void CheckDevice(JsonElement root, List f)
{
if (!TrySection(root, "device", out var s)) return;
CheckUnknownKeys(s, SectionKeys["device"], "device.", f);
if (TryString(s, "ip", out var ip) && string.IsNullOrWhiteSpace(ip))
f.Add(new ConfigFinding(true, "DEVICE_IP_EMPTY", "device.ip is empty — the host cannot connect to anything."));
if (TryInt(s, "port", out var port) && (port < 1 || port > 65535))
f.Add(new ConfigFinding(true, "DEVICE_PORT_RANGE", $"device.port={port} is outside 1..65535."));
if (TryInt(s, "machineNumber", out var mn) && mn < 1)
f.Add(new ConfigFinding(true, "DEVICE_MACHINENUMBER", $"device.machineNumber={mn} must be >= 1."));
}
private static void CheckDevices(JsonElement root, List f)
{
if (!TrySection(root, "devices", out var s)) return;
CheckUnknownKeys(s, SectionKeys["devices"], "devices.", f);
Positive(s, "refreshSeconds", "devices.refreshSeconds", f);
if (TryString(s, "source", out var source))
{
if (!string.Equals(source, "laravel", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(source, "static", StringComparison.OrdinalIgnoreCase))
{
f.Add(new ConfigFinding(true, "DEVICES_SOURCE_UNKNOWN",
$"devices.source=\"{source}\" is not understood (laravel|static). "
+ "An unknown source falls back to the single static device without saying so."));
}
// laravel with no address and no fallback = nothing to supervise.
if (string.Equals(source, "laravel", StringComparison.OrdinalIgnoreCase)
&& TryString(s, "baseAddress", out var ba) && string.IsNullOrWhiteSpace(ba)
&& TryBool(s, "fallbackToStatic", out var fallback) && !fallback)
{
f.Add(new ConfigFinding(true, "DEVICES_UNREACHABLE_PLAN",
"devices.source=laravel with an empty baseAddress and fallbackToStatic=false: "
+ "the device list can never be resolved, so the host would supervise nothing."));
}
}
}
private static void CheckSdkSession(JsonElement root, List f)
{
if (TrySection(root, "sdk", out var sdk))
{
CheckUnknownKeys(sdk, SectionKeys["sdk"], "sdk.", f);
Positive(sdk, "commTimeoutSeconds", "sdk.commTimeoutSeconds", f);
}
if (TrySection(root, "session", out var sess))
{
CheckUnknownKeys(sess, SectionKeys["session"], "session.", f);
Positive(sess, "operationTimeoutMs", "session.operationTimeoutMs", f);
Positive(sess, "connectTimeoutMs", "session.connectTimeoutMs", f);
}
if (TrySection(root, "realtime", out var rt))
CheckUnknownKeys(rt, SectionKeys["realtime"], "realtime.", f);
if (TrySection(root, "persistence", out var pers))
CheckUnknownKeys(pers, SectionKeys["persistence"], "persistence.", f);
}
private static void CheckRead(JsonElement root, List f)
{
if (!TrySection(root, "read", out var s)) return;
CheckUnknownKeys(s, SectionKeys["read"], "read.", f);
// Case-SENSITIVE on purpose. DeviceWorker maps these with a C# switch expression, which is
// ordinal: "timewindow" or "Timewindow" falls through to `_ => Auto` silently. Matching that
// behaviour here is the whole point — a case-insensitive check would wave through exactly the
// typos this rule exists to catch.
if (TryString(s, "mode", out var mode) && !ReadModes.Contains(mode, StringComparer.Ordinal))
{
f.Add(new ConfigFinding(true, "READ_MODE_UNKNOWN",
$"read.mode=\"{mode}\" is not one of {string.Join("|", ReadModes)}. "
+ "DeviceWorker would silently substitute Auto, so the mode you asked for is not the mode you get."));
}
Positive(s, "lookbackMinutes", "read.lookbackMinutes", f);
Positive(s, "maxRecordsPerRead", "read.maxRecordsPerRead", f);
Positive(s, "failureRetryBackoffMs", "read.failureRetryBackoffMs", f);
Positive(s, "windowedIntervalMs", "read.windowedIntervalMs", f);
Positive(s, "fullReconcileMinutes", "read.fullReconcileMinutes", f);
if (TryInt(s, "failureRetryLimit", out var frl) && frl < 0)
f.Add(new ConfigFinding(true, "READ_RETRY_NEGATIVE", $"read.failureRetryLimit={frl} must be >= 0."));
if (TryInt(s, "overlapMinutes", out var ov) && ov < 0)
f.Add(new ConfigFinding(true, "READ_OVERLAP_NEGATIVE", $"read.overlapMinutes={ov} must be >= 0 "
+ "(overlap is what makes the watermark safe across device clock skew; it cannot be negative)."));
// fullReconcileMinutes must be able to cover the window it re-reads, or the safety net
// never actually covers the gap it exists to cover.
if (TryInt(s, "fullReconcileMinutes", out var frm) && TryInt(s, "overlapMinutes", out var ovl) && frm <= ovl)
f.Add(new ConfigFinding(true, "READ_RECONCILE_TOO_SHORT",
$"read.fullReconcileMinutes={frm} is not greater than overlapMinutes={ovl}: "
+ "the periodic full pass would never catch up with its own overlap."));
}
private static void CheckSupervisor(JsonElement root, List f)
{
if (!TrySection(root, "supervisor", out var s)) return;
CheckUnknownKeys(s, SectionKeys["supervisor"], "supervisor.", f);
Positive(s, "reconnectDelayMs", "supervisor.reconnectDelayMs", f);
Positive(s, "healthIntervalMs", "supervisor.healthIntervalMs", f);
Positive(s, "readIntervalMs", "supervisor.readIntervalMs", f);
Positive(s, "maxReconnectDelayMs", "supervisor.maxReconnectDelayMs", f);
AtLeast(s, "pingFailThreshold", 1, "supervisor.pingFailThreshold", f);
AtLeast(s, "readRecreateThreshold", 1, "supervisor.readRecreateThreshold", f);
AtLeast(s, "liveStaleMinutes", 1, "supervisor.liveStaleMinutes", f);
if (TryInt(s, "maxReconnectDelayMs", out var maxDelay) && TryInt(s, "reconnectDelayMs", out var delay)
&& delay > maxDelay)
{
f.Add(new ConfigFinding(true, "SUPERVISOR_BACKOFF_INVERTED",
$"supervisor.reconnectDelayMs={delay} exceeds maxReconnectDelayMs={maxDelay}: "
+ "the backoff ceiling is below its own starting value."));
}
}
private static void CheckUpload(JsonElement root, List f)
{
if (!TrySection(root, "upload", out var s)) return;
CheckUnknownKeys(s, SectionKeys["upload"], "upload.", f);
Positive(s, "timeoutSeconds", "upload.timeoutSeconds", f);
AtLeast(s, "batchSize", 1, "upload.batchSize", f);
AtLeast(s, "maxConcurrency", 1, "upload.maxConcurrency", f);
Positive(s, "pollingIntervalMs", "upload.pollingIntervalMs", f);
var enabled = TryBool(s, "enabled", out var e) && e;
if (!enabled) return;
// Delivery is ON: the two things that silently disable it again.
if (TryString(s, "baseAddress", out var ba) && string.IsNullOrWhiteSpace(ba))
f.Add(new ConfigFinding(true, "UPLOAD_ENDPOINT_EMPTY",
"upload.enabled=true but upload.baseAddress is empty — delivery cannot start, "
+ "and a disabled uploader never reports an error: it simply stops trying."));
else if (TryString(s, "baseAddress", out var url) && !Uri.TryCreate(url, UriKind.Absolute, out _))
f.Add(new ConfigFinding(true, "UPLOAD_ENDPOINT_INVALID",
$"upload.baseAddress=\"{url}\" is not an absolute URL."));
if (TryString(s, "apiToken", out var tok) && string.IsNullOrWhiteSpace(tok))
f.Add(new ConfigFinding(true, "UPLOAD_TOKEN_EMPTY",
"upload.enabled=true but upload.apiToken is empty — every batch will be rejected."));
}
///
/// Heartbeat reporting is the only subsystem whose failure is invisible on its own side: if the
/// cadence is too slow, Laravel simply keeps judging the device offline and nothing here objects.
/// That is exactly the shape of the 2026-10-11 outage, so the two ways to be silently useless
/// (too slow, or enabled with no endpoint to send to) are refused here rather than discovered
/// later in a dashboard that has been showing "offline" all along.
///
private static void CheckHeartbeat(JsonElement root, List f)
{
if (!TrySection(root, "heartbeat", out var s)) return;
CheckUnknownKeys(s, SectionKeys["heartbeat"], "heartbeat.", f);
if (!TryBool(s, "enabled", out var enabled) || !enabled) return;
if (TryInt(s, "intervalSeconds", out var interval) && interval > 0
&& interval >= HeartbeatConfig.LaravelOnlineThresholdSeconds)
{
f.Add(new ConfigFinding(true, "HEARTBEAT_INTERVAL_TOO_SLOW",
$"heartbeat.intervalSeconds={interval} is not below Laravel's {HeartbeatConfig.LaravelOnlineThresholdSeconds}s "
+ "online threshold (Device::isOnline reads last_seen_at within 120s). Every beat would be "
+ "recorded and every device would still show offline — reporting that works and convinces nobody."));
}
// The heartbeat rides on the delivery endpoint (same base address, same token). Delivery off
// means nothing to send with, and a reporter that cannot reach its endpoint is not reporting.
if (!TrySection(root, "upload", out var upload))
{
f.Add(new ConfigFinding(true, "HEARTBEAT_NO_UPLOAD_SECTION",
"heartbeat.enabled=true but there is no upload section: the heartbeat shares the upload "
+ "endpoint and token, so it has no way to reach the backend."));
}
else if (!(TryBool(upload, "enabled", out var uploadEnabled) && uploadEnabled))
{
f.Add(new ConfigFinding(true, "HEARTBEAT_REQUIRES_UPLOAD",
"heartbeat.enabled=true but upload.enabled is not true. Either turn delivery on, or turn "
+ "the heartbeat off — an enabled reporter with no delivery path reports nothing."));
}
}
// ---------- helpers ----------
private static bool TrySection(JsonElement root, string name, out JsonElement section)
{
section = default;
foreach (var p in root.EnumerateObject())
{
if (Cmp.Equals(p.Name, name))
{
section = p.Value;
return section.ValueKind == JsonValueKind.Object;
}
}
return false;
}
private static bool TryInt(JsonElement s, string name, out int value)
{
value = 0;
foreach (var p in s.EnumerateObject())
{
if (!Cmp.Equals(p.Name, name)) continue;
if (p.Value.ValueKind == JsonValueKind.Number && p.Value.TryGetInt32(out value)) return true;
if (p.Value.ValueKind == JsonValueKind.String && int.TryParse(p.Value.GetString(), out value)) return true;
return false;
}
return false;
}
private static bool TryBool(JsonElement s, string name, out bool value)
{
value = false;
foreach (var p in s.EnumerateObject())
{
if (!Cmp.Equals(p.Name, name)) continue;
if (p.Value.ValueKind is JsonValueKind.True or JsonValueKind.False)
{
value = p.Value.GetBoolean();
return true;
}
return false;
}
return false;
}
private static bool TryString(JsonElement s, string name, out string value)
{
value = "";
foreach (var p in s.EnumerateObject())
{
if (!Cmp.Equals(p.Name, name)) continue;
if (p.Value.ValueKind == JsonValueKind.String)
{
value = p.Value.GetString() ?? "";
return true;
}
return false;
}
return false;
}
private static void Positive(JsonElement s, string key, string label, List f)
{
if (TryInt(s, key, out var v) && v <= 0)
f.Add(new ConfigFinding(true, "INTERVAL_NOT_POSITIVE",
$"{label}={v} must be greater than zero — a non-positive interval is an undefined cadence, not a slow one."));
}
private static void AtLeast(JsonElement s, string key, int min, string label, List f)
{
if (TryInt(s, key, out var v) && v < min)
f.Add(new ConfigFinding(true, "VALUE_OUT_OF_RANGE", $"{label}={v} must be >= {min}."));
}
/// Closest known key by edit distance, for a typo hint. Empty when nothing is plausibly close.
private static string? NearestKnown(string actual, HashSet known)
{
string? best = null;
var bestScore = int.MaxValue;
foreach (var k in known)
{
var d = EditDistance(actual, k);
if (d < bestScore)
{
bestScore = d;
best = k;
}
}
// Only suggest when it really is a small change; otherwise the hint is noise.
var threshold = Math.Max(2, actual.Length / 3);
return best is not null && bestScore <= threshold ? best : null;
}
private static int EditDistance(string a, string b)
{
var n = a.Length;
var m = b.Length;
if (n == 0) return m;
if (m == 0) return n;
var prev = new int[m + 1];
var cur = new int[m + 1];
for (var j = 0; j <= m; j++) prev[j] = j;
for (var i = 1; i <= n; i++)
{
cur[0] = i;
for (var j = 1; j <= m; j++)
{
var cost = char.ToUpperInvariant(a[i - 1]) == char.ToUpperInvariant(b[j - 1]) ? 0 : 1;
cur[j] = Math.Min(Math.Min(cur[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);
}
(prev, cur) = (cur, prev);
}
return prev[m];
}
}