MdpRelationalSyncService.SnapshotDeletes.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using System.Globalization;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed partial class MdpRelationalSyncService
  7. {
  8. private sealed record SnapshotKeyNames(string Order, string Line);
  9. private static async Task<SnapshotKeyNames> ReadSnapshotKeyNames(ISqlSugarClient store, ConnectorBinding binding)
  10. {
  11. var scope = binding.Identity;
  12. var registry = new MdpIngestDatasetRegistry(store);
  13. var active = await registry.ResolveActiveBindingAsync(scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetKey);
  14. if (active is null || active.DatasetId != scope.DatasetId || active.SourceSchemaVersion != binding.SourceSchemaVersion)
  15. throw new ConnectorContractException(ConnectorError.ScopeMismatch);
  16. var mapping = await registry.ReadPublishedMapping(active)
  17. ?? throw new ConnectorContractException(ConnectorError.InvalidManifest);
  18. var config = new PurchaseVersionConfiguration(scope.DatasetKey, active.SourceSchemaVersion, mapping);
  19. return new(config.Names["PoNo"], config.Names["PoLine"]);
  20. }
  21. private static async Task SaveSnapshotKeys(ISqlSugarClient store, string runId, ConnectorBatchCandidate page,
  22. SnapshotKeyNames names)
  23. {
  24. using var source = JsonDocument.Parse(page.Payload);
  25. foreach (var row in source.RootElement.GetProperty("data").GetProperty("list").EnumerateArray())
  26. {
  27. var order = ReadKey(row, names.Order, 100);
  28. var line = ReadKey(row, names.Line, 50);
  29. await store.Ado.ExecuteCommandAsync("""
  30. INSERT INTO mdp_connector_purchase_snapshot_key (run_id,po_no,po_line)
  31. VALUES (@runId,@order,@line)
  32. """, new { runId, order, line });
  33. }
  34. }
  35. private static string ReadKey(JsonElement row, string name, int limit)
  36. {
  37. if (!row.TryGetProperty(name, out var key) || key.ValueKind != JsonValueKind.String
  38. || key.GetString() is not { } value || value.Length > limit
  39. || string.IsNullOrWhiteSpace(value) || value.Contains('#'))
  40. throw new ConnectorContractException(ConnectorError.InvalidBatch);
  41. return value;
  42. }
  43. private static async Task<(long Rows, int Pages)> FreezeSnapshotDeletes(SqlSugarClient store, ConnectorBinding binding,
  44. string runId, string signature, SnapshotKeyNames names, long fence, int previousPageCount, CancellationToken token)
  45. {
  46. var scope = binding.Identity;
  47. var baseline = await store.Ado.SqlQuerySingleAsync<SnapshotBaseline>("""
  48. SELECT s.run_id AS RunId,s.fence_version AS Fence
  49. FROM mdp_connector_purchase_snapshot s JOIN mdp_connector_relational_sync_run r ON r.run_id=s.run_id
  50. WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId AND r.source_id=@SourceId
  51. AND r.scope_version=@signature AND r.phase='SUCCEEDED'
  52. ORDER BY r.created_at_utc DESC LIMIT 1
  53. """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, scope.SourceId, signature });
  54. if (baseline is not null && fence < baseline.Fence)
  55. throw new ConnectorContractException(ConnectorError.InvalidBatch);
  56. long removed = 0;
  57. var pages = 0;
  58. if (baseline is not null)
  59. {
  60. string? lastNo = null, lastLine = null;
  61. while (true)
  62. {
  63. token.ThrowIfCancellationRequested();
  64. var missing = await store.Ado.SqlQueryAsync<SnapshotKey>("""
  65. SELECT old.po_no AS PoNo,old.po_line AS PoLine
  66. FROM mdp_connector_purchase_snapshot_key old
  67. LEFT JOIN mdp_connector_purchase_snapshot_key now_key ON now_key.run_id=@runId
  68. AND now_key.po_no=old.po_no AND now_key.po_line=old.po_line
  69. WHERE old.run_id=@previous AND now_key.po_no IS NULL
  70. AND (@lastNo IS NULL OR old.po_no>@lastNo OR (old.po_no=@lastNo AND old.po_line>@lastLine))
  71. ORDER BY old.po_no,old.po_line LIMIT 100
  72. """, new { runId, previous = baseline.RunId, lastNo, lastLine });
  73. if (missing.Count == 0) break;
  74. if (fence <= baseline.Fence)
  75. throw new ConnectorContractException(ConnectorError.InvalidBatch);
  76. if (names.Order.StartsWith("_mdp", StringComparison.Ordinal) || names.Line.StartsWith("_mdp", StringComparison.Ordinal))
  77. throw new ConnectorContractException(ConnectorError.InvalidManifest);
  78. var body = JsonSerializer.SerializeToUtf8Bytes(new
  79. {
  80. factoryId = scope.FactoryId.ToString(CultureInfo.InvariantCulture),
  81. data = new
  82. {
  83. list = missing.Select(key => new Dictionary<string, object>
  84. {
  85. [names.Order] = key.PoNo, [names.Line] = key.PoLine,
  86. ["_mdpChangeVersion"] = fence, ["_mdpDeleted"] = true,
  87. }),
  88. },
  89. });
  90. var ordinal = previousPageCount + ++pages;
  91. var id = "relational-sync-" + runId + "-" + ordinal.ToString(CultureInfo.InvariantCulture);
  92. var position = "snapshot-delete:" + ordinal.ToString(CultureInfo.InvariantCulture);
  93. var frozen = ConnectorFrozenBatch.Capture(binding, new(id, id, body, position, position, false));
  94. await store.Ado.ExecuteCommandAsync("""
  95. INSERT INTO mdp_connector_relational_sync_page
  96. (run_id,ordinal,idem_key,payload_sha256,payload,position_key,next_position)
  97. VALUES (@runId,@ordinal,@id,@sha,@body,@position,@position)
  98. """, new { runId, ordinal, id, sha = frozen.Pending.Id.PayloadSha256, body, position });
  99. removed += missing.Count;
  100. lastNo = missing[^1].PoNo;
  101. lastLine = missing[^1].PoLine;
  102. if (missing.Count < 100) break;
  103. }
  104. }
  105. await store.Ado.ExecuteCommandAsync("""
  106. INSERT INTO mdp_connector_purchase_snapshot (run_id,fence_version) VALUES (@runId,@fence)
  107. """, new { runId, fence });
  108. return (removed, pages);
  109. }
  110. private sealed class SnapshotBaseline
  111. {
  112. public string RunId { get; set; } = "";
  113. public long Fence { get; set; }
  114. }
  115. private sealed class SnapshotKey
  116. {
  117. public string PoNo { get; set; } = "";
  118. public string PoLine { get; set; } = "";
  119. }
  120. }