PurchaseDispatcher.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System.Data;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. using MySqlConnector;
  5. namespace Admin.NET.DataPlatform.Worker;
  6. internal sealed class PurchaseDispatcher(string connectionString, IAidopPackageHandoff handoff)
  7. {
  8. // Only the dispatcher locks the delivery row. The HTTP receiver never uses this connection or table.
  9. public async Task<bool> RunOneAsync(CancellationToken token)
  10. {
  11. await using var connection = new MySqlConnection(connectionString);
  12. await connection.OpenAsync(token);
  13. await using var tx = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, token);
  14. using var claim = new MySqlCommand("""
  15. SELECT batch_id,tenant_id,factory_id,source_id,dataset_id,package_json,package_sha256,
  16. event_ordinals,isolated_count,attempt_count
  17. FROM mdp_ingest_purchase_dispatch WHERE status='READY' AND next_attempt_at<=UTC_TIMESTAMP(6)
  18. ORDER BY next_attempt_at,batch_id LIMIT 1 FOR UPDATE SKIP LOCKED
  19. """, connection, tx);
  20. PurchaseTaskLease scope;
  21. byte[] snapshot;
  22. string digest, positions;
  23. int isolatedCount, attempts;
  24. await using (var row = await claim.ExecuteReaderAsync(token))
  25. {
  26. if (!await row.ReadAsync(token)) return false;
  27. scope = new(row.GetGuid(0), row.GetInt64(1), row.GetInt64(2), row.GetInt64(3), row.GetInt64(4),
  28. 0, string.Empty, null, null);
  29. snapshot = row.GetFieldValue<byte[]>(5);
  30. digest = row.GetString(6);
  31. positions = row.GetString(7);
  32. isolatedCount = row.GetInt32(8);
  33. attempts = row.GetInt32(9);
  34. }
  35. var final = "HANDOFF_READY";
  36. string? error = null;
  37. int? accepted = null;
  38. int isolated = 0;
  39. try
  40. {
  41. var package = JsonSerializer.Deserialize<PurchaseHandoffPackage>(snapshot, JsonSerializerOptions.Web);
  42. if (package?.Items is null || package.Items.Any(line => line is null) || package.BatchId != scope.BatchId || package.LeaseToken != string.Empty
  43. || package.TenantId != scope.TenantId || package.FactoryId != scope.FactoryId
  44. || package.SourceId != scope.SourceId || package.DatasetId != scope.DatasetId || package.ComputeDigest() != digest)
  45. throw new PurchaseHandoffException("DISPATCH_SNAPSHOT_INVALID", false);
  46. var events = package.Items.Select(line => line.RawEventId).ToHashSet();
  47. var ordinals = JsonSerializer.Deserialize<Dictionary<Guid, int>>(positions);
  48. if (ordinals is null || events.Count != package.Items.Count || !events.All(ordinals.ContainsKey))
  49. throw new PurchaseHandoffException("DISPATCH_SNAPSHOT_INVALID", false);
  50. // Including on the first claim: a prior dispatcher may have died after remote commit and before local commit.
  51. var receipt = await handoff.FindReceiptAsync(scope.BatchId, digest, token)
  52. ?? await handoff.SubmitAsync(package, token);
  53. if (!receipt.Matches(scope.BatchId, events))
  54. throw new PurchaseHandoffException("HANDOFF_INVALID_RECEIPT", true);
  55. if (receipt.Conflicts.Count > 0)
  56. {
  57. var conflicts = receipt.Conflicts.Distinct().Select(x => new PurchaseIsolation(x, ordinals[x.RawEventId])).ToArray();
  58. await PurchaseWorkerStore.InsertIsolationsAsync(connection, tx, scope, conflicts, token);
  59. }
  60. accepted = receipt.AcceptedCount;
  61. isolated = isolatedCount + receipt.Conflicts.Count;
  62. final = receipt.AcceptedCount == 0 ? "QUARANTINED"
  63. : isolatedCount + receipt.Conflicts.Count == 0 ? "SUCCEEDED" : "PARTIAL";
  64. }
  65. catch (JsonException)
  66. {
  67. error = "DISPATCH_SNAPSHOT_INVALID";
  68. final = "FAILED";
  69. }
  70. catch (PurchaseHandoffException ex)
  71. {
  72. error = ex.Code;
  73. if (!ex.Retry) final = "FAILED";
  74. }
  75. using var update = new MySqlCommand("""
  76. UPDATE mdp_ingest_purchase_dispatch SET status=@Status,attempt_count=attempt_count+1,
  77. next_attempt_at=TIMESTAMPADD(SECOND,@Delay,UTC_TIMESTAMP(6)) WHERE batch_id=@Batch
  78. """, connection, tx);
  79. update.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D"));
  80. update.Parameters.AddWithValue("@Status", final == "HANDOFF_READY" ? "READY" : final == "FAILED" ? "FAILED" : "DONE");
  81. update.Parameters.AddWithValue("@Delay", attempts switch { 0 => 30, 1 => 120, _ => 600 });
  82. await update.ExecuteNonQueryAsync(token);
  83. using var finish = new MySqlCommand("""
  84. UPDATE mdp_ingest_receive_task SET status=@Status,last_error_code=@Error,updated_at_utc=UTC_TIMESTAMP(6)
  85. WHERE batch_id=@Batch AND status='HANDOFF_READY'
  86. """, connection, tx);
  87. finish.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D"));
  88. finish.Parameters.AddWithValue("@Status", final);
  89. finish.Parameters.AddWithValue("@Error", (object?)error ?? DBNull.Value);
  90. if (await finish.ExecuteNonQueryAsync(token) != 1)
  91. throw new InvalidDataException("Confirmed dispatch has no matching pending task.");
  92. if (accepted.HasValue)
  93. {
  94. using var evidence = new MySqlCommand("""
  95. UPDATE mdp_ingest_release_batch SET accepted_count=@Accepted, isolated_count=@Isolated,
  96. acknowledged_at=UTC_TIMESTAMP(6)
  97. WHERE batch_id=@Batch AND acknowledged_at IS NULL
  98. """, connection, tx);
  99. evidence.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D"));
  100. evidence.Parameters.AddWithValue("@Accepted", accepted.Value);
  101. evidence.Parameters.AddWithValue("@Isolated", isolated);
  102. await evidence.ExecuteNonQueryAsync(token);
  103. }
  104. await tx.CommitAsync(token);
  105. Console.WriteLine($"Dispatch {scope.BatchId:D}: {final} {error}");
  106. return true;
  107. }
  108. }