using System.Text.Json;
using AttendanceHub.Sync.Persistence;
using AttendanceHub.Sync.Upload;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AttendanceHub.Sync.Host;
///
/// Production upload activation for the EXISTING delivery layer (HttpUploadApiClient + UploadWorker).
/// Delivery only: ISyncStore + HTTP. Never touches COM/SDK, never blocks LIVE/READ acquisition.
/// All uploader failures are logged and swallowed inside the loop — they can never terminate the process.
///
public sealed class UploadRuntime : IAsyncDisposable
{
private readonly ISyncStore _store;
private readonly UploadWorker _worker;
private readonly ILogger _log;
private readonly HttpClient? _ownedHttp;
public UploadRuntime(ISyncStore store, IUploadApiClient client, ILogger? log = null,
RetryPolicy? retry = null, HttpClient? ownedHttp = null)
{
_store = store;
_log = log ?? NullLogger.Instance;
_worker = new UploadWorker(store, client, retry ?? RetryPolicy.Default, _log);
_ownedHttp = ownedHttp;
}
///
/// Parse the "upload" config section. Returns null when the section is missing
/// or upload.enabled=false (activation stays controlled).
///
public static UploadConfig? ParseFromElement(JsonElement upload)
{
try
{
if (!upload.TryGetProperty("enabled", out var en) || en.ValueKind != JsonValueKind.True)
return null;
var baseAddress = upload.GetProperty("baseAddress").GetString();
if (string.IsNullOrWhiteSpace(baseAddress))
return null;
var apiToken = upload.GetProperty("apiToken").GetString() ?? "";
var batchPath = upload.TryGetProperty("batchPath", out var bp)
? bp.GetString() ?? "/api/v1/sync/punches"
: "/api/v1/sync/punches";
var timeoutSec = upload.TryGetProperty("timeoutSeconds", out var ts) ? ts.GetInt32() : 30;
var batchSize = upload.TryGetProperty("batchSize", out var bs) ? bs.GetInt32() : 200;
var maxConcurrency = upload.TryGetProperty("maxConcurrency", out var mc) ? mc.GetInt32() : 1;
var pollMs = upload.TryGetProperty("pollingIntervalMs", out var pl) ? pl.GetInt32() : 15000;
// Optional upload-layer identity: Laravel authorizes by devices.ip, not by the
// acquisition deviceId. When absent/empty => fall back to the main device identity.
string? payloadDeviceId = null;
if (upload.TryGetProperty("deviceId", out var pdi) && pdi.ValueKind == JsonValueKind.String)
payloadDeviceId = string.IsNullOrWhiteSpace(pdi.GetString()) ? null : pdi.GetString();
return new UploadConfig(new Uri(baseAddress), apiToken, batchPath,
TimeSpan.FromSeconds(timeoutSec), batchSize, maxConcurrency, pollMs, payloadDeviceId);
}
catch (Exception)
{
return null; // malformed section => not activated (caller logs)
}
}
public static UploadConfig? ParseFromFile(string configPath)
{
using var doc = JsonDocument.Parse(File.ReadAllText(configPath));
return doc.RootElement.TryGetProperty("upload", out var up) ? ParseFromElement(up) : null;
}
/// One claim/upload/ack cycle — public for tests and for the background loop.
public async Task RunOnceAsync(string deviceId, int batchSize, CancellationToken ct = default)
{
var startUtc = DateTimeOffset.UtcNow;
var cycle = await _worker.RunOnceAsync(new[] { deviceId }, batchSize, ct).ConfigureAwait(false);
try
{
var stats = await _store.GetUploadStatsAsync(deviceId, ct).ConfigureAwait(false);
_log.LogInformation(
"UPLOAD_CYCLE device={Device} startUtc={Start} endUtc={End} success={S} retry={R} dlq={D} pending={P} sending={Sn} sent={Se} retryState={Rs} dlqState={Dl} lastSuccessAt={Ls}",
deviceId, startUtc.ToString("o"), DateTimeOffset.UtcNow.ToString("o"),
cycle.TotalSuccess, cycle.TotalRetry, cycle.TotalDlq,
stats.Pending, stats.Sending, stats.Sent, stats.Retry, stats.Dlq, stats.LastSuccessAt);
}
catch (Exception ex)
{
_log.LogWarning(ex, "UPLOAD_STATS_FAILED device={Device}", deviceId);
}
return cycle;
}
/// Background loop: sequential cycles over ALL managed devices, bounded by Host cancellation; failures never escape.
public Task RunAsync(string deviceId, int batchSize, int pollingIntervalMs, CancellationToken ct)
=> RunAsync(() => new[] { deviceId }, batchSize, pollingIntervalMs, ct);
///
/// Background loop for a dynamic device set: the provider is evaluated every cycle so devices
/// added/removed at runtime are picked up without restarting delivery.
///
public async Task RunAsync(Func> deviceIdsProvider, int batchSize, int pollingIntervalMs, CancellationToken ct)
{
_log.LogInformation("UPLOAD_LOOP_START devices=dynamic batchSize={B} pollMs={P}", batchSize, pollingIntervalMs);
while (!ct.IsCancellationRequested)
{
var deviceIds = Array.Empty();
try
{
deviceIds = deviceIdsProvider()?.ToArray() ?? Array.Empty();
}
catch (Exception ex)
{
_log.LogWarning(ex, "UPLOAD_DEVICE_LIST_FAILED — cycle skipped");
}
if (deviceIds.Length == 0)
{
_log.LogDebug("UPLOAD_CYCLE_SKIPPED reason=no_devices");
}
else
{
foreach (var deviceId in deviceIds)
{
try
{
await RunOnceAsync(deviceId, batchSize, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
// Delivery failures must NEVER terminate the process or affect acquisition.
_log.LogError(ex, "UPLOAD_LOOP_ERROR device={Device} — delivery only, acquisition unaffected", deviceId);
}
}
}
if (ct.IsCancellationRequested)
break;
try
{
await Task.Delay(pollingIntervalMs, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
_log.LogInformation("UPLOAD_LOOP_STOP devices=dynamic");
}
public ValueTask DisposeAsync()
{
_ownedHttp?.Dispose();
return ValueTask.CompletedTask;
}
}
/// Upload activation settings (from config "upload" section).
public sealed record UploadConfig(
Uri BaseAddress,
string ApiToken,
string BatchPath,
TimeSpan Timeout,
int BatchSize,
int MaxConcurrency,
int PollingIntervalMs,
string? DeviceId = null);