using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace ZKTecoSyncService.Tests;
///
/// TEST_LIVE24H_RT_HEALTH — Long-Lived Session Stability Observation
///
/// Observes a SINGLE CZKEMClass instance for extended duration with:
/// Connect_Net → RegEvent(65535) → OnAttTransactionEx (live callback)
/// Periodic ReadRTLog / GetRTLog probes (NO ReadGeneralLogData / SSR_GetGeneralLogData)
///
/// NO automatic recovery. NO SQLite. NO HTTP. NO Upload. NO reconciliation.
/// NO production code. Pure COM SDK observation.
///
/// Purpose: Prove or disprove that one CZKEM instance can hold a stable live session
/// while periodically probing with ReadRTLog/GetRTLog.
///
/// Usage:
/// dotnet test --filter "FullyQualifiedName~TEST_LIVE24H_RT_HEALTH"
///
/// Environment:
/// TestDevice:Ip — device IP (default: 172.20.30.221)
/// TestDevice:Port — device port (default: 4370)
/// TestDevice:CommKey — comm key (default: 0)
/// TestDevice:MachineNumber — machine number (default: 1)
/// TEST_DURATION_HOURS — test duration in hours (default: 24)
/// RT_PROBE_INTERVAL_SEC — ReadRTLog/GetRTLog interval in seconds (default: 30)
///
public class TEST_LIVE24H_RT_HEALTH
{
private readonly ITestOutputHelper _output;
private readonly string _ip;
private readonly int _port;
private readonly int _commKey;
private readonly int _machine;
private readonly double _durationHours;
private readonly int _rtProbeIntervalSec;
public TEST_LIVE24H_RT_HEALTH(ITestOutputHelper output)
{
_output = output;
_ip = Environment.GetEnvironmentVariable("TestDevice:Ip") ?? "172.20.30.221";
_port = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:Port"), out var p) ? p : 4370;
_commKey = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:CommKey"), out var k) ? k : 0;
_machine = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:MachineNumber"), out var m) ? m : 1;
_durationHours = double.TryParse(Environment.GetEnvironmentVariable("TEST_DURATION_HOURS"), out var h) ? h : 24;
_rtProbeIntervalSec = int.TryParse(Environment.GetEnvironmentVariable("RT_PROBE_INTERVAL_SEC"), out var s) ? s : 30;
}
private void Log(string msg)
{
Console.WriteLine(msg);
_output.WriteLine(msg);
}
// ═══════════════════════════════════════════════════════════════════
// Metrics — using long fields for Interlocked safety
// ═══════════════════════════════════════════════════════════════════
private sealed class Metrics
{
public DateTime SessionStart { get; set; }
public DateTime SessionEnd { get; set; }
public int ConnectNetCount { get; set; }
public int RegEventCount { get; set; }
// ReadRTLog
public long ReadRTLogTotal;
public long ReadRTLogSuccess;
public long ReadRTLogFailure;
// GetRTLog
public long GetRTLogTotal;
public long GetRTLogSuccess;
public long GetRTLogFailure;
// Callbacks
public long CallbackTotal;
public long CallbackUniquePersonnel;
public long CallbackDuplicateCount;
public DateTime FirstCallbackAt { get; set; }
public DateTime LastCallbackAt { get; set; }
public int CallbackThreadId { get; set; }
public ApartmentState CallbackApartment { get; set; }
// Callback duration — stored as ticks (1 tick = 100ns), safe for Interlocked
public long CallbackMinDurationTicks = long.MaxValue;
public long CallbackMaxDurationTicks = long.MinValue;
public long CallbackTotalDurationTicks;
// Errors
public long Exceptions;
public long UnexpectedDisconnects;
public long SpontaneousReconnects;
// Session
public bool SessionAlive { get; set; }
public string LastError { get; set; } = "";
}
// ═══════════════════════════════════════════════════════════════════
// Main Test
// ═══════════════════════════════════════════════════════════════════
[Fact]
public void Run()
{
var metrics = new Metrics();
var personnelSet = new ConcurrentDictionary();
var cts = new CancellationTokenSource();
var totalDuration = TimeSpan.FromHours(_durationHours);
Log("╔══════════════════════════════════════════════════════════════╗");
Log("║ TEST_LIVE24H_RT_HEALTH — Long-Lived Session Observation ║");
Log($"║ Device: {_ip}:{_port} ║");
Log($"║ Duration: {_durationHours}h | Probe interval: {_rtProbeIntervalSec}s ║");
Log("║ ReadGeneralLogData: BLOCKED ║");
Log("║ SSR_GetGeneralLogData: BLOCKED ║");
Log("║ SQLite: BLOCKED | HTTP: BLOCKED | Upload: BLOCKED ║");
Log("║ Automatic recovery: NONE ║");
Log("╚══════════════════════════════════════════════════════════════╝\n");
zkemkeeper.CZKEMClass? zkem = null;
metrics.SessionStart = DateTime.UtcNow;
try
{
// ─── Step 1: Create COM object ───
Log("[STEP 1] Creating CZKEMClass instance...");
zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
Log($" COM object created: 0x{RuntimeHelpers.GetHashCode(zkem):X8}");
Log($" Thread: {Thread.CurrentThread.ManagedThreadId} ({Thread.CurrentThread.GetApartmentState()})");
// ─── Step 2: Connect_Net ───
Log("\n[STEP 2] Connect_Net...");
bool connected = zkem.Connect_Net(_ip, _port);
metrics.ConnectNetCount++;
Log($" Connect_Net: {connected}");
if (!connected)
{
int err = -1;
zkem.GetLastError(ref err);
Log($" GetLastError: {err}");
Log(" ABORT: Cannot connect");
metrics.SessionEnd = DateTime.UtcNow;
PrintReport(metrics, personnelSet);
return;
}
Log(" Connected successfully");
// ─── Step 3: RegEvent(65535) ───
Log("\n[STEP 3] RegEvent(65535)...");
bool regOk = zkem.RegEvent(_machine, 65535);
metrics.RegEventCount++;
Log($" RegEvent(65535): {regOk}");
if (!regOk)
{
Log(" WARNING: RegEvent failed — callbacks may not fire");
}
// ─── Step 4: Subscribe to OnAttTransactionEx ───
Log("\n[STEP 4] Subscribing to OnAttTransactionEx...");
zkem.OnAttTransactionEx += (string enrollNumber, int isInValid, int attState,
int verifyMethod, int year, int month, int day, int hour, int minute, int second, int workCode) =>
{
var callbackSw = Stopwatch.StartNew();
var callbackTime = DateTime.UtcNow;
long currentCount = Interlocked.Increment(ref metrics.CallbackTotal);
// Capture first callback info
if (currentCount == 1)
{
metrics.CallbackThreadId = Thread.CurrentThread.ManagedThreadId;
metrics.CallbackApartment = Thread.CurrentThread.GetApartmentState();
metrics.FirstCallbackAt = callbackTime;
}
metrics.LastCallbackAt = callbackTime;
// Track unique personnel
personnelSet.TryAdd(enrollNumber, 0);
metrics.CallbackUniquePersonnel = personnelSet.Count;
// Duplicate = total - unique (approximate)
if (currentCount > personnelSet.Count)
{
Interlocked.Increment(ref metrics.CallbackDuplicateCount);
}
callbackSw.Stop();
long elapsedTicks = callbackSw.ElapsedTicks;
// Update min (atomic CAS loop)
long oldMin;
do { oldMin = Interlocked.Read(ref metrics.CallbackMinDurationTicks); }
while (elapsedTicks < oldMin && Interlocked.CompareExchange(ref metrics.CallbackMinDurationTicks, elapsedTicks, oldMin) != oldMin);
// Update max (atomic CAS loop)
long oldMax;
do { oldMax = Interlocked.Read(ref metrics.CallbackMaxDurationTicks); }
while (elapsedTicks > oldMax && Interlocked.CompareExchange(ref metrics.CallbackMaxDurationTicks, elapsedTicks, oldMax) != oldMax);
Interlocked.Add(ref metrics.CallbackTotalDurationTicks, elapsedTicks);
Log($" [CALLBACK #{currentCount}] {enrollNumber} | {year}-{month:D2}-{day:D2} {hour:D2}:{minute:D2}:{second:D2} | " +
$"Thread {Thread.CurrentThread.ManagedThreadId} ({Thread.CurrentThread.GetApartmentState()}) | " +
$"{callbackSw.Elapsed.TotalMilliseconds:F3}ms");
};
Log(" Subscribed. Waiting for live punches...\n");
// ─── Step 5: Background probe loop (ReadRTLog + GetRTLog) ───
Log("[STEP 5] Starting periodic RT probes...\n");
var probeTask = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_rtProbeIntervalSec), cts.Token);
}
catch (OperationCanceledException) { break; }
// ReadRTLog
var rtSw = Stopwatch.StartNew();
try
{
bool readRT = zkem.ReadRTLog(_machine);
rtSw.Stop();
Interlocked.Increment(ref metrics.ReadRTLogTotal);
if (readRT)
Interlocked.Increment(ref metrics.ReadRTLogSuccess);
else
Interlocked.Increment(ref metrics.ReadRTLogFailure);
Log($" [RT_PROBE] ReadRTLog={readRT} ({rtSw.ElapsedMilliseconds}ms)");
}
catch (Exception ex)
{
rtSw.Stop();
Interlocked.Increment(ref metrics.ReadRTLogTotal);
Interlocked.Increment(ref metrics.ReadRTLogFailure);
Interlocked.Increment(ref metrics.Exceptions);
Log($" [RT_PROBE] ReadRTLog EXCEPTION: {ex.GetType().Name}: {ex.Message}");
}
// GetRTLog
var gtSw = Stopwatch.StartNew();
try
{
bool getRT = zkem.GetRTLog(_machine);
gtSw.Stop();
Interlocked.Increment(ref metrics.GetRTLogTotal);
if (getRT)
Interlocked.Increment(ref metrics.GetRTLogSuccess);
else
Interlocked.Increment(ref metrics.GetRTLogFailure);
Log($" [RT_PROBE] GetRTLog={getRT} ({gtSw.ElapsedMilliseconds}ms)");
}
catch (Exception ex)
{
gtSw.Stop();
Interlocked.Increment(ref metrics.GetRTLogTotal);
Interlocked.Increment(ref metrics.GetRTLogFailure);
Interlocked.Increment(ref metrics.Exceptions);
metrics.LastError = $"GetRTLog: {ex.GetType().Name}: {ex.Message}";
Log($" [RT_PROBE] GetRTLog EXCEPTION: {ex.GetType().Name}: {ex.Message}");
}
metrics.SessionAlive = true;
}
});
// ─── Step 6: Wait for duration or cancellation ───
Log($"[STEP 6] Running for {_durationHours}h. Press Ctrl+C to stop early.\n");
Log($" Session started: {metrics.SessionStart:yyyy-MM-dd HH:mm:ss.fff} UTC");
Log($" Expected end: {(metrics.SessionStart + totalDuration):yyyy-MM-dd HH:mm:ss.fff} UTC\n");
var deadlineCts = new CancellationTokenSource(totalDuration);
var ctrlCcts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Log("\n [CTRL+C] Early termination requested...");
ctrlCcts.Cancel();
};
try
{
using var combined = CancellationTokenSource.CreateLinkedTokenSource(deadlineCts.Token, ctrlCcts.Token, cts.Token);
Task.Delay(Timeout.Infinite, combined.Token).GetAwaiter().GetResult();
}
catch (OperationCanceledException) { }
// ─── Step 7: Cleanup ───
Log("\n[STEP 7] Stopping...");
cts.Cancel();
try { probeTask.Wait(TimeSpan.FromSeconds(5)); } catch { }
metrics.SessionEnd = DateTime.UtcNow;
// ─── Report ───
PrintReport(metrics, personnelSet);
}
catch (Exception ex)
{
Interlocked.Increment(ref metrics.Exceptions);
metrics.LastError = $"{ex.GetType().Name}: {ex.Message}";
Log($"\n [FATAL] {ex.GetType().Name}: {ex.Message}");
Log(ex.StackTrace ?? "");
}
finally
{
if (zkem != null)
{
try
{
Log(" Releasing COM object...");
Marshal.ReleaseComObject(zkem);
}
catch { }
zkem = null;
}
}
}
// ═══════════════════════════════════════════════════════════════════
// Report
// ═══════════════════════════════════════════════════════════════════
private void PrintReport(Metrics m, ConcurrentDictionary personnel)
{
var elapsed = m.SessionEnd - m.SessionStart;
double minMs = m.CallbackMinDurationTicks == long.MaxValue ? 0 : (double)m.CallbackMinDurationTicks / Stopwatch.Frequency * 1000.0;
double maxMs = m.CallbackMaxDurationTicks == long.MinValue ? 0 : (double)m.CallbackMaxDurationTicks / Stopwatch.Frequency * 1000.0;
double avgMs = m.CallbackTotal > 0 ? (double)m.CallbackTotalDurationTicks / m.CallbackTotal / Stopwatch.Frequency * 1000.0 : 0;
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════════════════════════════════");
sb.AppendLine(" TEST_LIVE24H_RT_HEALTH — FINAL REPORT");
sb.AppendLine("═══════════════════════════════════════════════════════════════════");
sb.AppendLine();
sb.AppendLine(" SESSION");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Start: {m.SessionStart:yyyy-MM-dd HH:mm:ss.fff} UTC");
sb.AppendLine($" End: {m.SessionEnd:yyyy-MM-dd HH:mm:ss.fff} UTC");
sb.AppendLine($" Duration: {elapsed.TotalHours:F2}h ({elapsed.TotalMinutes:F0} min)");
sb.AppendLine($" Alive at end: {m.SessionAlive}");
sb.AppendLine();
sb.AppendLine(" CONNECTION");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Connect_Net count: {m.ConnectNetCount}");
sb.AppendLine($" RegEvent count: {m.RegEventCount}");
sb.AppendLine();
sb.AppendLine(" READRTLOG");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Total: {Interlocked.Read(ref m.ReadRTLogTotal)}");
sb.AppendLine($" Success: {Interlocked.Read(ref m.ReadRTLogSuccess)}");
sb.AppendLine($" Failure: {Interlocked.Read(ref m.ReadRTLogFailure)}");
sb.AppendLine();
sb.AppendLine(" GETRTLOG");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Total: {Interlocked.Read(ref m.GetRTLogTotal)}");
sb.AppendLine($" Success: {Interlocked.Read(ref m.GetRTLogSuccess)}");
sb.AppendLine($" Failure: {Interlocked.Read(ref m.GetRTLogFailure)}");
sb.AppendLine();
sb.AppendLine(" LIVE CALLBACK (OnAttTransactionEx)");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Total: {Interlocked.Read(ref m.CallbackTotal)}");
sb.AppendLine($" Unique personnel: {m.CallbackUniquePersonnel}");
sb.AppendLine($" Duplicate count: {Interlocked.Read(ref m.CallbackDuplicateCount)}");
sb.AppendLine($" First callback: {(m.FirstCallbackAt == default ? "N/A" : m.FirstCallbackAt.ToString("yyyy-MM-dd HH:mm:ss.fff") + " UTC")}");
sb.AppendLine($" Last callback: {(m.LastCallbackAt == default ? "N/A" : m.LastCallbackAt.ToString("yyyy-MM-dd HH:mm:ss.fff") + " UTC")}");
sb.AppendLine($" Thread ID: {m.CallbackThreadId}");
sb.AppendLine($" Apartment: {m.CallbackApartment}");
sb.AppendLine($" Min duration: {minMs:F3}ms");
sb.AppendLine($" Max duration: {maxMs:F3}ms");
sb.AppendLine($" Avg duration: {avgMs:F3}ms");
sb.AppendLine();
sb.AppendLine(" PERSONNEL");
sb.AppendLine(" ─────────────────────────────────────────────");
foreach (var pid in personnel.Keys)
sb.AppendLine($" {pid}");
sb.AppendLine();
sb.AppendLine(" ERRORS");
sb.AppendLine(" ─────────────────────────────────────────────");
sb.AppendLine($" Exceptions: {Interlocked.Read(ref m.Exceptions)}");
sb.AppendLine($" Unexpected disconnects: {Interlocked.Read(ref m.UnexpectedDisconnects)}");
sb.AppendLine($" Spontaneous reconnects: {Interlocked.Read(ref m.SpontaneousReconnects)}");
sb.AppendLine($" Last error: {m.LastError}");
sb.AppendLine();
sb.AppendLine("═══════════════════════════════════════════════════════════════════");
sb.AppendLine(" CLASSIFICATION");
sb.AppendLine("═══════════════════════════════════════════════════════════════════");
long total = Interlocked.Read(ref m.CallbackTotal);
long exceptions = Interlocked.Read(ref m.Exceptions);
long disc = Interlocked.Read(ref m.UnexpectedDisconnects);
long recon = Interlocked.Read(ref m.SpontaneousReconnects);
string stabilityClass;
if (exceptions == 0 && disc == 0 && recon == 0 && total > 0)
stabilityClass = "LIVE_SESSION_STABILITY_PROVEN";
else if (total > 0 && recon == 0)
stabilityClass = "LIVE_SESSION_STABILITY_PARTIALLY_PROVEN";
else
stabilityClass = "LIVE_SESSION_STABILITY_NOT_PROVEN";
sb.AppendLine($" {stabilityClass}");
sb.AppendLine();
sb.AppendLine(" FULL_READ_INTERACTION_STABILITY: NOT_TESTED");
sb.AppendLine(" (ReadGeneralLogData / SSR_GetGeneralLogData not exercised)");
sb.AppendLine("═══════════════════════════════════════════════════════════════════");
Log(sb.ToString());
// Write to file
var reportPath = Path.Combine(AppContext.BaseDirectory, $"TEST_LIVE24H_RT_HEALTH_{DateTime.UtcNow:yyyyMMdd_HHmmss}.txt");
File.WriteAllText(reportPath, sb.ToString());
Log($"\n Report saved: {reportPath}");
}
}