using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; namespace Admin.NET.DataPlatform.Worker; internal sealed class PurchaseWorker(PurchaseWorkerStore store) { public async Task RunOneAsync(CancellationToken stoppingToken) { var lease = await store.ClaimAsync(stoppingToken); if (lease is null) return false; using var processing = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); using var heartbeat = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); var renewal = MaintainLeaseAsync(lease, processing, heartbeat.Token); try { await ProcessAsync(lease, processing.Token); } catch (PurchaseHandoffException error) when (error.Code == "LEASE_LOST") { Console.Error.WriteLine($"Batch {lease.BatchId} lost its lease."); } catch (PurchaseHandoffException error) { await ReportFailureAsync(lease, error.Code, error.Retry, processing.Token); } catch (Exception error) when (error is JsonException or InvalidDataException or IngestContractException or FormatException or ArgumentException) { await ReportFailureAsync(lease, "INVALID_RAW_OR_PACKAGE", retry: false, processing.Token); } catch (OperationCanceledException) when (processing.IsCancellationRequested && !stoppingToken.IsCancellationRequested) { // Another Worker may take over after expiry. Do not update a lease whose ownership is uncertain. } finally { await heartbeat.CancelAsync(); await renewal; } return true; } private async Task ProcessAsync(PurchaseTaskLease lease, CancellationToken cancellationToken) { var prepared = await store.ReadRawAsync(lease, cancellationToken); var converted = PurchaseBatchProcessor.Process(prepared, lease.Token); var package = converted.Package with { LeaseToken = string.Empty }; var digest = package.ComputeDigest(); if (lease.PackageJson is not null || lease.PackageDigest is not null) { var previous = lease.PackageJson is null ? null : JsonSerializer.Deserialize(lease.PackageJson, JsonSerializerOptions.Web); if (previous is null || previous.LeaseToken != string.Empty || previous.ComputeDigest() != digest || lease.PackageDigest != digest) throw new InvalidDataException("Stored package differs from the frozen Raw batch."); } var ordinals = prepared.Events.ToDictionary(row => row.RawEventId, row => row.RecordOrdinal); var isolated = converted.Quarantines.Select(row => new PurchaseIsolation(row, ordinals[row.RawEventId])).ToArray(); if (package.Items.Count == 0) await store.CompleteAsync(lease, "QUARANTINED", isolated, cancellationToken); else await store.ConfirmAsync(lease, package, digest, ordinals, isolated, cancellationToken); } private async Task ReportFailureAsync(PurchaseTaskLease lease, string code, bool retry, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested && await store.FailAsync(lease, code, retry, cancellationToken)) Console.Error.WriteLine($"Batch {lease.BatchId} attempt {lease.AttemptNumber}: {code}."); } private async Task MaintainLeaseAsync(PurchaseTaskLease lease, CancellationTokenSource processing, CancellationToken cancellationToken) { try { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15)); while (await timer.WaitForNextTickAsync(cancellationToken)) { if (await store.RenewAsync(lease, cancellationToken)) continue; await processing.CancelAsync(); return; } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { } catch (Exception error) { Console.Error.WriteLine($"Batch {lease.BatchId} heartbeat failed: {error.GetType().Name}."); await processing.CancelAsync(); } } }