PurchaseWorker.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. namespace Admin.NET.DataPlatform.Worker;
  4. internal sealed class PurchaseWorker(PurchaseWorkerStore store)
  5. {
  6. public async Task<bool> RunOneAsync(CancellationToken stoppingToken)
  7. {
  8. var lease = await store.ClaimAsync(stoppingToken);
  9. if (lease is null)
  10. return false;
  11. using var processing = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
  12. using var heartbeat = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
  13. var renewal = MaintainLeaseAsync(lease, processing, heartbeat.Token);
  14. try
  15. {
  16. await ProcessAsync(lease, processing.Token);
  17. }
  18. catch (PurchaseHandoffException error) when (error.Code == "LEASE_LOST")
  19. {
  20. Console.Error.WriteLine($"Batch {lease.BatchId} lost its lease.");
  21. }
  22. catch (PurchaseHandoffException error)
  23. {
  24. await ReportFailureAsync(lease, error.Code, error.Retry, processing.Token);
  25. }
  26. catch (Exception error) when (error is JsonException or InvalidDataException or IngestContractException or FormatException or ArgumentException)
  27. {
  28. await ReportFailureAsync(lease, "INVALID_RAW_OR_PACKAGE", retry: false, processing.Token);
  29. }
  30. catch (OperationCanceledException) when (processing.IsCancellationRequested && !stoppingToken.IsCancellationRequested)
  31. {
  32. // Another Worker may take over after expiry. Do not update a lease whose ownership is uncertain.
  33. }
  34. finally
  35. {
  36. await heartbeat.CancelAsync();
  37. await renewal;
  38. }
  39. return true;
  40. }
  41. private async Task ProcessAsync(PurchaseTaskLease lease, CancellationToken cancellationToken)
  42. {
  43. var prepared = await store.ReadRawAsync(lease, cancellationToken);
  44. var converted = PurchaseBatchProcessor.Process(prepared, lease.Token);
  45. var package = converted.Package with { LeaseToken = string.Empty };
  46. var digest = package.ComputeDigest();
  47. if (lease.PackageJson is not null || lease.PackageDigest is not null)
  48. {
  49. var previous = lease.PackageJson is null ? null :
  50. JsonSerializer.Deserialize<PurchaseHandoffPackage>(lease.PackageJson, JsonSerializerOptions.Web);
  51. if (previous is null || previous.LeaseToken != string.Empty || previous.ComputeDigest() != digest
  52. || lease.PackageDigest != digest)
  53. throw new InvalidDataException("Stored package differs from the frozen Raw batch.");
  54. }
  55. var ordinals = prepared.Events.ToDictionary(row => row.RawEventId, row => row.RecordOrdinal);
  56. var isolated = converted.Quarantines.Select(row => new PurchaseIsolation(row, ordinals[row.RawEventId])).ToArray();
  57. if (package.Items.Count == 0)
  58. await store.CompleteAsync(lease, "QUARANTINED", isolated, cancellationToken);
  59. else
  60. await store.ConfirmAsync(lease, package, digest, ordinals, isolated, cancellationToken);
  61. }
  62. private async Task ReportFailureAsync(PurchaseTaskLease lease, string code, bool retry, CancellationToken cancellationToken)
  63. {
  64. if (!cancellationToken.IsCancellationRequested && await store.FailAsync(lease, code, retry, cancellationToken))
  65. Console.Error.WriteLine($"Batch {lease.BatchId} attempt {lease.AttemptNumber}: {code}.");
  66. }
  67. private async Task MaintainLeaseAsync(PurchaseTaskLease lease, CancellationTokenSource processing, CancellationToken cancellationToken)
  68. {
  69. try
  70. {
  71. using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15));
  72. while (await timer.WaitForNextTickAsync(cancellationToken))
  73. {
  74. if (await store.RenewAsync(lease, cancellationToken))
  75. continue;
  76. await processing.CancelAsync();
  77. return;
  78. }
  79. }
  80. catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
  81. {
  82. }
  83. catch (Exception error)
  84. {
  85. Console.Error.WriteLine($"Batch {lease.BatchId} heartbeat failed: {error.GetType().Name}.");
  86. await processing.CancelAsync();
  87. }
  88. }
  89. }