using System.Data; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using MySqlConnector; namespace Admin.NET.DataPlatform.Worker; internal sealed class PurchaseDispatcher(string connectionString, IAidopPackageHandoff handoff) { // Only the dispatcher locks the delivery row. The HTTP receiver never uses this connection or table. public async Task RunOneAsync(CancellationToken token) { await using var connection = new MySqlConnection(connectionString); await connection.OpenAsync(token); await using var tx = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, token); using var claim = new MySqlCommand(""" SELECT batch_id,tenant_id,factory_id,source_id,dataset_id,package_json,package_sha256, event_ordinals,isolated_count,attempt_count FROM mdp_ingest_purchase_dispatch WHERE status='READY' AND next_attempt_at<=UTC_TIMESTAMP(6) ORDER BY next_attempt_at,batch_id LIMIT 1 FOR UPDATE SKIP LOCKED """, connection, tx); PurchaseTaskLease scope; byte[] snapshot; string digest, positions; int isolatedCount, attempts; await using (var row = await claim.ExecuteReaderAsync(token)) { if (!await row.ReadAsync(token)) return false; scope = new(row.GetGuid(0), row.GetInt64(1), row.GetInt64(2), row.GetInt64(3), row.GetInt64(4), 0, string.Empty, null, null); snapshot = row.GetFieldValue(5); digest = row.GetString(6); positions = row.GetString(7); isolatedCount = row.GetInt32(8); attempts = row.GetInt32(9); } var final = "HANDOFF_READY"; string? error = null; int? accepted = null; int isolated = 0; try { var package = JsonSerializer.Deserialize(snapshot, JsonSerializerOptions.Web); if (package?.Items is null || package.Items.Any(line => line is null) || package.BatchId != scope.BatchId || package.LeaseToken != string.Empty || package.TenantId != scope.TenantId || package.FactoryId != scope.FactoryId || package.SourceId != scope.SourceId || package.DatasetId != scope.DatasetId || package.ComputeDigest() != digest) throw new PurchaseHandoffException("DISPATCH_SNAPSHOT_INVALID", false); var events = package.Items.Select(line => line.RawEventId).ToHashSet(); var ordinals = JsonSerializer.Deserialize>(positions); if (ordinals is null || events.Count != package.Items.Count || !events.All(ordinals.ContainsKey)) throw new PurchaseHandoffException("DISPATCH_SNAPSHOT_INVALID", false); // Including on the first claim: a prior dispatcher may have died after remote commit and before local commit. var receipt = await handoff.FindReceiptAsync(scope.BatchId, digest, token) ?? await handoff.SubmitAsync(package, token); if (!receipt.Matches(scope.BatchId, events)) throw new PurchaseHandoffException("HANDOFF_INVALID_RECEIPT", true); if (receipt.Conflicts.Count > 0) { var conflicts = receipt.Conflicts.Distinct().Select(x => new PurchaseIsolation(x, ordinals[x.RawEventId])).ToArray(); await PurchaseWorkerStore.InsertIsolationsAsync(connection, tx, scope, conflicts, token); } accepted = receipt.AcceptedCount; isolated = isolatedCount + receipt.Conflicts.Count; final = receipt.AcceptedCount == 0 ? "QUARANTINED" : isolatedCount + receipt.Conflicts.Count == 0 ? "SUCCEEDED" : "PARTIAL"; } catch (JsonException) { error = "DISPATCH_SNAPSHOT_INVALID"; final = "FAILED"; } catch (PurchaseHandoffException ex) { error = ex.Code; if (!ex.Retry) final = "FAILED"; } using var update = new MySqlCommand(""" UPDATE mdp_ingest_purchase_dispatch SET status=@Status,attempt_count=attempt_count+1, next_attempt_at=TIMESTAMPADD(SECOND,@Delay,UTC_TIMESTAMP(6)) WHERE batch_id=@Batch """, connection, tx); update.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D")); update.Parameters.AddWithValue("@Status", final == "HANDOFF_READY" ? "READY" : final == "FAILED" ? "FAILED" : "DONE"); update.Parameters.AddWithValue("@Delay", attempts switch { 0 => 30, 1 => 120, _ => 600 }); await update.ExecuteNonQueryAsync(token); using var finish = new MySqlCommand(""" UPDATE mdp_ingest_receive_task SET status=@Status,last_error_code=@Error,updated_at_utc=UTC_TIMESTAMP(6) WHERE batch_id=@Batch AND status='HANDOFF_READY' """, connection, tx); finish.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D")); finish.Parameters.AddWithValue("@Status", final); finish.Parameters.AddWithValue("@Error", (object?)error ?? DBNull.Value); if (await finish.ExecuteNonQueryAsync(token) != 1) throw new InvalidDataException("Confirmed dispatch has no matching pending task."); if (accepted.HasValue) { using var evidence = new MySqlCommand(""" UPDATE mdp_ingest_release_batch SET accepted_count=@Accepted, isolated_count=@Isolated, acknowledged_at=UTC_TIMESTAMP(6) WHERE batch_id=@Batch AND acknowledged_at IS NULL """, connection, tx); evidence.Parameters.AddWithValue("@Batch", scope.BatchId.ToString("D")); evidence.Parameters.AddWithValue("@Accepted", accepted.Value); evidence.Parameters.AddWithValue("@Isolated", isolated); await evidence.ExecuteNonQueryAsync(token); } await tx.CommitAsync(token); Console.WriteLine($"Dispatch {scope.BatchId:D}: {final} {error}"); return true; } }