| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433 |
- using Microsoft.Extensions.Configuration;
- using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed partial class MdpRelationalSyncService(
- ISqlSugarClient db, IConfiguration settings, MdpPurchaseHandoffService receiver) : ITransient
- {
- internal async Task<object[]> ListAsync(long tenantId, long factoryId, long id)
- {
- using var store = MdpIngestDatabase.Open(db);
- var rows = await store.Ado.SqlQueryAsync<RelationalRun>(SyncRunSelect + "\n" + """
- WHERE tenant_id=@tenantId AND factory_id=@factoryId AND dataset_id=@id
- ORDER BY created_at_utc DESC LIMIT 30
- """, new { tenantId, factoryId, id });
- return rows.Select(MapRun).ToArray();
- }
- internal async Task<object> RunAsync(RelationalTrialProfile profile, Guid? prior, string mode, CancellationToken token,
- string? scheduledSignature = null)
- {
- if (!profile.SyncEnabled || (mode is "INCR" or "REPLAY" && !HasAppendLog(profile) && !HasTimeSource(profile)))
- throw new MdpIngestHttpException(409, "RELATIONAL_MODE_UNAVAILABLE");
- using var store = MdpIngestDatabase.Open(db);
- var dataset = await store.Queryable<MdpIngestDataset>()
- .Where(row => row.Id == profile.DatasetId && row.TenantId == profile.TenantId
- && row.FactoryId == profile.FactoryId && row.Enabled)
- .FirstAsync(token);
- var source = await store.Queryable<MdpSource>()
- .Where(row => row.Id == profile.SourceId && row.TenantId == profile.TenantId && row.Status == 1)
- .FirstAsync(token);
- if (source is null || dataset?.ActiveSchemaVersion is null
- || await store.Ado.SqlQuerySingleAsync<string>(
- "SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@DatasetId", new { profile.DatasetId }) != "ACTIVE")
- throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
- var (_, binding, configuration) = await CreateRelationalTrial(store, profile, dataset, source);
- var signature = Signature(profile, binding);
- var runId = (prior ?? Guid.NewGuid()).ToString("D");
- var run = prior.HasValue
- ? await FindScopedRun(store, runId, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.Id)
- ?? throw new MdpIngestHttpException(404, "RELATIONAL_RUN_NOT_FOUND")
- : null;
- if (run is not null && (run.ScopeVersion != signature || run.SourceId != profile.SourceId
- || run.SchemaVersion != binding.SourceSchemaVersion))
- {
- if (run.Phase is "RECEIVING" or "RECONCILING")
- await RecordRecovery(store, runId, ChangedPlanReason);
- throw new MdpIngestHttpException(409, "RELATIONAL_PLAN_CHANGED");
- }
- if (scheduledSignature is not null && signature != scheduledSignature)
- throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
- var (address, key) = await LoadRelationalReceiver(store, profile, dataset, token);
- if (run is null)
- {
- var baseline = mode is "INCR" or "REPLAY" ? await LatestCompleted(store, profile, signature) : null;
- if (baseline?.RecoveryReason == HistoryExpiredReason)
- throw new MdpIngestHttpException(409, "RELATIONAL_REINITIALIZATION_REQUIRED");
- var report = await InspectProfile(profile, binding, token);
- var issue = report.Checks.FirstOrDefault(x => x.Severity == "block");
- if (issue is not null) throw new MdpIngestHttpException(409, issue.Code);
- try
- {
- await FreezeRelationalRun(store, profile, binding, signature, runId, mode, token);
- }
- catch (ConnectorContractException error) when (error.Code == ConnectorError.HistoryExpired && baseline is not null)
- {
- await RecordRecovery(store, baseline.RunId, HistoryExpiredReason);
- throw new MdpIngestHttpException(409, "RELATIONAL_REINITIALIZATION_REQUIRED");
- }
- run = await FindRun(store, runId, binding, profile.Id)
- ?? throw new MdpIngestHttpException(404, "RELATIONAL_RUN_NOT_FOUND");
- }
- await ReceiveFrozenPages(store, run, binding,
- (frozen, cancellation) => SubmitRelationalTrial(address, binding.Identity.DatasetKey, frozen, key, cancellation), token);
- var received = await FindRun(store, runId, binding, profile.Id);
- await ReconcileRelationalRun(store, received!, binding, configuration, token);
- return MapRun((await FindRun(store, runId, binding, profile.Id))!);
- }
- internal async Task<bool> RunScheduledAsync(long tenantId, string taskCode, CancellationToken token)
- {
- using var store = MdpIngestDatabase.Open(db);
- var assigned = await store.Ado.SqlQuerySingleAsync<RelationalScheduleBinding?>("""
- SELECT factory_id AS FactoryId,dataset_id AS DatasetId,source_id AS SourceId,profile_id AS ProfileId,
- scope_version AS ScopeVersion,task_code AS TaskCode
- FROM mdp_connector_relational_schedule WHERE tenant_id=@tenantId AND task_code=@taskCode
- """, new { tenantId, taskCode });
- var profiles = (await ReadProfiles(settings["MDP_RELATIONAL_TRIALS_FILE"], token))
- .Where(p => p.SyncEnabled && p.TenantId == tenantId);
- var profile = assigned is null
- ? profiles.SingleOrDefault(p => string.Equals(p.ScheduleTaskCode, taskCode, StringComparison.Ordinal))
- : profiles.SingleOrDefault(p => p.Id == assigned.ProfileId && p.FactoryId == assigned.FactoryId
- && p.DatasetId == assigned.DatasetId && p.SourceId == assigned.SourceId);
- if (profile is null)
- {
- if (assigned is not null) throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
- return false;
- }
- if (assigned is null && await BoundSchedule(store, profile) is not null) return false;
- if (assigned is not null)
- {
- var sourceCode = await store.Queryable<MdpSource>().Where(s => s.Id == profile.SourceId
- && s.TenantId == tenantId && s.Status == 1).Select(s => s.SourceCode).FirstAsync(token);
- if (assigned.ScopeVersion is null || sourceCode is null || !(await EligibleTasksAsync(store, profile, sourceCode, token))
- .Any(task => string.Equals(task.TaskCode, taskCode, StringComparison.Ordinal)))
- throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
- }
- using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
- deadline.CancelAfter(TimeSpan.FromSeconds(75));
- var latest = await store.Ado.SqlQuerySingleAsync<RelationalRun>(SyncRunSelect + "\n" + """
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
- AND source_id=@SourceId AND profile_id=@Id AND (active_slot=1 OR phase IN ('SUCCEEDED','REVIEW'))
- AND (@version IS NULL OR scope_version=@version OR active_slot=1)
- AND (active_slot=1 OR EXISTS (
- SELECT 1 FROM mdp_connector_relational_sync_window w
- WHERE w.run_id=mdp_connector_relational_sync_run.run_id AND w.mode IN ('FULL','INCR')
- ))
- ORDER BY (active_slot=1) DESC,created_at_utc DESC LIMIT 1
- """, new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, version = assigned?.ScopeVersion });
- if (latest?.Phase == "REVIEW")
- throw new MdpIngestHttpException(409, "RELATIONAL_RECONCILIATION_REQUIRED");
- Guid? running = latest?.Phase is "RECEIVING" or "RECONCILING" ? Guid.Parse(latest.RunId) : null;
- var baselineReady = latest?.Phase == "SUCCEEDED" &&
- (latest.ProvenPages == latest.PageCount || (assigned is null && latest.Mode == "INCR"));
- var mode = baselineReady && (HasAppendLog(profile) || HasTimeSource(profile)) ? "INCR" : "FULL";
- await RunAsync(profile, running, mode, deadline.Token, assigned?.ScopeVersion);
- return true;
- }
- private static string Signature(RelationalTrialProfile profile, ConnectorBinding binding) =>
- Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
- {
- profile.Id, profile.Driver, profile.Database, profile.Schema, profile.Table, profile.PositionColumn,
- profile.Columns, profile.OdbcFamily, profile.Preflight, profile.SyncPageSize, profile.LookbackPositions,
- profile.FieldRules, profile.ConnectionString, binding.ConfigVersion,
- }, RelationalTrialJson)));
- private static async Task FreezeRelationalRun(SqlSugarClient store, RelationalTrialProfile profile, ConnectorBinding binding,
- string signature, string runId, string mode, CancellationToken token)
- {
- var identity = binding.Identity;
- var tx = await store.Ado.UseTranAsync(async () =>
- {
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_relational_sync_run
- (run_id,tenant_id,factory_id,dataset_id,source_id,profile_id,scope_version,schema_version,phase,
- active_slot,created_at_utc,updated_at_utc)
- VALUES (@runId,@TenantId,@FactoryId,@DatasetId,@SourceId,@profileId,@signature,
- @SourceSchemaVersion,'FROZEN',1,UTC_TIMESTAMP(6),UTC_TIMESTAMP(6))
- """, new { runId, identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId,
- profileId = profile.Id, signature, binding.SourceSchemaVersion });
- RelationalLogWindow? window = null;
- if (HasAppendLog(profile))
- {
- var previous = await store.Ado.SqlQuerySingleAsync<long?>("""
- SELECT MAX(w.to_position) FROM mdp_connector_relational_sync_window w
- JOIN mdp_connector_relational_sync_run r ON r.run_id=w.run_id
- WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId
- AND r.source_id=@SourceId AND r.profile_id=@profileId AND r.scope_version=@signature
- AND r.phase='SUCCEEDED' AND w.mode IN ('FULL','INCR')
- AND (w.mode='INCR' OR r.page_count=(SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=r.run_id AND x.issue_code IS NULL))
- """, new { identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId, profileId = profile.Id, signature });
- if (mode != "FULL" && !previous.HasValue)
- throw new MdpIngestHttpException(409, "RELATIONAL_FULL_RECONCILIATION_REQUIRED");
- window = new(mode == "FULL" ? null : previous, mode == "REPLAY" ? profile.LookbackPositions : 0, mode == "REPLAY");
- }
- RelationalTimeCapture? time = null;
- if (HasTimeSource(profile) && profile.Preflight is { } config)
- {
- var previous = await store.Ado.SqlQuerySingleAsync<DateTime?>("""
- SELECT MAX(w.to_utc) FROM mdp_connector_relational_time_window w
- JOIN mdp_connector_relational_sync_run r ON r.run_id=w.run_id
- JOIN mdp_connector_relational_sync_window m ON m.run_id=w.run_id
- WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId
- AND r.source_id=@SourceId AND r.profile_id=@profileId AND r.scope_version=@signature
- AND r.phase='SUCCEEDED' AND m.mode IN ('FULL','INCR')
- AND (m.mode='INCR' OR r.page_count=(SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=r.run_id AND x.issue_code IS NULL))
- """, new { identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId, profileId = profile.Id, signature });
- if (mode != "FULL" && !previous.HasValue)
- throw new MdpIngestHttpException(409, "RELATIONAL_FULL_RECONCILIATION_REQUIRED");
- time = new(config.IncrementalField!,
- mode == "FULL" ? null : new DateTimeOffset(DateTime.SpecifyKind(previous!.Value, DateTimeKind.Utc)),
- config.MaxCommitDelaySeconds!.Value, config.LookbackSeconds!.Value, config.RetentionSeconds!.Value, mode == "REPLAY",
- config.DeletePolicy == "snapshot-difference" ? config.SnapshotFenceTable : null,
- config.DeletePolicy == "snapshot-difference" ? config.SnapshotFenceColumn : null);
- }
- var execution = TrialExecution(profile, binding);
- await using var source = await TrialDriver(profile, execution).OpenReadOnlyAsync(execution, profile.Id, token);
- if (source is not IRelationalSnapshotSource snapshot)
- throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
- var snapshotKeys = time is { Completed: null, FenceTable: not null } ? await ReadSnapshotKeyNames(store, binding) : null;
- async Task FreezePage(ConnectorBatchCandidate page, int ordinal, CancellationToken cancellation)
- {
- cancellation.ThrowIfCancellationRequested();
- if (snapshotKeys is not null)
- await SaveSnapshotKeys(store, runId, page, snapshotKeys);
- var id = "relational-sync-" + runId + "-" + ordinal.ToString(CultureInfo.InvariantCulture);
- var frozen = ConnectorFrozenBatch.Capture(binding, page with { SenderBatchId = id, IdempotencyKey = id });
- 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,@payload,@position,@next)
- """, new { runId, ordinal, id, sha = frozen.Pending.Id.PayloadSha256, payload = frozen.Payload.ToArray(),
- position = frozen.Pending.SourcePosition, next = frozen.Pending.NextCheckpoint });
- }
- RelationalSnapshotSummary summary;
- if (time is not null)
- {
- if (source is not IRelationalTimeSnapshotSource timeSource)
- throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
- var capture = await timeSource.CaptureTimeAsync(profile.SyncPageSize, FreezePage, time, token);
- summary = new(capture.RowCount, capture.PageCount);
- if (snapshotKeys is not null)
- {
- var fence = capture.Fence ?? throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
- var removed = await FreezeSnapshotDeletes(store, binding, runId, signature, snapshotKeys, fence,
- summary.PageCount, token);
- summary = summary with { RowCount = summary.RowCount + removed.Rows, PageCount = summary.PageCount + removed.Pages };
- }
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_relational_time_window (run_id,from_utc,to_utc)
- VALUES (@runId,@fromUtc,@toUtc)
- """, new { runId, fromUtc = capture.From?.UtcDateTime, toUtc = capture.To.UtcDateTime });
- }
- else
- summary = await snapshot.CaptureAsync(profile.SyncPageSize, FreezePage, token, window);
- token.ThrowIfCancellationRequested();
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_relational_sync_window (run_id,mode,from_position,to_position)
- VALUES (@runId,@mode,@fromPosition,@toPosition)
- """, new { runId, mode, fromPosition = window?.Start, toPosition = summary.UpperPosition ?? 0 });
- if (profile.Preflight?.SourceGeneration is > 0 and var sourceGeneration)
- await store.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_relational_change_run (run_id,source_generation)
- VALUES (@runId,@sourceGeneration)
- """, new { runId, sourceGeneration });
- await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_run
- SET row_count=@RowCount,page_count=@PageCount,phase='RECEIVING',updated_at_utc=UTC_TIMESTAMP(6)
- WHERE run_id=@runId
- """, new { runId, summary.RowCount, summary.PageCount });
- });
- if (!tx.IsSuccess) throw tx.ErrorException!;
- }
- private static async Task ReceiveFrozenPages(SqlSugarClient store, RelationalRun run, ConnectorBinding binding,
- Func<ConnectorFrozenBatch, CancellationToken, Task<MdpIngestReceipt>>? submit, CancellationToken token)
- {
- if (run.Phase != "RECEIVING") return;
- var lease = Guid.NewGuid().ToString("D");
- if (await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_run SET lease_token=@lease,lease_until_utc=UTC_TIMESTAMP(6)+INTERVAL 100 SECOND
- WHERE run_id=@RunId AND phase='RECEIVING'
- AND (lease_until_utc IS NULL OR lease_until_utc<UTC_TIMESTAMP(6))
- """, new { run.RunId, lease }) != 1)
- throw new MdpIngestHttpException(409, "RELATIONAL_RUN_BUSY");
- try
- {
- var pages = await store.Ado.SqlQueryAsync<RelationalPage>("""
- SELECT ordinal,idem_key AS IdemKey,payload_sha256 AS PayloadSha256,payload,
- position_key AS Position,next_position AS NextPosition
- FROM mdp_connector_relational_sync_page WHERE run_id=@RunId AND raw_id IS NULL
- ORDER BY ordinal LIMIT 8
- """, new { run.RunId });
- foreach (var page in pages)
- {
- token.ThrowIfCancellationRequested();
- var identity = new ConnectorBatchIdentity(binding, page.IdemKey, page.IdemKey, page.PayloadSha256);
- var pending = new ConnectorPendingBatch(identity, page.Position, page.NextPosition);
- var frozen = ConnectorFrozenBatch.Restore(pending, page.Payload);
- var raw = await FindFrozenReceipt(store, run, page);
- if (raw == Guid.Empty)
- {
- if (submit is null) break;
- if (run.CreatedAtUtc <= DateTime.UtcNow.AddDays(-6))
- throw new MdpIngestHttpException(409, "RELATIONAL_RECEIPT_RECONCILIATION_REQUIRED");
- var receipt = await submit(frozen, token);
- if (receipt.BatchId == Guid.Empty || receipt.SchemaVersion != binding.SourceSchemaVersion
- || receipt.ReceiveStatus != "accepted" || receipt.AcceptedRecordCount <= 0)
- throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
- raw = receipt.BatchId;
- }
- var decision = ConnectorResume.Decide(binding, pending, new(identity, ConnectorConfirmation.CloudDurable, raw), frozen);
- if (decision.Action != ConnectorResumeAction.Advance)
- throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
- var progress = await store.Ado.UseTranAsync(async () =>
- {
- var args = new { run.RunId, page.Ordinal, previous = page.Ordinal - 1, lease,
- raw = raw.ToString("D"), next = decision.NextCheckpoint };
- if (await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_run
- SET committed_page=@Ordinal,committed_position=@next,committed_raw_id=@raw,
- updated_at_utc=UTC_TIMESTAMP(6)
- WHERE run_id=@RunId AND lease_token=@lease AND lease_until_utc>UTC_TIMESTAMP(6)
- AND committed_page=@previous
- """, args) != 1)
- throw new MdpIngestHttpException(409, "RELATIONAL_RUN_LEASE_LOST");
- if (await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_page SET raw_id=@raw
- WHERE run_id=@RunId AND ordinal=@Ordinal AND raw_id IS NULL
- """, args) != 1)
- throw new MdpIngestHttpException(409, "RELATIONAL_PAGE_STATE_CONFLICT");
- });
- if (!progress.IsSuccess) throw progress.ErrorException!;
- }
- await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_run SET phase='RECONCILING',updated_at_utc=UTC_TIMESTAMP(6)
- WHERE run_id=@RunId AND lease_token=@lease AND lease_until_utc>UTC_TIMESTAMP(6) AND page_count=committed_page
- """, new { run.RunId, lease });
- }
- finally
- {
- await store.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_relational_sync_run SET lease_token=NULL,lease_until_utc=NULL
- WHERE run_id=@RunId AND lease_token=@lease
- """, new { run.RunId, lease });
- }
- }
- private static async Task<Guid> FindFrozenReceipt(SqlSugarClient store, RelationalRun run, RelationalPage page)
- {
- var found = await store.Ado.SqlQuerySingleAsync<PersistedRelationalReceipt>("""
- SELECT batch_id AS BatchId,payload_sha256 AS PayloadSha256,source_schema_version AS SchemaVersion
- FROM mdp_ingest_raw_batch
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
- AND source_id=@SourceId AND idempotency_key=@IdemKey
- """, new { run.TenantId, run.FactoryId, run.DatasetId, run.SourceId, page.IdemKey });
- if (found is null) return Guid.Empty;
- if (found.PayloadSha256 != page.PayloadSha256 || found.SchemaVersion != run.SchemaVersion
- || !Guid.TryParse(found.BatchId, out var id) || id == Guid.Empty)
- throw new MdpIngestHttpException(409, "RELATIONAL_RECEIPT_MISMATCH");
- return id;
- }
- private static Task<RelationalRun?> FindRun(SqlSugarClient store, string runId, ConnectorBinding binding, string profileId)
- {
- var scope = binding.Identity;
- return store.Ado.SqlQuerySingleAsync<RelationalRun>(SyncRunSelect + "\n" + """
- WHERE run_id=@runId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
- AND source_id=@SourceId AND profile_id=@profileId
- """, new { runId, scope.TenantId, scope.FactoryId, scope.DatasetId, scope.SourceId, profileId });
- }
- private static object MapRun(RelationalRun run) => new
- {
- run.RunId, run.ProfileId, run.Phase, run.RowCount, run.PageCount, run.CommittedPage,
- run.CommittedPosition, run.CommittedRawId, run.CreatedAtUtc, run.Mode, run.WindowStart, run.WindowEnd,
- run.ProvenPages, run.CheckedRows, run.ProofIssue, run.ProofKey, run.RecoveryReason,
- windowFromUtc = run.WindowFromUtc.HasValue ? DateTime.SpecifyKind(run.WindowFromUtc.Value, DateTimeKind.Utc) : (DateTime?)null,
- windowToUtc = run.WindowToUtc.HasValue ? DateTime.SpecifyKind(run.WindowToUtc.Value, DateTimeKind.Utc) : (DateTime?)null,
- };
- private const string SyncRunSelect = """
- SELECT run_id AS RunId,tenant_id AS TenantId,factory_id AS FactoryId,dataset_id AS DatasetId,source_id AS SourceId,
- profile_id AS ProfileId,scope_version AS ScopeVersion,schema_version AS SchemaVersion,phase,
- row_count AS RowCount,page_count AS PageCount,committed_page AS CommittedPage,
- committed_position AS CommittedPosition,committed_raw_id AS CommittedRawId,created_at_utc AS CreatedAtUtc,
- (SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=mdp_connector_relational_sync_run.run_id AND x.issue_code IS NULL) AS ProvenPages,
- (SELECT COALESCE(SUM(x.checked_rows),0) FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=mdp_connector_relational_sync_run.run_id) AS CheckedRows,
- (SELECT x.issue_code FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=mdp_connector_relational_sync_run.run_id AND x.issue_code IS NOT NULL ORDER BY x.ordinal LIMIT 1) AS ProofIssue,
- (SELECT x.issue_key FROM mdp_connector_relational_sync_proof x
- WHERE x.run_id=mdp_connector_relational_sync_run.run_id AND x.issue_code IS NOT NULL ORDER BY x.ordinal LIMIT 1) AS ProofKey,
- (SELECT h.reason FROM mdp_connector_relational_sync_recovery h
- WHERE h.run_id=mdp_connector_relational_sync_run.run_id AND h.resolved_at_utc IS NULL
- ORDER BY h.detected_at_utc DESC,h.reason LIMIT 1) AS RecoveryReason,
- (SELECT w.mode FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS Mode,
- (SELECT w.from_position FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowStart,
- (SELECT w.to_position FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowEnd,
- (SELECT w.from_utc FROM mdp_connector_relational_time_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowFromUtc,
- (SELECT w.to_utc FROM mdp_connector_relational_time_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowToUtc
- FROM mdp_connector_relational_sync_run
- """;
- private sealed class RelationalRun
- {
- public string RunId { get; set; } = "";
- public long TenantId { get; set; }
- public long FactoryId { get; set; }
- public long DatasetId { get; set; }
- public long SourceId { get; set; }
- public string ProfileId { get; set; } = "";
- public string ScopeVersion { get; set; } = "";
- public string SchemaVersion { get; set; } = "";
- public string Phase { get; set; } = "";
- public long RowCount { get; set; }
- public int PageCount { get; set; }
- public int CommittedPage { get; set; }
- public int ProvenPages { get; set; }
- public long CheckedRows { get; set; }
- public string? ProofIssue { get; set; }
- public string? ProofKey { get; set; }
- public string? RecoveryReason { get; set; }
- public string? CommittedPosition { get; set; }
- public string? CommittedRawId { get; set; }
- public DateTime CreatedAtUtc { get; set; }
- public string? Mode { get; set; }
- public long? WindowStart { get; set; }
- public long? WindowEnd { get; set; }
- public DateTime? WindowFromUtc { get; set; }
- public DateTime? WindowToUtc { get; set; }
- }
- private sealed class RelationalPage
- {
- public int Ordinal { get; set; }
- public string IdemKey { get; set; } = "";
- public string PayloadSha256 { get; set; } = "";
- public byte[] Payload { get; set; } = [];
- public string Position { get; set; } = "";
- public string NextPosition { get; set; } = "";
- }
- private sealed class PersistedRelationalReceipt
- {
- public string BatchId { get; set; } = "";
- public string PayloadSha256 { get; set; } = "";
- public string SchemaVersion { get; set; } = "";
- }
- }
|