| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- using System.Globalization;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed partial class MdpRelationalSyncService
- {
- private sealed record SnapshotKeyNames(string Order, string Line);
- private static async Task<SnapshotKeyNames> ReadSnapshotKeyNames(ISqlSugarClient store, ConnectorBinding binding)
- {
- var scope = binding.Identity;
- var registry = new MdpIngestDatasetRegistry(store);
- var active = await registry.ResolveActiveBindingAsync(scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetKey);
- if (active is null || active.DatasetId != scope.DatasetId || active.SourceSchemaVersion != binding.SourceSchemaVersion)
- throw new ConnectorContractException(ConnectorError.ScopeMismatch);
- var mapping = await registry.ReadPublishedMapping(active)
- ?? throw new ConnectorContractException(ConnectorError.InvalidManifest);
- var config = new PurchaseVersionConfiguration(scope.DatasetKey, active.SourceSchemaVersion, mapping);
- return new(config.Names["PoNo"], config.Names["PoLine"]);
- }
- private static async Task SaveSnapshotKeys(ISqlSugarClient store, string runId, ConnectorBatchCandidate page,
- SnapshotKeyNames names)
- {
- using var source = JsonDocument.Parse(page.Payload);
- foreach (var row in source.RootElement.GetProperty("data").GetProperty("list").EnumerateArray())
- {
- var order = ReadKey(row, names.Order, 100);
- var line = ReadKey(row, names.Line, 50);
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_purchase_snapshot_key (run_id,po_no,po_line)
- VALUES (@runId,@order,@line)
- """, new { runId, order, line });
- }
- }
- private static string ReadKey(JsonElement row, string name, int limit)
- {
- if (!row.TryGetProperty(name, out var key) || key.ValueKind != JsonValueKind.String
- || key.GetString() is not { } value || value.Length > limit
- || string.IsNullOrWhiteSpace(value) || value.Contains('#'))
- throw new ConnectorContractException(ConnectorError.InvalidBatch);
- return value;
- }
- private static async Task<(long Rows, int Pages)> FreezeSnapshotDeletes(SqlSugarClient store, ConnectorBinding binding,
- string runId, string signature, SnapshotKeyNames names, long fence, int previousPageCount, CancellationToken token)
- {
- var scope = binding.Identity;
- var baseline = await store.Ado.SqlQuerySingleAsync<SnapshotBaseline>("""
- SELECT s.run_id AS RunId,s.fence_version AS Fence
- FROM mdp_connector_purchase_snapshot s JOIN mdp_connector_relational_sync_run r ON r.run_id=s.run_id
- WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId AND r.source_id=@SourceId
- AND r.scope_version=@signature AND r.phase='SUCCEEDED'
- ORDER BY r.created_at_utc DESC LIMIT 1
- """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, scope.SourceId, signature });
- if (baseline is not null && fence < baseline.Fence)
- throw new ConnectorContractException(ConnectorError.InvalidBatch);
- long removed = 0;
- var pages = 0;
- if (baseline is not null)
- {
- string? lastNo = null, lastLine = null;
- while (true)
- {
- token.ThrowIfCancellationRequested();
- var missing = await store.Ado.SqlQueryAsync<SnapshotKey>("""
- SELECT old.po_no AS PoNo,old.po_line AS PoLine
- FROM mdp_connector_purchase_snapshot_key old
- LEFT JOIN mdp_connector_purchase_snapshot_key now_key ON now_key.run_id=@runId
- AND now_key.po_no=old.po_no AND now_key.po_line=old.po_line
- WHERE old.run_id=@previous AND now_key.po_no IS NULL
- AND (@lastNo IS NULL OR old.po_no>@lastNo OR (old.po_no=@lastNo AND old.po_line>@lastLine))
- ORDER BY old.po_no,old.po_line LIMIT 100
- """, new { runId, previous = baseline.RunId, lastNo, lastLine });
- if (missing.Count == 0) break;
- if (fence <= baseline.Fence)
- throw new ConnectorContractException(ConnectorError.InvalidBatch);
- if (names.Order.StartsWith("_mdp", StringComparison.Ordinal) || names.Line.StartsWith("_mdp", StringComparison.Ordinal))
- throw new ConnectorContractException(ConnectorError.InvalidManifest);
- var body = JsonSerializer.SerializeToUtf8Bytes(new
- {
- factoryId = scope.FactoryId.ToString(CultureInfo.InvariantCulture),
- data = new
- {
- list = missing.Select(key => new Dictionary<string, object>
- {
- [names.Order] = key.PoNo, [names.Line] = key.PoLine,
- ["_mdpChangeVersion"] = fence, ["_mdpDeleted"] = true,
- }),
- },
- });
- var ordinal = previousPageCount + ++pages;
- var id = "relational-sync-" + runId + "-" + ordinal.ToString(CultureInfo.InvariantCulture);
- var position = "snapshot-delete:" + ordinal.ToString(CultureInfo.InvariantCulture);
- var frozen = ConnectorFrozenBatch.Capture(binding, new(id, id, body, position, position, false));
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_relational_sync_page
- (run_id,ordinal,idem_key,payload_sha256,payload,position_key,next_position)
- VALUES (@runId,@ordinal,@id,@sha,@body,@position,@position)
- """, new { runId, ordinal, id, sha = frozen.Pending.Id.PayloadSha256, body, position });
- removed += missing.Count;
- lastNo = missing[^1].PoNo;
- lastLine = missing[^1].PoLine;
- if (missing.Count < 100) break;
- }
- }
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_purchase_snapshot (run_id,fence_version) VALUES (@runId,@fence)
- """, new { runId, fence });
- return (removed, pages);
- }
- private sealed class SnapshotBaseline
- {
- public string RunId { get; set; } = "";
- public long Fence { get; set; }
- }
- private sealed class SnapshotKey
- {
- public string PoNo { get; set; } = "";
- public string PoLine { get; set; } = "";
- }
- }
|