using System.Text;
using System.Text.Json;
using AttendanceHub.Sync.Configuration;
using AttendanceHub.Sync.Oversight;
using AttendanceHub.Sync.Persistence.Sqlite;
using AttendanceHub.Sync.Upload;
using AttendanceHub.Sync.Workers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace AttendanceHub.Sync.Host;
///
/// Phase 1 console host (Windows service installer intentionally out of scope).
/// Host → DeviceRegistry (dynamic device list) → SyncHub → Supervisor(s) → DeviceWorker
/// → exclusive STA COM owner(s) → CZKEM → Connect/RegEvent/Read/Telemetry.
/// One process supervises ANY number of devices: the count comes from the resolved device list
/// (Laravel API by default, static config as fallback) and can change at runtime.
///
public static class Program
{
public static async Task Main(string[] args)
{
// Service mode: route ALL console output (structured logs included) to a durable file,
// because a Windows service has no console. Interactive/console runs are untouched.
// Size-based rotation (32 MB × 3 files ceiling) so the log cannot grow unbounded.
if (!Environment.UserInteractive)
{
var svcLogDir = Path.Combine(AppContext.BaseDirectory, "logs");
Directory.CreateDirectory(svcLogDir);
var svcLogPath = Path.Combine(svcLogDir, "attendancehub_sync.log");
var svcWriter = new RotatingFileWriter(svcLogPath);
Console.SetOut(svcWriter);
Console.SetError(svcWriter);
Console.WriteLine($"{DateTimeOffset.UtcNow:o} SERVICE_CONSOLE_REDIRECT path={svcLogPath} rotationBytes={RotatingFileWriter.DefaultMaxBytes} keep={RotatingFileWriter.DefaultKeep}");
}
var configPath = args.FirstOrDefault(a => a.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
?? FindDefaultConfig();
if (configPath is null || !File.Exists(configPath))
{
Console.Error.WriteLine("ERROR: phase1.device.json not found. Pass a path or place config/phase1.device.json beside the host.");
return 2;
}
// ---------- Config validation: BEFORE the SCM handshake, deliberately ----------
// A service that refuses to start must never have reported SERVICE_RUNNING, or its refusal
// is indistinguishable from a healthy start to anything watching the SCM. Console is already
// redirected to the durable log in service mode (above), so these lines still land on disk.
//
// The findings are all cases where the file does not mean what its author thinks it means:
// unknown keys that System.Text.Json would swallow, non-positive intervals, an unreadable
// read.mode. Running anyway is what the 2026-10-11 outage looked like, so the host exits
// instead — loudly, and before touching a single device.
var configFindings = ConfigValidator.Validate(File.ReadAllText(configPath));
foreach (var finding in configFindings)
{
var stamp = $"{DateTimeOffset.UtcNow:o}";
if (finding.IsError)
Console.Error.WriteLine($"{stamp} FATAL CONFIG_INVALID code={finding.Code} {finding.Message}");
else
Console.WriteLine($"{stamp} warn CONFIG_WARN code={finding.Code} {finding.Message}");
}
if (configFindings.Any(f => f.IsError))
{
Console.Error.WriteLine(
$"{DateTimeOffset.UtcNow:o} CONFIG_REJECTED — refusing to start rather than run on a config "
+ $"that does not mean what it says ({configFindings.Count(f => f.IsError)} error(s) above). "
+ "Nothing has been connected to and no punch has been read. Fix the findings and restart.");
return 3;
}
// SCM integration — V2 plan §P designates AttendanceHub.Sync.Host as the "Windows service host"
// (DI / config / lifetime). UseWindowsService is a no-op for interactive console runs.
// (Fully-qualified: the `Host` namespace segment would otherwise collide with the Host class.)
var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
.UseWindowsService(o => o.ServiceName = "ZKTecoSyncService")
.Build();
await host.StartAsync(); // SCM handshake -> SERVICE_RUNNING
try
{
using var loggerFactory = LoggerFactory.Create(b =>
{
b.AddSimpleConsole(o =>
{
o.SingleLine = true;
o.TimestampFormat = "HH:mm:ss.fff ";
});
b.SetMinimumLevel(LogLevel.Information);
});
var log = loggerFactory.CreateLogger("Host");
var config = Phase1ConfigLoader.Load(configPath);
// Delivery activation (SQLite -> Laravel): parse existing "upload" section.
// enabled=false => null => no uploader constructed (controlled activation).
UploadConfig? uploadCfg = null;
try
{
uploadCfg = UploadRuntime.ParseFromFile(configPath);
}
catch (Exception ex)
{
log.LogError(ex, "UPLOAD_CONFIG_PARSE_FAILED — delivery stays disabled, acquisition unaffected");
}
// Device list source (dynamic by default: Laravel is the single source of truth).
var devicesCfg = DevicesConfigParser.ParseFromFile(configPath);
if (devicesCfg is not null)
{
if (string.IsNullOrWhiteSpace(devicesCfg.BaseAddress) && uploadCfg is not null)
devicesCfg.BaseAddress = uploadCfg.BaseAddress.AbsoluteUri;
if (string.IsNullOrWhiteSpace(devicesCfg.ApiToken) && uploadCfg is not null)
devicesCfg.ApiToken = uploadCfg.ApiToken;
}
log.LogInformation(
"PHASE1_HOST_START config={Config} staticDevice={Device} {Ip}:{Port} deviceSource={Src} refreshSec={Ref}",
configPath, config.Device.DeviceId, config.Device.Ip, config.Device.Port,
devicesCfg?.Source ?? "static", devicesCfg?.RefreshSeconds ?? 0);
// Heartbeat reporting (liveness to the backend's existing /sync/heartbeat). Parsed here,
// before the plan is printed, so the plan states whether this host will report at all.
var heartbeatCfg = HeartbeatConfig.ParseFromFile(configPath);
// Production composition: Host -> SyncHub -> Supervisor -> DeviceRuntime -> DeviceWorker
// -> LivePunchIngress (LIVE) + ReconciliationPersistence (READ) -> ISyncStore (SQLite outbox)
// canonical identity = device_id | personnel_code | punch_time_device_local
var dbPath = Path.Combine(AppContext.BaseDirectory, "attendancehub_v2.db");
var dedupeLogEnabled = ReadDedupeLogFlag(configPath);
await using var store = new SQLiteSyncStore(dbPath, loggerFactory.CreateLogger("Sqlite"), dedupeLogEnabled);
await store.InitializeAsync();
log.LogInformation(
"PHASE1_PERSISTENCE_WIRED db={Db} dedupeLog={Dedupe} identity=device_id|personnel_code|punch_time_device_local paths=LIVE_ingress+READ_reconciliation",
dbPath, dedupeLogEnabled);
await using var hub = new SyncHub(config, loggerFactory, store, TimeSpan.FromMinutes(5));
using var cts = new CancellationTokenSource();
if (Environment.UserInteractive)
{
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
log.LogInformation("HOST_CANCEL requested");
cts.Cancel();
};
}
// SCM STOP -> ApplicationStopping -> cancel the runtime loop -> finally: host.StopAsync -> SERVICE_STOPPED.
host.Services.GetRequiredService().ApplicationStopping.Register(() =>
{
log.LogInformation("HOST_STOP_SIGNAL source=SCM");
cts.Cancel();
});
// ---------- Device list resolution (dynamic count from Laravel) ----------
var staticDevice = config.Device;
IReadOnlyList initialDevices = new[] { staticDevice };
DeviceRegistry? registry = null;
HttpClient? registryHttp = null;
try
{
if (devicesCfg is not null && string.Equals(devicesCfg.Source, "laravel", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrWhiteSpace(devicesCfg.BaseAddress))
{
registryHttp = new HttpClient
{
BaseAddress = new Uri(devicesCfg.BaseAddress),
Timeout = TimeSpan.FromSeconds(Math.Max(5, devicesCfg.RefreshSeconds / 2))
};
registry = new DeviceRegistry(devicesCfg, registryHttp, staticDevice,
loggerFactory.CreateLogger());
initialDevices = await registry.RefreshAsync(cts.Token);
// Runtime add/remove: Laravel decides the device set, the hub applies the diff.
registry.Updated += devices => _ = Task.Run(async () =>
{
try
{
await hub.ApplyAsync(devices, cts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested) { }
catch (Exception ex)
{
log.LogError(ex, "DEVICE_APPLY_FAILED — previous device set kept");
}
}, CancellationToken.None);
await registry.StartAsync(cts.Token);
}
else
{
log.LogInformation(
"DEVICE_REGISTRY_SKIPPED source={Src} baseAddress=\"{Ba}\" — static device list in effect (count=1)",
devicesCfg?.Source ?? "(no devices section)", devicesCfg?.BaseAddress ?? "");
}
}
catch (Exception ex)
{
log.LogError(ex, "DEVICE_REGISTRY_START_FAILED — falling back to the static device list");
}
if (initialDevices.Count == 0)
{
log.LogWarning("DEVICE_LIST_EMPTY — falling back to the static device {Device}", staticDevice.DeviceId);
initialDevices = new[] { staticDevice };
}
await hub.ApplyAsync(initialDevices, cts.Token);
log.LogInformation("DEVICES_ACTIVE count={N} ids={Ids}", hub.DeviceIds.Count, string.Join(",", hub.DeviceIds));
// ---------- State the plan, loudly, before doing anything with it ----------
// Everything after this point is healthy-looking on its own. The plan is the only line that
// says what the host was supposed to be doing, so a reader can tell "delivery off" from
// "delivery broken" without reconstructing it from absence.
EffectivePlan.Print(log, staticDevice, devicesCfg, hub.DeviceIds, uploadCfg,
heartbeatCfg, config.Read, config.Supervisor, config.Sdk, dbPath);
// ---------- Delivery loop: EXISTING UploadWorker over the EXISTING outbox (store + HTTP only).
// Independent of acquisition: no COM/SDK call; failures are contained inside UploadRuntime.
// Device set is dynamic: every cycle re-reads the ids currently supervised by the hub.
UploadRuntime? uploadRuntime = null;
Task uploadTask = Task.CompletedTask;
if (uploadCfg is not null)
{
try
{
var uploadHttp = new HttpClient
{
BaseAddress = uploadCfg.BaseAddress,
Timeout = uploadCfg.Timeout
};
var deviceIdMap = BuildDeviceIdMap(config, devicesCfg);
var uploadClient = new HttpUploadApiClient(uploadHttp, new UploadClientOptions
{
BaseAddress = uploadCfg.BaseAddress,
ApiToken = uploadCfg.ApiToken,
BatchPath = uploadCfg.BatchPath,
Timeout = uploadCfg.Timeout,
BatchSize = uploadCfg.BatchSize,
MaxConcurrency = uploadCfg.MaxConcurrency,
// Upload-layer identity only (records[].device_id for Laravel).
PayloadDeviceId = uploadCfg.DeviceId,
// Per-device map (local id -> devices.ip): required once more than one device
// shares the outbox, otherwise every record would be attributed to one device.
DeviceIdMap = deviceIdMap
}, loggerFactory.CreateLogger());
uploadRuntime = new UploadRuntime(store, uploadClient,
loggerFactory.CreateLogger(), RetryPolicy.Default, uploadHttp);
log.LogInformation(
"UPLOAD_ACTIVATED endpoint={Endpoint} batchSize={B} maxConcurrency={C} pollMs={P} timeoutSec={T} deviceMap={M} (token configured — value not logged)",
new Uri(uploadCfg.BaseAddress, uploadCfg.BatchPath), uploadCfg.BatchSize,
uploadCfg.MaxConcurrency, uploadCfg.PollingIntervalMs,
(int)uploadCfg.Timeout.TotalSeconds,
deviceIdMap.Count == 0 ? "(identity)" : string.Join(",", deviceIdMap.Select(kv => kv.Key + "->" + kv.Value)));
uploadTask = Task.Run(() => uploadRuntime.RunAsync(
() => hub.DeviceIds, uploadCfg.BatchSize, uploadCfg.PollingIntervalMs, cts.Token),
CancellationToken.None);
}
catch (Exception ex)
{
log.LogError(ex, "UPLOAD_ACTIVATION_FAILED — delivery disabled, acquisition unaffected");
uploadRuntime = null;
uploadTask = Task.CompletedTask;
}
}
else
{
// WARNING, not Information: an acquisition-only host still connects, still reads,
// still logs healthy DUAL_HEALTH lines and still writes every punch to the ledger —
// so NOTHING looks wrong while attendance silently stops reaching MySQL. Every row
// accumulates as Pending with upload_attempts=0, because a disabled uploader never
// even tries, and the ledger's Pending count is not surfaced anywhere by default.
// That combination is what let a config copy disable delivery for a full morning
// without a single error in the log. Make it loud.
log.LogWarning(
"UPLOAD_INACTIVE — upload.enabled=false or section missing. This host is ACQUISITION-ONLY: "
+ "punches will be captured to the local ledger but NEVER delivered to the API/MySQL. "
+ "If delivery is expected, fix the upload section in the config this process loaded and restart.");
}
// ---------- Delivery watchdog: STARTED UNCONDITIONALLY.
// Deliberately not nested inside the uploadCfg branch above. The outage it exists to catch is
// "the uploader is not running at all", and a watchdog guarded by the same condition as the
// uploader cannot observe that: it would be switched off by exactly the misconfiguration it is
// supposed to report. It watches ledger backlog growth, so it stays correct whether delivery is
// disabled, failing, hung, or healthy.
var deliveryWatchdog = new DeliveryWatchdog(
store, () => hub.DeviceIds, loggerFactory.CreateLogger());
deliveryWatchdog.Start(cts.Token);
// ---------- Heartbeat reporting: liveness to the backend's EXISTING /sync/heartbeat ----------
// Separate loop, same posture as the watchdog: it borrows the workers' own health snapshots,
// performs no COM/SDK call and writes nothing to the ledger, so it cannot delay, fail or
// falsify acquisition or delivery. Enabled only when asked for — the host must not invent
// reporting, and a heartbeat nobody configured is a request nobody wanted.
HeartbeatReporter? heartbeatReporter = null;
Task heartbeatTask = Task.CompletedTask;
if (heartbeatCfg.Enabled && uploadCfg is not null)
{
try
{
heartbeatReporter = new HeartbeatReporter(
() => hub.Supervisors,
uploadCfg.BaseAddress,
uploadCfg.ApiToken,
heartbeatCfg.IntervalSeconds,
loggerFactory.CreateLogger());
heartbeatTask = Task.Run(() => heartbeatReporter.RunAsync(cts.Token), CancellationToken.None);
}
catch (Exception ex)
{
log.LogError(ex,
"HEARTBEAT_ACTIVATION_FAILED — liveness reporting disabled, acquisition and delivery unaffected");
heartbeatReporter = null;
heartbeatTask = Task.CompletedTask;
}
}
else if (heartbeatCfg.Enabled)
{
// WARNING, not Information: an enabled reporter with no delivery path has no endpoint
// and no token, so it cannot say anything. That must not look like a working setup.
log.LogWarning(
"HEARTBEAT_INACTIVE — heartbeat.enabled=true but the upload section is missing or disabled, "
+ "so there is no endpoint or token to report with. Devices will appear offline in the panel "
+ "even while acquisition is healthy.");
}
// ---------- Ledger hygiene: prune delivered punches older than retention + stale DLQ, then VACUUM.
// Store-only maintenance; first pass ~90s after start (deploy-time cleanup), then once per 24h.
var ledgerMaintenance = new LedgerMaintenance(store, loggerFactory.CreateLogger());
Task ledgerTask = Task.Run(() => ledgerMaintenance.RunAsync(cts.Token), CancellationToken.None);
// Interactive harness commands (multi-device).
log.LogInformation("COMMANDS: status | read | recreate | devices | rt | quit");
while (!cts.IsCancellationRequested)
{
if (Console.IsInputRedirected)
{
// headless: run until cancelled
try { await Task.Delay(1000, cts.Token); }
catch (OperationCanceledException) { break; }
continue;
}
Console.Write("phase1> ");
var line = Console.ReadLine();
if (line is null) break;
switch (line.Trim().ToLowerInvariant())
{
case "status":
foreach (var supervisor in hub.Supervisors)
{
var w = supervisor.Worker;
if (w is null) continue;
var h = w.Health;
log.LogInformation(
"STATUS device={Device} state={State} connected={C} reads={Rd} err={Err} gen={Gen}",
h.DeviceInfoOk is true ? supervisor.WorkerId : supervisor.WorkerId, h.State, h.Connected,
h.ReadsCompleted, h.LastError, h.LiveGeneration);
log.LogInformation(
"DUAL_STATUS device={Device} live={LC}/{LG}/pump={LP} lastLiveEvent={LE} readEv={REV} pingFail={PF} window={WS} lastFull={LFu} read={RC}/{RG}/pump={RP} lastReadOk={LS} lastCount={N} lastReadMs={Ms} consecFail={CF} liveStale={LSt}",
supervisor.WorkerId, h.LiveConnected, h.LiveGeneration, h.LivePumpAlive, h.LastLiveEventAt,
h.ReadSessionEvents, h.LivePingFailures + h.ReadPingFailures, h.WindowedReads, h.LastFullReadAt,
h.ReadConnected, h.ReadGeneration, h.ReadPumpAlive, h.LastReadSuccessAt,
h.LastReadRecordCount, h.LastReadDurationMs, h.ConsecutiveReadFailures, h.LiveStaleOccurrences);
}
break;
case "read":
foreach (var supervisor in hub.Supervisors)
{
var w = supervisor.Worker;
if (w is null) continue;
var r = await w.ReadOnceAsync();
log.LogInformation("READ device={Device} status={Status} api={Api} count={Count} ms={Ms} err={Err}",
supervisor.WorkerId, r.Status, r.ApiUsed, r.Records.Count, r.ElapsedMs, r.Error);
foreach (var rec in r.Records.Take(5))
log.LogInformation(" punch pin={Pin} {Y}-{Mo:00}-{D:00} {H:00}:{Mi:00}:{S:00} state={St} verify={V}",
rec.PersonnelCode, rec.Year, rec.Month, rec.Day, rec.Hour, rec.Minute, rec.Second,
rec.AttendanceState, rec.VerifyMethod);
}
break;
case "recreate":
await hub.ForEachAsync(s => s.ForceRecreateAsync(), cts.Token);
break;
case "devices":
log.LogInformation("DEVICES count={N} ids={Ids}", hub.DeviceIds.Count, string.Join(",", hub.DeviceIds));
break;
case "rt":
foreach (var supervisor in hub.Supervisors)
{
var w = supervisor.Worker;
if (w is null) continue;
log.LogInformation("RT device={Device} total={N} readSessionEv={R} staleRejected={S}",
supervisor.WorkerId, w.Health.RealtimeReceived, w.Health.ReadSessionEvents,
w.StaleGenerationRejections);
}
break;
case "quit":
case "exit":
cts.Cancel();
break;
default:
if (!string.IsNullOrWhiteSpace(line))
Console.WriteLine("commands: status | read | recreate | devices | rt | quit");
break;
}
}
// Graceful delivery shutdown: loop exits on the same cancellation as acquisition.
try
{
await uploadTask.WaitAsync(TimeSpan.FromSeconds(35));
}
catch (Exception ex)
{
log.LogWarning(ex, "UPLOAD_LOOP_STOP_TIMEOUT (best effort)");
}
try
{
await ledgerTask.WaitAsync(TimeSpan.FromSeconds(10));
}
catch (Exception ex)
{
log.LogWarning(ex, "LEDGER_MAINTENANCE_STOP_TIMEOUT (best effort)");
}
if (uploadRuntime is not null)
await uploadRuntime.DisposeAsync();
try
{
// The watchdog exits on the same cancellation as acquisition; bound the wait so a stuck
// sample can never hold up shutdown, then log the final per-device backlog state.
await deliveryWatchdog.DisposeAsync();
}
catch (Exception ex)
{
log.LogWarning(ex, "DELIVERY_WATCHDOG_STOP_TIMEOUT (best effort)");
}
try
{
// Same cancellation as acquisition; bounded so a slow beat cannot hold up shutdown.
await heartbeatTask.WaitAsync(TimeSpan.FromSeconds(15));
}
catch (Exception ex)
{
log.LogWarning(ex, "HEARTBEAT_LOOP_STOP_TIMEOUT (best effort)");
}
if (heartbeatReporter is not null)
await heartbeatReporter.DisposeAsync();
if (registry is not null)
await registry.DisposeAsync();
registryHttp?.Dispose();
log.LogInformation("PHASE1_HOST_STOP devices={N}", hub.DeviceIds.Count);
return 0;
}
finally
{
// SCM handshake completion -> SERVICE_STOPPED.
await host.StopAsync();
}
}
///
/// Local acquisition id → Laravel identity (devices.ip) for records[].device_id.
/// Devices whose local id already equals the ip need no entry (they map to themselves),
/// so the map only ever contains the ids that would otherwise be unrecognised by Laravel.
///
private static IReadOnlyDictionary BuildDeviceIdMap(
Phase1DeviceConfig config, DevicesConfig? devicesCfg)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(config.Device.Ip) &&
!string.Equals(config.Device.DeviceId, config.Device.Ip, StringComparison.OrdinalIgnoreCase))
map[config.Device.DeviceId] = config.Device.Ip;
if (devicesCfg is not null)
{
foreach (var (ip, localId) in devicesCfg.IdOverrides)
{
if (string.IsNullOrWhiteSpace(localId) || string.IsNullOrWhiteSpace(ip))
continue;
map[localId] = ip;
}
}
return map;
}
///
/// Optional "persistence.dedupeLogEnabled": when false (default) duplicate observations are
/// counted but not appended to ingest_dedupe_log. That table is observability-only and a full
/// reconciliation pass over a 50k-record buffer would otherwise write ~50k rows per cycle.
///
private static bool ReadDedupeLogFlag(string configPath)
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(configPath));
if (doc.RootElement.TryGetProperty("persistence", out var p) &&
p.TryGetProperty("dedupeLogEnabled", out var v))
return v.ValueKind == JsonValueKind.True;
}
catch (Exception)
{
// malformed section => default (efficient) behaviour
}
return false;
}
private static string? FindDefaultConfig()
{
var candidates = new[]
{
Path.Combine(AppContext.BaseDirectory, "config", "phase1.device.json"),
Path.Combine(AppContext.BaseDirectory, "phase1.device.json"),
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "config", "phase1.device.json")),
Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "config", "phase1.device.json")),
@"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\config\phase1.device.json"
};
return candidates.FirstOrDefault(File.Exists);
}
}