using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Persistence;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Upload;
///
/// HTTP client for Laravel punch upload with explicit per-record ACK.
/// At-least-once + idempotent backend. Never claims exactly-once.
///
public interface IUploadApiClient
{
Task UploadBatchAsync(
string batchId,
IReadOnlyList records,
CancellationToken cancellationToken = default);
}
public sealed class UploadClientOptions
{
public required Uri BaseAddress { get; init; }
public required string ApiToken { get; init; }
public string BatchPath { get; init; } = "/api/v1/sync/punches";
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
public int BatchSize { get; init; } = 200;
public int MaxConcurrency { get; init; } = 2;
///
/// Optional upload-layer identity for Laravel (records[].device_id only).
/// Laravel authorizes by devices.ip, not by the acquisition deviceId.
/// null/empty => outgoing device_id keeps the local record identity (existing behavior).
/// Local SQLite identity and UploadRecord.Identity are never changed by this.
/// Ignored when is supplied (multi-device mode).
///
public string? PayloadDeviceId { get; init; }
///
/// Per-device rewrite map: local acquisition deviceId → Laravel identity (devices.ip).
/// When present, ONLY the devices present in the map are rewritten and the global
/// fallback is not applied — otherwise every device would be
/// attributed to a single one. Devices whose local id already IS the ip simply miss the map
/// and keep their own id (which is what Laravel expects).
///
public IReadOnlyDictionary? DeviceIdMap { get; init; }
}
/// Default HTTP implementation (TLS enforced by HttpClient).
public sealed class HttpUploadApiClient : IUploadApiClient
{
private static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
private readonly HttpClient _http;
private readonly UploadClientOptions _options;
private readonly ILogger _log;
public HttpUploadApiClient(HttpClient http, UploadClientOptions options, ILogger? log = null)
{
_http = http;
_options = options;
_log = log ?? NullLogger.Instance;
if (_http.BaseAddress is null)
_http.BaseAddress = options.BaseAddress;
_http.Timeout = options.Timeout;
}
///
/// Explicit absolute URI: BaseAddress (e.g. .../AttendanceHub/public) + BatchPath
/// (e.g. /api/v1/sync/punches). Avoids HttpClient rooted-relative resolution that would
/// drop the base path prefix.
///
private Uri BuildUploadUri()
{
var baseUrl = _options.BaseAddress.AbsoluteUri.TrimEnd('/');
var path = _options.BatchPath.StartsWith('/') ? _options.BatchPath : "/" + _options.BatchPath;
return new Uri(baseUrl + path);
}
///
/// Serialize one claimed record for the wire. When a rewrite is configured, ONLY records[].device_id
/// is rewritten to the Laravel identity (devices.ip); every other field and the local record
/// identity stay untouched.
///
private JsonNode BuildRecordNode(UploadRecord r)
{
var node = JsonNode.Parse(r.PayloadJson);
if (node is not JsonObject obj)
return node!;
if (_options.DeviceIdMap is not null)
{
if (_options.DeviceIdMap.TryGetValue(r.Identity.DeviceId, out var mapped) && !string.IsNullOrEmpty(mapped))
obj["device_id"] = mapped;
// miss => local id already equals the Laravel identity (or is not managed here)
}
else if (!string.IsNullOrEmpty(_options.PayloadDeviceId))
{
obj["device_id"] = _options.PayloadDeviceId;
}
return node;
}
/// True when the outgoing device_id may differ from the local record identity.
private bool HasDeviceIdRewrite
=> _options.DeviceIdMap is not null || !string.IsNullOrEmpty(_options.PayloadDeviceId);
/// Local ids whose outgoing identity equals .
private IReadOnlyCollection LocalIdsFor(string payloadDeviceId)
{
var map = _options.DeviceIdMap;
if (map is null)
return [];
return map.Where(kv => string.Equals(kv.Value, payloadDeviceId, StringComparison.OrdinalIgnoreCase))
.Select(kv => kv.Key)
.ToList();
}
public async Task UploadBatchAsync(
string batchId,
IReadOnlyList records,
CancellationToken cancellationToken = default)
{
if (records.Count == 0)
return new UploadHttpResult(true, 204, new BatchAck(batchId, DateTimeOffset.UtcNow, []), FailureClass.Unknown, null);
var payload = new
{
batch_id = batchId,
records = records.Select(BuildRecordNode).ToArray()
};
var json = JsonSerializer.Serialize(payload, Json);
var uri = BuildUploadUri();
var sw = Stopwatch.StartNew();
using var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _options.ApiToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
using var response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
var status = (int)response.StatusCode;
sw.Stop();
_log.LogInformation("UPLOAD_HTTP endpoint={Url} batch={Batch} status={Status} durationMs={Ms} transportOk=true",
uri, batchId, status, sw.ElapsedMilliseconds);
if (response.StatusCode is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests
|| (int)response.StatusCode >= 500)
{
var cls = response.StatusCode == HttpStatusCode.TooManyRequests
? FailureClass.RetryableThrottle
: FailureClass.RetryableHttp;
return new UploadHttpResult(true, status, null, cls, body);
}
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
_log.LogError("UPLOAD_AUTH_FAILURE status={S}", status);
return new UploadHttpResult(true, status, null, FailureClass.PermanentAuth, body);
}
if (response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.UnprocessableEntity)
{
return new UploadHttpResult(true, status, null, FailureClass.PermanentValidation, body);
}
if (!response.IsSuccessStatusCode)
return new UploadHttpResult(true, status, null, FailureClass.Unknown, body);
var ack = ParseAck(batchId, body, records);
return new UploadHttpResult(true, status, ack, FailureClass.Unknown, null);
}
catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
sw.Stop();
_log.LogWarning("UPLOAD_HTTP endpoint={Url} batch={Batch} status=0 durationMs={Ms} transportOk=false failureClass=RetryableTransport",
uri, batchId, sw.ElapsedMilliseconds);
return new UploadHttpResult(false, 0, null, FailureClass.RetryableTransport, ex.Message);
}
catch (HttpRequestException ex)
{
sw.Stop();
_log.LogWarning("UPLOAD_HTTP endpoint={Url} batch={Batch} status=0 durationMs={Ms} transportOk=false failureClass=RetryableTransport",
uri, batchId, sw.ElapsedMilliseconds);
return new UploadHttpResult(false, 0, null, FailureClass.RetryableTransport, ex.Message);
}
}
private BatchAck ParseAck(string batchId, string body, IReadOnlyList records)
{
try
{
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
var list = new List();
var received = DateTimeOffset.UtcNow;
if (root.TryGetProperty("processed_at", out var pat) && DateTimeOffset.TryParse(pat.GetString(), out var patTs))
received = patTs;
void AddRange(string prop, RecordOutcome outcome, bool retryableHint)
{
if (!root.TryGetProperty(prop, out var arr) || arr.ValueKind != JsonValueKind.Array)
return;
foreach (var el in arr.EnumerateArray())
{
var identity = ReadIdentity(el, records);
var reason = el.TryGetProperty("reason", out var rs) ? rs.GetString() : null;
var receipt = el.TryGetProperty("server_receipt_id", out var rr) ? rr.GetString() : null;
var retryable = el.TryGetProperty("retryable", out var rb) && rb.ValueKind == JsonValueKind.True;
var o = outcome;
if (prop == "rejected")
o = retryable ? RecordOutcome.RetryableError : RecordOutcome.RejectedPermanent;
list.Add(new RecordAck(identity, o, reason, receipt, received));
}
}
AddRange("accepted", RecordOutcome.AcceptedNew, false);
AddRange("already_exists", RecordOutcome.AlreadyExists, false);
AddRange("rejected", RecordOutcome.RejectedPermanent, true);
// Fallback: aggregate-only response maps successes by count (not preferred).
if (list.Count == 0 && root.TryGetProperty("imported", out _))
{
// Treat whole batch as retryable if we cannot resolve per-identity ACK.
foreach (var r in records)
list.Add(new RecordAck(r.Identity, RecordOutcome.RetryableError, "aggregate_ack_unresolved", null, received));
}
return new BatchAck(batchId, received, list);
}
catch (Exception ex)
{
_log.LogError(ex, "UPLOAD_ACK_PARSE_FAILED");
return new BatchAck(batchId, DateTimeOffset.UtcNow,
records.Select(r => new RecordAck(r.Identity, RecordOutcome.RetryableError, "ack_parse_failed", null, null)).ToList());
}
}
private PunchIdentity ReadIdentity(JsonElement el, IReadOnlyList records)
{
var deviceId = el.TryGetProperty("device_id", out var d) ? d.GetString() ?? "" : "";
var pin = el.TryGetProperty("personnel_code", out var p) ? p.GetString() ?? "" : "";
var pt = el.TryGetProperty("punch_time", out var t) ? t.GetString() ?? "" : "";
var parsed = DateTimeOffset.TryParse(pt, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out var ts);
// Payload device_id rewrite: Laravel echoes the payload identity (devices.ip) while the
// local record keeps the acquisition device id. Map the ACK back to the local record
// (pin + punch_time, second granularity) so UploadWorker's ackMap keyed on local
// Identity.Key still matches.
if (parsed)
{
var tsSec = ts.UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
static bool SameTime(UploadRecord r, string pin2, long sec) =>
r.Identity.PersonnelCode == pin2 &&
r.Identity.PunchTime.UtcDateTime.Ticks / TimeSpan.TicksPerSecond == sec;
// 1) payload id already equals the local id (no rewrite configured for this device)
var direct = records.FirstOrDefault(r => r.Identity.DeviceId == deviceId && SameTime(r, pin, tsSec));
if (direct is not null)
return direct.Identity;
// 2) rewritten payload — prefer the record whose local id maps to the echoed id
if (HasDeviceIdRewrite)
{
var locals = LocalIdsFor(deviceId);
var scoped = records.FirstOrDefault(r =>
(locals.Count == 0 || locals.Contains(r.Identity.DeviceId)) && SameTime(r, pin, tsSec));
if (scoped is not null)
return scoped.Identity;
var any = records.FirstOrDefault(r => SameTime(r, pin, tsSec));
if (any is not null)
return any.Identity;
}
return new PunchIdentity(deviceId, pin, ts);
}
var fallback = records.FirstOrDefault(r =>
r.Identity.PersonnelCode == pin && r.Identity.DeviceId == deviceId);
return fallback?.Identity ?? new PunchIdentity(deviceId, pin, default);
}
}
///
/// Upload worker: round-robin devices, bounded batches, partial ACK, stale SENDING recovery.
/// Independent of COM / device reconciliation.
///
public sealed class UploadWorker
{
private readonly ISyncStore _store;
private readonly IUploadApiClient _client;
private readonly RetryPolicy _retry;
private readonly ILogger _log;
private readonly TimeSpan _sendingLease;
public UploadWorker(ISyncStore store, IUploadApiClient client, RetryPolicy? retry = null, ILogger? log = null)
{
_store = store;
_client = client;
_retry = retry ?? RetryPolicy.Default;
_sendingLease = _retry.SendingLease == default ? TimeSpan.FromMinutes(5) : _retry.SendingLease;
_log = log ?? NullLogger.Instance;
}
public async Task RecoverStaleSendingAsync(CancellationToken ct = default)
{
var n = await _store.RecoverStaleSendingAsync(_sendingLease, DateTimeOffset.UtcNow, ct).ConfigureAwait(false);
if (n > 0)
_log.LogWarning("UPLOAD_STALE_SENDING_RECOVERED count={N}", n);
return n;
}
public async Task RunOnceAsync(
IReadOnlyList deviceIds,
int batchSize,
CancellationToken ct = default)
{
await RecoverStaleSendingAsync(ct).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var results = new List();
// Round-robin: one batch per device per cycle so a huge backlog cannot starve others.
foreach (var deviceId in deviceIds)
{
var startUtc = DateTimeOffset.UtcNow;
var sw = Stopwatch.StartNew();
var claimed = await _store.ClaimPendingBatchAsync(deviceId, batchSize, _sendingLease, now, ct).ConfigureAwait(false);
if (claimed.Count == 0)
{
results.Add(new DeviceUploadResult(deviceId, 0, 0, 0, 0, null));
continue;
}
var batchId = $"B-{deviceId}-{now:yyyyMMddHHmmss}-{Guid.NewGuid():N}"[..48];
var http = await _client.UploadBatchAsync(batchId, claimed, ct).ConfigureAwait(false);
var success = 0;
var retry = 0;
var dlq = 0;
string? lastErr = http.Error;
int accepted = 0, alreadyExists = 0, rejected = 0, retryable = 0;
if (!http.TransportOk || http.Ack is null)
{
// Whole batch retryable (timeout / 5xx / lost response). Rows stay SENDING until lease/recover or we set Retry now.
retryable = claimed.Count;
foreach (var rec in claimed)
{
await _store.ApplyAckAsync(rec.LocalId, RecordOutcome.RetryableError, http.Error ?? http.FailureClass.ToString(),
null, DateTimeOffset.UtcNow, _retry, ct).ConfigureAwait(false);
retry++;
}
}
else
{
accepted = http.Ack.Records.Count(r => r.Outcome == RecordOutcome.AcceptedNew);
alreadyExists = http.Ack.Records.Count(r => r.Outcome == RecordOutcome.AlreadyExists);
rejected = http.Ack.Records.Count(r => r.Outcome is RecordOutcome.RejectedPermanent or RecordOutcome.RejectedInvalid);
retryable = http.Ack.Records.Count(r => r.Outcome == RecordOutcome.RetryableError);
var ackMap = http.Ack.Records.ToDictionary(
a => a.Identity.Key,
a => a,
StringComparer.Ordinal);
foreach (var rec in claimed)
{
if (ackMap.TryGetValue(rec.Identity.Key, out var ack))
{
await _store.ApplyAckAsync(rec.LocalId, ack.Outcome, ack.Reason, ack.ServerReceiptId,
DateTimeOffset.UtcNow, _retry, ct).ConfigureAwait(false);
if (ack.Outcome.IsTerminalSuccess()) success++;
else if (ack.Outcome.IsRetryable()) retry++;
else
{
await _store.MoveToClientDlqAsync(rec.LocalId, FailureClass.PermanentBusiness.ToString(),
ack.Reason ?? "permanent", DateTimeOffset.UtcNow, ct).ConfigureAwait(false);
dlq++;
}
}
else
{
// Response lost / missing identity -> retry (idempotent backend).
await _store.ApplyAckAsync(rec.LocalId, RecordOutcome.RetryableError, "missing_ack_identity",
null, DateTimeOffset.UtcNow, _retry, ct).ConfigureAwait(false);
retry++;
}
}
}
results.Add(new DeviceUploadResult(deviceId, claimed.Count, success, retry, dlq, lastErr));
sw.Stop();
_log.LogInformation(
"UPLOAD_BATCH device={Device} batch={Batch} batch_size={Size} startUtc={Start} endUtc={End} durationMs={Ms} http={Http} accepted={A} already_exists={AE} rejected={Rj} retryable={Rt} claimed={C} success={Su} retry={R} dlq={Dl} err={Err}",
deviceId, batchId, claimed.Count, startUtc.ToString("o"), DateTimeOffset.UtcNow.ToString("o"),
sw.ElapsedMilliseconds, http.StatusCode, accepted, alreadyExists, rejected, retryable,
claimed.Count, success, retry, dlq, lastErr);
}
return new UploadCycleResult(results);
}
}
public sealed record DeviceUploadResult(
string DeviceId,
int Claimed,
int Success,
int Retry,
int Dlq,
string? LastError);
public sealed record UploadCycleResult(IReadOnlyList Devices)
{
public int TotalSuccess => Devices.Sum(d => d.Success);
public int TotalRetry => Devices.Sum(d => d.Retry);
public int TotalDlq => Devices.Sum(d => d.Dlq);
}