using System.Diagnostics; using System.Text.Json; using AttendanceHub.Sync.Com; using AttendanceHub.Sync.Configuration; using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Reconciliation; using Microsoft.Extensions.Logging; namespace AttendanceHub.Sync.Soak; /// /// Multi-hour Phase 2 soak: periodic functional read + active RegEvent + generation telemetry. /// No SQLite, no Laravel, no upload, no cursor persistence. /// public static class Program { public static async Task Main(string[] args) { using var loggerFactory = LoggerFactory.Create(b => b.AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss.fff "; }).SetMinimumLevel(LogLevel.Information)); var log = loggerFactory.CreateLogger("Soak"); var hours = 4.0; foreach (var a in args) { if (a.StartsWith("--hours=") && double.TryParse(a.Split('=')[1], out var h)) hours = h; } var configPath = @"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\config\phase1.device.json"; var cfg = Phase1ConfigLoader.Load(configPath); var outPath = @"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\_phase2\soak_results.jsonl"; Directory.CreateDirectory(Path.GetDirectoryName(outPath)!); var summaryPath = @"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\_phase2\soak_summary.json"; var startedAt = DateTimeOffset.UtcNow; var deadline = startedAt.AddHours(hours); log.LogInformation("SOAK_START hours={H} until={Until} device={Dev} out={Out}", hours, deadline, cfg.Device.DeviceId, outPath); await using var session = new ComSession(cfg.Device.DeviceId, cfg.Device.Ip, cfg.Device.Port, cfg.Device.MachineNumber, cfg.Sdk.CommTimeoutSeconds, loggerFactory.CreateLogger("ComSession")); await session.InitializeAsync(); var probe = new ReadApiProbeService(session, cfg.Device.DeviceId, log); int rtCount = 0, reads = 0, comEx = 0, ownerViolations = 0, unexpectedGen = 0, readFail = 0, reconnects = 0; var gens = new HashSet(); var lastGen = 0; var moduleCheck = new List(); session.AttendanceReceived += _ => { Interlocked.Increment(ref rtCount); }; var connect = await session.ConnectAsync(); if (!connect.Success) { log.LogError("SOAK_CONNECT_FAIL {Err}", connect.Error); return 3; } await session.RegEventAsync(cfg.Realtime.EventMask); lastGen = session.Generation; gens.Add(lastGen); // Prove loaded modules once using (var proc = Process.GetCurrentProcess()) { proc.Refresh(); foreach (ProcessModule m in proc.Modules) { if (m.FileName.Contains("zkem", StringComparison.OrdinalIgnoreCase)) moduleCheck.Add($"{m.FileName} {new FileInfo(m.FileName).Length}"); } } var interval = TimeSpan.FromSeconds(90); while (DateTimeOffset.UtcNow < deadline) { try { var h = await session.GetFunctionalHealthAsync(); reads++; if (!h.FunctionalReadOk) readFail++; if (session.Info.OwnerThreadId != session.Info.OwnerThreadId) ownerViolations++; // always 0; real check is AssertOwnerThread inside ComSession if (session.Generation != lastGen) { if (!gens.Contains(session.Generation)) unexpectedGen++; lastGen = session.Generation; gens.Add(lastGen); } var sample = new { ts = DateTimeOffset.UtcNow, state = "soak", gen = session.Generation, ownerThread = session.Info.OwnerThreadId, apt = session.Info.ApartmentState, connected = h.Connected, infoOk = h.DeviceInfoOk, readOk = h.FunctionalReadOk, readApi = h.ReadApiUsed, logs = h.LogsEnumerated, readMs = h.ReadDurationMs, sdkErr = h.SdkError, rtCount, reads, readFail, comEx, unexpectedGen, users = h.Capability?.UserCount, attCount = h.Capability?.AttCount }; await File.AppendAllTextAsync(outPath, JsonSerializer.Serialize(sample) + "\n"); log.LogInformation( "SOAK_TICK gen={Gen} owner={Ow} readOk={R} api={Api} ms={Ms} rt={Rt} reads={N} fail={F} att={Att}", session.Generation, session.Info.OwnerThreadId, h.FunctionalReadOk, h.ReadApiUsed, h.ReadDurationMs, rtCount, reads, readFail, h.Capability?.AttCount); } catch (System.Runtime.InteropServices.COMException ex) { comEx++; log.LogError(ex, "SOAK_COM_EXCEPTION — recreate session"); try { await session.RecreateSessionAsync(); reconnects++; lastGen = session.Generation; gens.Add(lastGen); } catch (Exception rex) { log.LogError(rex, "SOAK_RECREATE_FAIL"); } } catch (Exception ex) { log.LogError(ex, "SOAK_ERROR"); try { await session.ConnectAsync(); await session.RegEventAsync(cfg.Realtime.EventMask); reconnects++; } catch { // keep looping } } var delay = interval; try { await Task.Delay(delay); } catch (OperationCanceledException) { break; } } var summary = new { startedAt, completedAt = DateTimeOffset.UtcNow, hours, deviceId = cfg.Device.DeviceId, ownerThreadFinal = session.Info.OwnerThreadId, apartment = session.Info.ApartmentState, generations = gens.OrderBy(x => x).ToArray(), reads, readFail, rtCount, comExceptions = comEx, ownerViolations, unexpectedGenerationChanges = unexpectedGen, reconnects, moduleCheck, passed = comEx == 0 && ownerViolations == 0 && unexpectedGen == 0 && readFail == 0 }; await File.WriteAllTextAsync(summaryPath, JsonSerializer.Serialize(summary, new JsonSerializerOptions { WriteIndented = true })); log.LogInformation("SOAK_DONE passed={Passed} reads={Reads} rt={Rt} comEx={Ex} gens={Gens}", summary.passed, reads, rtCount, comEx, string.Join(",", summary.generations)); await session.DisconnectAsync(); return 0; } }