using System.Diagnostics;
using AttendanceHub.Sync.Domain;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using zkemkeeper;
namespace AttendanceHub.Sync.Com;
///
/// Per-device COM session worker (testable, prod-safe). One worker owns:
///
/// - a dedicated STA owner thread with a permanent Windows message pump (),
/// - exactly one CZKEMClass RCW created and released ONLY on that owner,
/// - a command queue through which every SDK call is invoked (never ThreadPool / Task.Run / ad-hoc STA),
/// - owner-thread + generation identity, structured per-operation telemetry, and a clean
/// start / stop / recreate lifecycle (old owner fully stopped before a new one starts).
///
/// Application code talks to (ComSession) and never sees the RCW.
///
public sealed class DeviceSessionWorker : IAsyncDisposable
{
private static readonly TimeSpan DefaultOpTimeout = TimeSpan.FromSeconds(30);
private readonly string _deviceId;
private readonly int _machineNumber;
private readonly int _commTimeoutSeconds;
private readonly ILogger _log;
private readonly object _lifecycleGate = new();
private ComOwnerThread? _owner;
private CZKEMClass? _rcw;
private bool _rcwConnected;
private int _generation = 1;
private int _ownerThreadStarts;
private int _startGate;
private int _lastRcwReleaseThreadId;
private bool _disposed;
private string _sdkVersion = "";
private DateTimeOffset? _rcwCreatedAt;
private Action? _attachSinks;
private Action? _detachSinks;
public string DeviceId => _deviceId;
public int MachineNumber => _machineNumber;
public int Generation => _generation;
public int OwnerThreadId => _owner?.OwnerManagedThreadId ?? 0;
public string ApartmentState => _owner?.ApartmentState ?? "Stopped";
public bool IsRunning => _owner?.IsRunning == true;
public bool PumpAlive => _owner?.PumpAlive == true;
public long LastPumpTickMs => _owner?.LastPumpTickMs ?? 0;
/// SDK/queue operation currently executing on the owner (null when idle).
public string? CurrentOperation => _owner?.CurrentOperation;
/// Duration of the in-flight owner operation in ms (0 when idle). Use with PumpAlive: a long read shows here while the pump heartbeat is starved.
public long CurrentOperationDurationMs => _owner?.CurrentOperationDurationMs ?? 0;
public long CrossThreadAccessViolations => _owner?.CrossThreadAccessViolations ?? 0;
public int OwnerThreadStarts => _ownerThreadStarts;
public string SdkVersion => _sdkVersion;
public DateTimeOffset? RcwCreatedAt => _rcwCreatedAt;
public int LastRcwReleaseThreadId => _lastRcwReleaseThreadId;
public bool RcwConnected => _rcwConnected;
public DeviceSessionWorker(string deviceId, int machineNumber, int commTimeoutSeconds, ILogger? log = null)
{
_deviceId = deviceId;
_machineNumber = machineNumber;
_commTimeoutSeconds = commTimeoutSeconds;
_log = log ?? NullLogger.Instance;
}
/// Register the session's realtime sink attach/detach (must run on the owner thread).
public void RegisterEventSinks(Action attach, Action detach)
{
_attachSinks = attach;
_detachSinks = detach;
}
/// Step 5+6 of the lifecycle: start a NEW owner thread (STA + permanent pump) and create the RCW on it.
public async Task StartAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (Interlocked.Exchange(ref _startGate, 1) == 1)
throw new InvalidOperationException($"DeviceSessionWorker '{_deviceId}' already started (ownerTid={OwnerThreadId}).");
var owner = CreateOwner();
await CreateRcwAsync(owner, cancellationToken).ConfigureAwait(false);
}
///
/// The single gateway for every SDK/COM operation. Executes on the owner
/// thread with the RCW; asserts owner identity; records structured COM_OP telemetry
/// (device, generation, owner tid, apartment, api, start/end, duration, success, native last-error).
///
public async Task InvokeAsync(string api, Func body, TimeSpan timeout, CancellationToken cancellationToken = default)
{
var owner = _owner ?? throw new ZkSdkException(
api, "DeviceSessionWorker not started", null, 0, _generation, 0, Environment.CurrentManagedThreadId);
var startUtc = DateTimeOffset.UtcNow;
var sw = Stopwatch.StartNew();
try
{
var (value, execTid, nativeErr) = await owner.InvokeAsync(() =>
{
owner.AssertOwnerThread(api);
var zk = _rcw ?? throw new ZkSdkException(
api, "CZKEMClass not created", null, 0, _generation,
owner.OwnerManagedThreadId, Environment.CurrentManagedThreadId);
var v = body(zk);
return (v, Environment.CurrentManagedThreadId, TryNativeErrorCore(zk));
}, api, timeout, cancellationToken).ConfigureAwait(false);
sw.Stop();
_log.LogInformation(
"COM_OP device={Device} api={Api} generation={Gen} ownerTid={OwnerTid} apartment={Apt} execTid={ExecTid} startUtc={Start} endUtc={End} durationMs={Ms} ok=true nativeLastError={Err}",
_deviceId, api, _generation, owner.OwnerManagedThreadId, owner.ApartmentState,
execTid, startUtc.ToString("o"), DateTimeOffset.UtcNow.ToString("o"), sw.ElapsedMilliseconds, nativeErr);
return value;
}
catch (Exception ex)
{
sw.Stop();
_log.LogError(ex,
"COM_OP_FAILED device={Device} api={Api} generation={Gen} ownerTid={OwnerTid} apartment={Apt} startUtc={Start} endUtc={End} durationMs={Ms} ok=false",
_deviceId, api, _generation, owner.OwnerManagedThreadId, owner.ApartmentState,
startUtc.ToString("o"), DateTimeOffset.UtcNow.ToString("o"), sw.ElapsedMilliseconds);
throw;
}
}
/// Connect_Net on the owner; attaches registered realtime sinks on success (owner thread).
public Task ConnectAsync(string ip, int port, CancellationToken cancellationToken = default)
{
return InvokeAsync("Connect_Net", zk =>
{
var sw = Stopwatch.StartNew();
try
{
var ok = zk.Connect_Net(ip, port);
sw.Stop();
var err = TryNativeErrorCore(zk);
_rcwConnected = ok;
if (ok && _attachSinks is not null)
{
_attachSinks(zk); // sink subscription happens on the owner thread
}
_log.LogInformation(
"COM_CONNECT_OWNER_THREAD=ONLY_OWNER device={Device} api=Connect_Net ok={Ok} lastError={Err} elapsedMs={Ms} ownerThread={Tid} generation={Gen}",
_deviceId, ok, err, sw.ElapsedMilliseconds, OwnerThreadId, _generation);
return new ConnectResult(ok, "Connect_Net", ok, err, sw.ElapsedMilliseconds,
ok ? null : "Connect_Net returned false");
}
catch (ZkSdkException)
{
throw;
}
catch (Exception ex)
{
sw.Stop();
_rcwConnected = false;
_log.LogError(ex,
"Connect_Net COM_EXCEPTION elapsedMs={Ms} ownerThread={Tid} generation={Gen}",
sw.ElapsedMilliseconds, OwnerThreadId, _generation);
return new ConnectResult(false, "Connect_Net", false, null, sw.ElapsedMilliseconds, ex.ToString());
}
}, DefaultOpTimeout, cancellationToken);
}
/// Disconnect on the owner after detaching sinks (unsubscription on the owner thread).
public Task DisconnectAsync(CancellationToken cancellationToken = default)
{
return InvokeAsync("Disconnect", zk =>
{
try
{
_detachSinks?.Invoke(zk);
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DETACH_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} phase=disconnect",
_deviceId, _generation, OwnerThreadId);
}
if (_rcwConnected)
{
try
{
zk.Disconnect();
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DISCONNECT_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _generation, OwnerThreadId);
}
}
_rcwConnected = false;
_log.LogInformation(
"COM_DISCONNECT_OWNER_THREAD=ONLY_OWNER device={Device} ownerThread={Tid} generation={Gen} at={Ts}",
_deviceId, OwnerThreadId, _generation, DateTimeOffset.UtcNow.ToString("o"));
return true;
}, DefaultOpTimeout, cancellationToken);
}
/// RegEvent on the owner. Throws ZkSdkException on SDK false (same contract as before).
public Task RegEventAsync(int eventMask, CancellationToken cancellationToken = default)
{
return InvokeAsync("RegEvent", zk =>
{
var sw = Stopwatch.StartNew();
var ok = zk.RegEvent(_machineNumber, eventMask);
sw.Stop();
var err = TryNativeErrorCore(zk);
_log.LogInformation(
"COM_EVENT_REG_OWNER_THREAD=ONLY_OWNER api=RegEvent mask={Mask} ok={Ok} lastError={Err} elapsedMs={Ms} ownerThread={Tid} generation={Gen}",
eventMask, ok, err, sw.ElapsedMilliseconds, OwnerThreadId, _generation);
if (!ok)
throw new ZkSdkException("RegEvent", "RegEvent failed", err, sw.ElapsedMilliseconds,
_generation, OwnerThreadId, Environment.CurrentManagedThreadId);
return true;
}, DefaultOpTimeout, cancellationToken);
}
/// Fire-and-forget: run an action on the owner thread (realtime event handoff).
public bool TryPost(Action action, string context)
=> _owner?.TryPost(action, context) ?? false;
///
/// Full session recreate lifecycle:
/// stop old owner -> unsubscribe on old owner -> disconnect/release RCW on old owner -> terminate old pump
/// -> start new owner -> create new RCW -> connect (+subscribe sinks) -> RegEvent -> increment generation.
/// No overlapping live use of old and new RCWs: the old owner is fully disposed before the new one starts.
/// Generation increments last on success; on a post-swap failure it still increments (finally) so a
/// new owner is never left under an old generation.
///
public async Task RecreateAsync(string ip, int port, int regMask, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var oldGeneration = _generation;
_log.LogWarning("SESSION_OWNER_RECREATE_BEGIN device={Device} oldGeneration={Gen} oldOwnerTid={Tid}",
_deviceId, oldGeneration, OwnerThreadId);
var swapped = false;
var bumped = false;
try
{
// Steps 1-4: teardown + terminate the OLD owner (pump) completely.
var oldOwner = _owner;
if (oldOwner is not null)
{
try
{
await oldOwner.InvokeAsync(() =>
{
oldOwner.AssertOwnerThread("SessionTeardown");
if (_rcw is not null)
{
try
{
_detachSinks?.Invoke(_rcw);
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DETACH_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} phase=recreate_teardown",
_deviceId, _generation, oldOwner.OwnerManagedThreadId);
}
if (_rcwConnected)
{
try
{
_rcw.Disconnect();
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DISCONNECT_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} phase=recreate_teardown",
_deviceId, _generation, oldOwner.OwnerManagedThreadId);
}
}
ReleaseRcwOnOwner(_rcw, "recreate_teardown");
}
_rcw = null;
_rcwConnected = false;
_log.LogInformation(
"SESSION_TEARDOWN device={Device} ownerThread={Tid} generation={Gen} at={Ts}",
_deviceId, oldOwner.OwnerManagedThreadId, _generation, DateTimeOffset.UtcNow.ToString("o"));
return true;
}, "SessionTeardown", DefaultOpTimeout, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogError(ex,
"SESSION_TEARDOWN_OP_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} - continuing to stop owner",
_deviceId, _generation, oldOwner.OwnerManagedThreadId);
}
try
{
await oldOwner.DisposeAsync().ConfigureAwait(false); // step 4: terminate old pump
}
catch (Exception ex)
{
_log.LogError(ex, "COM_OWNER_STOP_FAILED device={Device} ownerTid={OldTid}",
_deviceId, oldOwner.OwnerManagedThreadId);
}
_owner = null;
_log.LogInformation(
"SESSION_OWNER_STOPPED device={Device} oldOwnerTid={Tid} oldGeneration={Gen}",
_deviceId, oldOwner.OwnerManagedThreadId, oldGeneration);
}
// Steps 5-6: brand-new owner, new RCW (created only on the new owner).
var owner = CreateOwner();
swapped = true;
await CreateRcwAsync(owner, cancellationToken).ConfigureAwait(false);
// Step 7: connect (+ realtime sink subscription on the owner).
var conn = await ConnectAsync(ip, port, cancellationToken).ConfigureAwait(false);
if (!conn.Success)
throw new ZkSdkException("Connect_Net", "Session recreate failed to connect", conn.LastError,
conn.ElapsedMs, _generation, OwnerThreadId, Environment.CurrentManagedThreadId);
// Step 8: subscribe RegEvent mask on the owner.
await RegEventAsync(regMask, cancellationToken).ConfigureAwait(false);
// Step 9: increment generation (success path).
_generation++;
bumped = true;
_log.LogInformation(
"SESSION_OWNER_RECREATE_OK device={Device} newGeneration={Gen} newOwnerTid={Tid} apartment={Apt}",
_deviceId, _generation, OwnerThreadId, ApartmentState);
}
finally
{
if (swapped && !bumped)
{
_generation++;
_log.LogWarning(
"SESSION_OWNER_RECREATE_GEN_INCREMENTED device={Device} newGeneration={Gen} newOwnerTid={Tid} reason=owner_swapped_after_failure",
_deviceId, _generation, OwnerThreadId);
}
}
}
public async ValueTask DisposeAsync()
{
lock (_lifecycleGate)
{
if (_disposed) return;
_disposed = true;
}
var owner = _owner;
if (owner is null) return;
try
{
await owner.InvokeAsync(() =>
{
owner.AssertOwnerThread("COM_RELEASE");
if (_rcw is not null)
{
try
{
_detachSinks?.Invoke(_rcw);
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DETACH_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} phase=dispose",
_deviceId, _generation, owner.OwnerManagedThreadId);
}
if (_rcwConnected)
{
try
{
_rcw.Disconnect();
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_DISCONNECT_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} phase=dispose",
_deviceId, _generation, owner.OwnerManagedThreadId);
}
}
ReleaseRcwOnOwner(_rcw, "dispose");
}
_rcwConnected = false;
_log.LogInformation(
"COM_RELEASE_OWNER_THREAD=ONLY_OWNER device={Device} ownerThread={Tid} generation={Gen}",
_deviceId, owner.OwnerManagedThreadId, _generation);
return true;
}, "COM_RELEASE", DefaultOpTimeout).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogError(ex,
"COM_RELEASE_OP_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _generation, owner.OwnerManagedThreadId);
}
try
{
await owner.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.LogError(ex, "COM_OWNER_STOP_FAILED device={Device} ownerTid={OwnerTid}",
_deviceId, owner.OwnerManagedThreadId);
}
_owner = null;
_log.LogInformation("COM_WORKER_DISPOSED device={Device} generation={Gen}", _deviceId, _generation);
}
// ------------------------------------------------------------------
// internals
// ------------------------------------------------------------------
private ComOwnerThread CreateOwner()
{
var owner = new ComOwnerThread(_deviceId, _log);
owner.Start();
lock (_lifecycleGate) _owner = owner;
Interlocked.Increment(ref _ownerThreadStarts);
_log.LogInformation(
"DEVICE_SESSION_WORKER_OWNER_START device={Device} generation={Gen} starts={Starts} ownerTid={Tid} apartment={Apt}",
_deviceId, _generation, _ownerThreadStarts, owner.OwnerManagedThreadId, owner.ApartmentState);
return owner;
}
private Task CreateRcwAsync(ComOwnerThread owner, CancellationToken cancellationToken)
{
return owner.InvokeAsync(() =>
{
owner.AssertOwnerThread("COM_CREATE");
_rcw = new CZKEMClass();
_rcwCreatedAt = DateTimeOffset.UtcNow;
_sdkVersion = SafeGetSdkVersionCore(_rcw);
_log.LogInformation(
"COM_CREATE_OWNER_THREAD=ONLY_OWNER device={Device} pid={Pid} worker={Worker} ownerThread={Tid} apartment={Apt} generation={Gen} sdk={Sdk} createdAt={Ts}",
_deviceId, Environment.ProcessId, _deviceId, owner.OwnerManagedThreadId, owner.ApartmentState,
_generation, _sdkVersion, _rcwCreatedAt);
var ok = _rcw.SetCommuTimeOut(_commTimeoutSeconds);
var err = TryNativeErrorCore(_rcw);
_log.LogInformation("SetCommuTimeOut seconds={S} ok={Ok} lastError={Err}", _commTimeoutSeconds, ok, err);
return true;
}, "COM_CREATE", DefaultOpTimeout, cancellationToken);
}
private void ReleaseRcwOnOwner(CZKEMClass zk, string phase)
{
// Owner thread only - asserted by every caller path (all run inside owner invokes).
try
{
if (System.Runtime.InteropServices.Marshal.IsComObject(zk))
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(zk);
_lastRcwReleaseThreadId = Environment.CurrentManagedThreadId;
}
catch (Exception ex)
{
_log.LogError(ex,
"COM_RELEASE_FAILED device={Device} generation={Gen} ownerTid={OwnerTid} execTid={ExecTid} phase={Phase}",
_deviceId, _generation, OwnerThreadId, Environment.CurrentManagedThreadId, phase);
}
_rcw = null;
_rcwCreatedAt = null;
}
private string SafeGetSdkVersionCore(CZKEMClass zk)
{
try
{
string v = "";
return zk.GetSDKVersion(ref v) ? v : "";
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_SDK_VERSION_QUERY_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _generation, OwnerThreadId);
return "";
}
}
private int? TryNativeErrorCore(CZKEMClass zk)
{
try
{
int err = 0;
zk.GetLastError(ref err);
return err;
}
catch (Exception ex)
{
_log.LogWarning(ex,
"COM_NATIVE_ERROR_QUERY_FAILED device={Device} generation={Gen} ownerTid={OwnerTid}",
_deviceId, _generation, OwnerThreadId);
return null;
}
}
}