namespace AttendanceHub.Sync.Domain;
///
/// Abstraction over one exclusive COM session. Implementations must execute every
/// SDK operation on the single owner thread. Callers never see a COM RCW.
///
public interface IZkComSession : IAsyncDisposable
{
int Generation { get; }
ZkSessionInfo Info { get; }
bool IsConnected { get; }
/// Owner-thread message pump liveness (health metric; false while the pump is starved or dead).
bool PumpAlive { get; }
/// Realtime events dispatched directly on the owner thread (LIVE observability).
long EventsDirectOnOwner { get; }
/// Realtime events captured off-owner and handed to the owner queue (LIVE observability).
long EventsHandedToOwner { get; }
/// Realtime events dropped because the owner/session was unavailable (LIVE observability; healthy runs = 0).
long EventsDropped { get; }
/// Raised for attendance realtime events already validated against the current generation.
event Action? AttendanceReceived;
Task InitializeAsync(CancellationToken cancellationToken = default);
Task ConnectAsync(CancellationToken cancellationToken = default);
Task DisconnectAsync(CancellationToken cancellationToken = default);
Task RegEventAsync(int eventMask, CancellationToken cancellationToken = default);
Task ProbeCapabilityAsync(CancellationToken cancellationToken = default);
Task GetFunctionalHealthAsync(CancellationToken cancellationToken = default);
Task ReadAttendanceAsync(AttendanceReadRequest request, CancellationToken cancellationToken = default);
Task RecreateSessionAsync(CancellationToken cancellationToken = default);
///
/// Cheap liveness probe: a NON-log-read SDK round trip (device info) with a short timeout.
/// It never mutates connection state — the caller decides when repeated failures mean the
/// session is a zombie (the COM OnDisConnected callback is not reliable on these devices,
/// so liveness MUST be proven by actual I/O). Default implementation for device-free fakes:
/// "alive while connected".
///
Task PingAsync(CancellationToken cancellationToken = default)
=> Task.FromResult(IsConnected);
}
public sealed record ZkSessionInfo(
int ProcessId,
string WorkerId,
int OwnerThreadId,
string ApartmentState,
int Generation,
string SdkVersion,
DateTimeOffset? ComCreatedAt,
DateTimeOffset? ConnectedAt,
DateTimeOffset? DisconnectedAt);
public sealed record ConnectResult(
bool Success,
string ApiName,
bool ReturnValue,
int? LastError,
long ElapsedMs,
string? Error);
public sealed record DeviceCapability(
string? Serial,
string? Mac,
string? ProductCode,
string? Firmware,
string? FirmwareFamily,
string? SdkVersion,
string? Platform,
string? DeviceIp,
bool IsNewFirmware,
int AttCount,
int AttCapacity,
int AttRemaining,
int UserCount,
string PreferredReadApi,
string PreferredRealtimeApi,
IReadOnlyList ProbedApis);
public sealed record FunctionalHealth(
bool Connected,
bool DeviceInfoOk,
bool FunctionalReadOk,
string ReadApiUsed,
int LogsEnumerated,
long ReadDurationMs,
string? SdkError,
DeviceCapability? Capability);
public sealed record RawAttendanceEvent(
int Generation,
string PersonnelCode,
bool IsInvalid,
int AttendanceState,
int VerifyMethod,
int Year,
int Month,
int Day,
int Hour,
int Minute,
int Second,
int WorkCode,
string SourceApi,
DateTimeOffset CapturedAt);
public sealed record AttendanceReadRequest(
DateTimeOffset Start,
DateTimeOffset End,
AttendanceReadMode Mode,
int MaxRecords,
bool AllowFallback = true,
///
/// Auto mode only: attempt the windowed ReadTimeGLogData(start,end) load first and fall
/// back to full-buffer ReadGeneralLogData when the device rejects it. False keeps the
/// legacy "full-buffer only" behaviour (tests, tools, full reconciliation passes).
///
bool TryTimeWindow = false);
public enum AttendanceReadMode
{
Auto = 0,
TimeWindow = 1,
NewOnly = 2,
LegacyFull = 3
}
public sealed record AttendanceReadResult(
AttendanceReadStatus Status,
string ApiUsed,
string? DrainApiUsed,
IReadOnlyList Records,
long ElapsedMs,
int? LastError,
string? Error,
/// True when the load was served by the windowed API (no full-buffer fallback happened).
bool WindowedLoad = false);
public enum AttendanceReadStatus
{
Success = 0,
TrueEmpty = 1,
ReadFailure = 2,
Timeout = 3,
Disconnected = 4,
ComException = 5,
/// API not supported / not usable on this device/firmware at runtime.
CapabilityUnsupported = 6
}
public sealed class ZkSdkException : Exception
{
public string ApiName { get; }
public int? LastError { get; }
public long ElapsedMs { get; }
public int Generation { get; }
public int OwnerThreadId { get; }
public int WorkerThreadId { get; }
public ZkSdkException(
string apiName,
string message,
int? lastError,
long elapsedMs,
int generation,
int ownerThreadId,
int workerThreadId,
Exception? inner = null)
: base(message, inner)
{
ApiName = apiName;
LastError = lastError;
ElapsedMs = elapsedMs;
Generation = generation;
OwnerThreadId = ownerThreadId;
WorkerThreadId = workerThreadId;
}
}