using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Com;
///
/// Stable dedicated STA thread with a real Windows message pump and a command queue.
/// All COM create/use/release for one device session must run on this thread.
///
public sealed class ComOwnerThread : IAsyncDisposable
{
private readonly string _ownerName;
private readonly ILogger _log;
private readonly ConcurrentQueue _queue = new();
private readonly AutoResetEvent _commandSignal = new(false);
private readonly CancellationTokenSource _lifetime = new();
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _stopped = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Thread? _thread;
private volatile bool _running;
private int _ownerManagedThreadId;
private int _ownerOsThreadId;
private string _apartmentLabel = "Unknown";
private long _lastPumpTickMs;
private long _crossThreadAccessViolations;
private volatile string? _currentOperation;
private long _currentOperationStartedTicks;
public int OwnerManagedThreadId => _ownerManagedThreadId;
public int OwnerOsThreadId => _ownerOsThreadId;
public string ApartmentState => _apartmentLabel;
public bool IsRunning => _running;
///
/// Tick of the last actual pump-loop iteration (message-wait / dispatch cycle ONLY).
/// Never refreshed by queue-item completion: a long blocking SDK call starves the pump,
/// and honestly reports false while the loop is inside such a call.
///
public long LastPumpTickMs => Volatile.Read(ref _lastPumpTickMs);
/// Pump loop is running AND has completed a wait/dispatch cycle within the last 3 seconds (quantum 250 ms).
public bool PumpAlive => _running && (Environment.TickCount64 - Volatile.Read(ref _lastPumpTickMs)) < 3000;
/// Name of the SDK/queue operation currently executing on the owner thread, or null when idle.
public string? CurrentOperation => _currentOperation;
/// Duration of the in-flight operation in ms (0 when idle). Complements PumpAlive: a long read shows here.
public long CurrentOperationDurationMs
{
get
{
var started = Volatile.Read(ref _currentOperationStartedTicks);
return started == 0 ? 0 : Environment.TickCount64 - started;
}
}
/// Number of detected attempts to assert on a foreign thread (healthy runs stay at 0).
public long CrossThreadAccessViolations => Interlocked.Read(ref _crossThreadAccessViolations);
private void BeginOperation(string name)
{
_currentOperation = name;
Volatile.Write(ref _currentOperationStartedTicks, Environment.TickCount64);
}
private void EndOperation()
{
_currentOperation = null;
Volatile.Write(ref _currentOperationStartedTicks, 0);
}
public ComOwnerThread(string ownerName, ILogger? log = null)
{
_ownerName = ownerName;
_log = log ?? NullLogger.Instance;
}
public void Start()
{
if (_thread is not null)
throw new InvalidOperationException($"ComOwnerThread '{_ownerName}' already started.");
_thread = new Thread(OwnerMain)
{
IsBackground = true,
Name = $"ZkComOwner-{_ownerName}"
};
_thread.SetApartmentState(System.Threading.ApartmentState.STA);
_thread.Start();
_started.Task.GetAwaiter().GetResult();
}
public Task StartAsync()
{
Start();
return Task.CompletedTask;
}
/// Run a function on the owner thread. Never call COM from the caller thread.
public Task InvokeAsync(Func func, string apiName, TimeSpan timeout, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(!_running, this);
var item = new WorkItem(func, apiName, timeout, cancellationToken);
_queue.Enqueue(item);
_commandSignal.Set();
return item.Task;
}
public Task InvokeAsync(Action action, string apiName, TimeSpan timeout, CancellationToken cancellationToken = default)
{
return InvokeAsync(() =>
{
action();
return true;
}, apiName, timeout, cancellationToken);
}
public void AssertOwnerThread(string apiName)
{
var current = Environment.CurrentManagedThreadId;
if (current != _ownerManagedThreadId)
{
Interlocked.Increment(ref _crossThreadAccessViolations);
_log.LogError(
"CROSS_THREAD_COM_ACCESS api={Api} currentThread={Cur} ownerThread={Owner} owner={Name} apartment={Apt}",
apiName, current, _ownerManagedThreadId, _ownerName, _apartmentLabel);
throw new InvalidOperationException(
$"COM_ACCESS_VIOLATION api={apiName} currentThread={current} ownerThread={_ownerManagedThreadId} name={_ownerName}");
}
}
///
/// Fire-and-forget: run on the owner thread (used to bring COM event
/// callbacks into the owner context). Never executes on the caller thread. Returns false if the
/// owner is not running (caller must log the drop).
///
public bool TryPost(Action action, string context)
{
if (!_running)
{
_log.LogWarning("OWNER_POST_DROPPED context={Context} reason=owner_not_running owner={Owner}", context, _ownerName);
return false;
}
_queue.Enqueue(new PostWorkItem(action, context));
_commandSignal.Set();
return true;
}
private void OwnerMain()
{
_ownerManagedThreadId = Environment.CurrentManagedThreadId;
_ownerOsThreadId = (int)NativePump.GetCurrentThreadId();
_apartmentLabel = nameof(System.Threading.ApartmentState.STA);
var hr = NativePump.CoInitializeEx(IntPtr.Zero, NativePump.COINIT_APARTMENTTHREADED | NativePump.COINIT_DISABLE_OLE1DDE);
_log.LogInformation(
"COM_OWNER_START owner={Owner} managedThreadId={Mtid} osThreadId={Otid} apartment={Apt} coInitHr=0x{Hr:X8}",
_ownerName, _ownerManagedThreadId, _ownerOsThreadId, _apartmentLabel, hr);
_running = true;
Volatile.Write(ref _lastPumpTickMs, Environment.TickCount64);
_started.TrySetResult();
try
{
PumpLoop();
}
catch (Exception ex)
{
_log.LogError(ex, "COM_OWNER_PUMP_CRASH owner={Owner}", _ownerName);
}
finally
{
DrainAndFaultAll("owner stopping");
_running = false;
NativePump.CoUninitialize();
_log.LogInformation("COM_OWNER_STOP owner={Owner} managedThreadId={Mtid}", _ownerName, _ownerManagedThreadId);
_stopped.TrySetResult();
}
}
private void PumpLoop()
{
var handle = _commandSignal.SafeWaitHandle.DangerousGetHandle();
var handles = new[] { handle };
while (!_lifetime.IsCancellationRequested)
{
var wait = NativePump.MsgWaitForMultipleObjectsEx(
nCount: 1,
pHandles: handles,
dwMilliseconds: 250,
dwWakeMask: NativePump.QS_ALLINPUT,
dwFlags: NativePump.MWMO_INPUTAVAILABLE);
if (wait == NativePump.WAIT_FAILED)
{
var err = Marshal.GetLastWin32Error();
_log.LogError("MSG_WAIT_FAILED owner={Owner} win32={Err}", _ownerName, err);
break;
}
// Always dispatch pending window/COM messages (connection-point sinks).
DispatchPendingMessages();
// Heartbeat: proves the pump loop is alive for the entire session lifetime.
Volatile.Write(ref _lastPumpTickMs, Environment.TickCount64);
// Then execute queued device commands on this same thread.
ProcessQueue();
}
DispatchPendingMessages();
ProcessQueue();
}
private static void DispatchPendingMessages()
{
while (NativePump.PeekMessage(out var msg, IntPtr.Zero, 0, 0, NativePump.PM_REMOVE))
{
NativePump.TranslateMessage(ref msg);
NativePump.DispatchMessage(ref msg);
}
}
///
/// Record pump liveness. Called ONLY from the pump loop itself (OwnerMain start + each
/// wait/dispatch iteration). Queue-item completion must NOT refresh this: telemetry has to
/// distinguish "pump is dispatching" from "owner thread is stuck inside a blocking SDK call".
///
private void MarkPumpTick() => Volatile.Write(ref _lastPumpTickMs, Environment.TickCount64);
private void ProcessQueue()
{
while (_queue.TryDequeue(out var item))
{
if (_lifetime.IsCancellationRequested)
{
item.TryCancel("owner shutting down");
continue;
}
if (item.IsCanceled)
{
item.TryCancel("caller canceled");
continue;
}
item.ExecuteOnOwner(this);
}
}
private void DrainAndFaultAll(string reason)
{
while (_queue.TryDequeue(out var item))
item.TryCancel(reason);
}
public async ValueTask DisposeAsync()
{
_lifetime.Cancel();
_commandSignal.Set();
if (_thread is not null)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
await _stopped.Task.WaitAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
_log.LogWarning("COM_OWNER_STOP_TIMEOUT owner={Owner} — aborting owner thread", _ownerName);
// Last resort: native hang; abandon background thread (process exit cleans up).
}
}
_commandSignal.Dispose();
_lifetime.Dispose();
}
private interface IWorkItem
{
bool IsCanceled { get; }
void ExecuteOnOwner(ComOwnerThread owner);
void TryCancel(string reason);
}
/// Fire-and-forget work item: never faults a TCS; failures become structured telemetry.
private sealed class PostWorkItem : IWorkItem
{
private readonly Action _action;
private readonly string _context;
public PostWorkItem(Action action, string context)
{
_action = action;
_context = context;
}
public bool IsCanceled => false;
public void ExecuteOnOwner(ComOwnerThread owner)
{
owner.BeginOperation(_context);
try
{
_action();
}
catch (Exception ex)
{
owner._log.LogError(ex, "OWNER_POST_FAILURE context={Context} owner={Owner}", _context, owner._ownerName);
}
finally
{
owner.EndOperation();
}
}
public void TryCancel(string reason)
{
// Fire-and-forget: no caller to notify. Shutdown drops are logged by TryPost/OwnerMain.
}
}
private sealed class WorkItem : IWorkItem
{
private readonly Func _func;
private readonly string _apiName;
private readonly TimeSpan _timeout;
private readonly CancellationToken _ct;
private readonly TaskCompletionSource _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
public WorkItem(Func func, string apiName, TimeSpan timeout, CancellationToken ct)
{
_func = func;
_apiName = apiName;
_timeout = timeout;
_ct = ct;
}
public Task Task => _tcs.Task;
public bool IsCanceled => _ct.IsCancellationRequested;
public void ExecuteOnOwner(ComOwnerThread owner)
{
owner.BeginOperation(_apiName);
var sw = System.Diagnostics.Stopwatch.StartNew();
try
{
_ct.ThrowIfCancellationRequested();
// Soft timeout is applied by callers around long SDK ops via CancellationTokenSource;
// owner still executes to completion to avoid tearing COM mid-call.
var result = _func();
sw.Stop();
if (sw.Elapsed > _timeout)
{
owner._log.LogWarning(
"COM_OP_SLOW api={Api} elapsedMs={Ms} timeoutMs={T} ownerThread={Tid} generationLocal={G}",
_apiName, sw.ElapsedMilliseconds, _timeout.TotalMilliseconds, owner._ownerManagedThreadId, 0);
}
_tcs.TrySetResult(result);
}
catch (Exception ex)
{
sw.Stop();
_tcs.TrySetException(ex);
}
finally
{
owner.EndOperation();
}
}
public void TryCancel(string reason)
{
_tcs.TrySetException(new OperationCanceledException($"{_apiName}: {reason}"));
}
}
}