MdpRelationalSyncService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using Microsoft.Extensions.Configuration;
  2. using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
  3. using System.Globalization;
  4. using System.Security.Cryptography;
  5. using System.Text.Json;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  7. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  8. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  9. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  10. public sealed partial class MdpRelationalSyncService(
  11. ISqlSugarClient db, IConfiguration settings, MdpPurchaseHandoffService receiver) : ITransient
  12. {
  13. internal async Task<object[]> ListAsync(long tenantId, long factoryId, long id)
  14. {
  15. using var store = MdpIngestDatabase.Open(db);
  16. var rows = await store.Ado.SqlQueryAsync<RelationalRun>(SyncRunSelect + "\n" + """
  17. WHERE tenant_id=@tenantId AND factory_id=@factoryId AND dataset_id=@id
  18. ORDER BY created_at_utc DESC LIMIT 30
  19. """, new { tenantId, factoryId, id });
  20. return rows.Select(MapRun).ToArray();
  21. }
  22. internal async Task<object> RunAsync(RelationalTrialProfile profile, Guid? prior, string mode, CancellationToken token,
  23. string? scheduledSignature = null)
  24. {
  25. if (!profile.SyncEnabled || (mode is "INCR" or "REPLAY" && !HasAppendLog(profile) && !HasTimeSource(profile)))
  26. throw new MdpIngestHttpException(409, "RELATIONAL_MODE_UNAVAILABLE");
  27. using var store = MdpIngestDatabase.Open(db);
  28. var dataset = await store.Queryable<MdpIngestDataset>()
  29. .Where(row => row.Id == profile.DatasetId && row.TenantId == profile.TenantId
  30. && row.FactoryId == profile.FactoryId && row.Enabled)
  31. .FirstAsync(token);
  32. var source = await store.Queryable<MdpSource>()
  33. .Where(row => row.Id == profile.SourceId && row.TenantId == profile.TenantId && row.Status == 1)
  34. .FirstAsync(token);
  35. if (source is null || dataset?.ActiveSchemaVersion is null
  36. || await store.Ado.SqlQuerySingleAsync<string>(
  37. "SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@DatasetId", new { profile.DatasetId }) != "ACTIVE")
  38. throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
  39. var (_, binding, configuration) = await CreateRelationalTrial(store, profile, dataset, source);
  40. var signature = Signature(profile, binding);
  41. var runId = (prior ?? Guid.NewGuid()).ToString("D");
  42. var run = prior.HasValue
  43. ? await FindScopedRun(store, runId, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.Id)
  44. ?? throw new MdpIngestHttpException(404, "RELATIONAL_RUN_NOT_FOUND")
  45. : null;
  46. if (run is not null && (run.ScopeVersion != signature || run.SourceId != profile.SourceId
  47. || run.SchemaVersion != binding.SourceSchemaVersion))
  48. {
  49. if (run.Phase is "RECEIVING" or "RECONCILING")
  50. await RecordRecovery(store, runId, ChangedPlanReason);
  51. throw new MdpIngestHttpException(409, "RELATIONAL_PLAN_CHANGED");
  52. }
  53. if (scheduledSignature is not null && signature != scheduledSignature)
  54. throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
  55. var (address, key) = await LoadRelationalReceiver(store, profile, dataset, token);
  56. if (run is null)
  57. {
  58. var baseline = mode is "INCR" or "REPLAY" ? await LatestCompleted(store, profile, signature) : null;
  59. if (baseline?.RecoveryReason == HistoryExpiredReason)
  60. throw new MdpIngestHttpException(409, "RELATIONAL_REINITIALIZATION_REQUIRED");
  61. var report = await InspectProfile(profile, binding, token);
  62. var issue = report.Checks.FirstOrDefault(x => x.Severity == "block");
  63. if (issue is not null) throw new MdpIngestHttpException(409, issue.Code);
  64. try
  65. {
  66. await FreezeRelationalRun(store, profile, binding, signature, runId, mode, token);
  67. }
  68. catch (ConnectorContractException error) when (error.Code == ConnectorError.HistoryExpired && baseline is not null)
  69. {
  70. await RecordRecovery(store, baseline.RunId, HistoryExpiredReason);
  71. throw new MdpIngestHttpException(409, "RELATIONAL_REINITIALIZATION_REQUIRED");
  72. }
  73. run = await FindRun(store, runId, binding, profile.Id)
  74. ?? throw new MdpIngestHttpException(404, "RELATIONAL_RUN_NOT_FOUND");
  75. }
  76. await ReceiveFrozenPages(store, run, binding,
  77. (frozen, cancellation) => SubmitRelationalTrial(address, binding.Identity.DatasetKey, frozen, key, cancellation), token);
  78. var received = await FindRun(store, runId, binding, profile.Id);
  79. await ReconcileRelationalRun(store, received!, binding, configuration, token);
  80. return MapRun((await FindRun(store, runId, binding, profile.Id))!);
  81. }
  82. internal async Task<bool> RunScheduledAsync(long tenantId, string taskCode, CancellationToken token)
  83. {
  84. using var store = MdpIngestDatabase.Open(db);
  85. var assigned = await store.Ado.SqlQuerySingleAsync<RelationalScheduleBinding?>("""
  86. SELECT factory_id AS FactoryId,dataset_id AS DatasetId,source_id AS SourceId,profile_id AS ProfileId,
  87. scope_version AS ScopeVersion,task_code AS TaskCode
  88. FROM mdp_connector_relational_schedule WHERE tenant_id=@tenantId AND task_code=@taskCode
  89. """, new { tenantId, taskCode });
  90. var profiles = (await ReadProfiles(settings["MDP_RELATIONAL_TRIALS_FILE"], token))
  91. .Where(p => p.SyncEnabled && p.TenantId == tenantId);
  92. var profile = assigned is null
  93. ? profiles.SingleOrDefault(p => string.Equals(p.ScheduleTaskCode, taskCode, StringComparison.Ordinal))
  94. : profiles.SingleOrDefault(p => p.Id == assigned.ProfileId && p.FactoryId == assigned.FactoryId
  95. && p.DatasetId == assigned.DatasetId && p.SourceId == assigned.SourceId);
  96. if (profile is null)
  97. {
  98. if (assigned is not null) throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
  99. return false;
  100. }
  101. if (assigned is null && await BoundSchedule(store, profile) is not null) return false;
  102. if (assigned is not null)
  103. {
  104. var sourceCode = await store.Queryable<MdpSource>().Where(s => s.Id == profile.SourceId
  105. && s.TenantId == tenantId && s.Status == 1).Select(s => s.SourceCode).FirstAsync(token);
  106. if (assigned.ScopeVersion is null || sourceCode is null || !(await EligibleTasksAsync(store, profile, sourceCode, token))
  107. .Any(task => string.Equals(task.TaskCode, taskCode, StringComparison.Ordinal)))
  108. throw new MdpIngestHttpException(409, "RELATIONAL_SCHEDULE_REBIND_REQUIRED");
  109. }
  110. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  111. deadline.CancelAfter(TimeSpan.FromSeconds(75));
  112. var latest = await store.Ado.SqlQuerySingleAsync<RelationalRun>(SyncRunSelect + "\n" + """
  113. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
  114. AND source_id=@SourceId AND profile_id=@Id AND (active_slot=1 OR phase IN ('SUCCEEDED','REVIEW'))
  115. AND (@version IS NULL OR scope_version=@version OR active_slot=1)
  116. AND (active_slot=1 OR EXISTS (
  117. SELECT 1 FROM mdp_connector_relational_sync_window w
  118. WHERE w.run_id=mdp_connector_relational_sync_run.run_id AND w.mode IN ('FULL','INCR')
  119. ))
  120. ORDER BY (active_slot=1) DESC,created_at_utc DESC LIMIT 1
  121. """, new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, version = assigned?.ScopeVersion });
  122. if (latest?.Phase == "REVIEW")
  123. throw new MdpIngestHttpException(409, "RELATIONAL_RECONCILIATION_REQUIRED");
  124. Guid? running = latest?.Phase is "RECEIVING" or "RECONCILING" ? Guid.Parse(latest.RunId) : null;
  125. var baselineReady = latest?.Phase == "SUCCEEDED" &&
  126. (latest.ProvenPages == latest.PageCount || (assigned is null && latest.Mode == "INCR"));
  127. var mode = baselineReady && (HasAppendLog(profile) || HasTimeSource(profile)) ? "INCR" : "FULL";
  128. await RunAsync(profile, running, mode, deadline.Token, assigned?.ScopeVersion);
  129. return true;
  130. }
  131. private static string Signature(RelationalTrialProfile profile, ConnectorBinding binding) =>
  132. Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
  133. {
  134. profile.Id, profile.Driver, profile.Database, profile.Schema, profile.Table, profile.PositionColumn,
  135. profile.Columns, profile.OdbcFamily, profile.Preflight, profile.SyncPageSize, profile.LookbackPositions,
  136. profile.FieldRules, profile.ConnectionString, binding.ConfigVersion,
  137. }, RelationalTrialJson)));
  138. private static async Task FreezeRelationalRun(SqlSugarClient store, RelationalTrialProfile profile, ConnectorBinding binding,
  139. string signature, string runId, string mode, CancellationToken token)
  140. {
  141. var identity = binding.Identity;
  142. var tx = await store.Ado.UseTranAsync(async () =>
  143. {
  144. await store.Ado.ExecuteCommandAsync("""
  145. INSERT INTO mdp_connector_relational_sync_run
  146. (run_id,tenant_id,factory_id,dataset_id,source_id,profile_id,scope_version,schema_version,phase,
  147. active_slot,created_at_utc,updated_at_utc)
  148. VALUES (@runId,@TenantId,@FactoryId,@DatasetId,@SourceId,@profileId,@signature,
  149. @SourceSchemaVersion,'FROZEN',1,UTC_TIMESTAMP(6),UTC_TIMESTAMP(6))
  150. """, new { runId, identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId,
  151. profileId = profile.Id, signature, binding.SourceSchemaVersion });
  152. RelationalLogWindow? window = null;
  153. if (HasAppendLog(profile))
  154. {
  155. var previous = await store.Ado.SqlQuerySingleAsync<long?>("""
  156. SELECT MAX(w.to_position) FROM mdp_connector_relational_sync_window w
  157. JOIN mdp_connector_relational_sync_run r ON r.run_id=w.run_id
  158. WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId
  159. AND r.source_id=@SourceId AND r.profile_id=@profileId AND r.scope_version=@signature
  160. AND r.phase='SUCCEEDED' AND w.mode IN ('FULL','INCR')
  161. AND (w.mode='INCR' OR r.page_count=(SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
  162. WHERE x.run_id=r.run_id AND x.issue_code IS NULL))
  163. """, new { identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId, profileId = profile.Id, signature });
  164. if (mode != "FULL" && !previous.HasValue)
  165. throw new MdpIngestHttpException(409, "RELATIONAL_FULL_RECONCILIATION_REQUIRED");
  166. window = new(mode == "FULL" ? null : previous, mode == "REPLAY" ? profile.LookbackPositions : 0, mode == "REPLAY");
  167. }
  168. RelationalTimeCapture? time = null;
  169. if (HasTimeSource(profile) && profile.Preflight is { } config)
  170. {
  171. var previous = await store.Ado.SqlQuerySingleAsync<DateTime?>("""
  172. SELECT MAX(w.to_utc) FROM mdp_connector_relational_time_window w
  173. JOIN mdp_connector_relational_sync_run r ON r.run_id=w.run_id
  174. JOIN mdp_connector_relational_sync_window m ON m.run_id=w.run_id
  175. WHERE r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.dataset_id=@DatasetId
  176. AND r.source_id=@SourceId AND r.profile_id=@profileId AND r.scope_version=@signature
  177. AND r.phase='SUCCEEDED' AND m.mode IN ('FULL','INCR')
  178. AND (m.mode='INCR' OR r.page_count=(SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
  179. WHERE x.run_id=r.run_id AND x.issue_code IS NULL))
  180. """, new { identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId, profileId = profile.Id, signature });
  181. if (mode != "FULL" && !previous.HasValue)
  182. throw new MdpIngestHttpException(409, "RELATIONAL_FULL_RECONCILIATION_REQUIRED");
  183. time = new(config.IncrementalField!,
  184. mode == "FULL" ? null : new DateTimeOffset(DateTime.SpecifyKind(previous!.Value, DateTimeKind.Utc)),
  185. config.MaxCommitDelaySeconds!.Value, config.LookbackSeconds!.Value, config.RetentionSeconds!.Value, mode == "REPLAY",
  186. config.DeletePolicy == "snapshot-difference" ? config.SnapshotFenceTable : null,
  187. config.DeletePolicy == "snapshot-difference" ? config.SnapshotFenceColumn : null);
  188. }
  189. var execution = TrialExecution(profile, binding);
  190. await using var source = await TrialDriver(profile, execution).OpenReadOnlyAsync(execution, profile.Id, token);
  191. if (source is not IRelationalSnapshotSource snapshot)
  192. throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  193. var snapshotKeys = time is { Completed: null, FenceTable: not null } ? await ReadSnapshotKeyNames(store, binding) : null;
  194. async Task FreezePage(ConnectorBatchCandidate page, int ordinal, CancellationToken cancellation)
  195. {
  196. cancellation.ThrowIfCancellationRequested();
  197. if (snapshotKeys is not null)
  198. await SaveSnapshotKeys(store, runId, page, snapshotKeys);
  199. var id = "relational-sync-" + runId + "-" + ordinal.ToString(CultureInfo.InvariantCulture);
  200. var frozen = ConnectorFrozenBatch.Capture(binding, page with { SenderBatchId = id, IdempotencyKey = id });
  201. await store.Ado.ExecuteCommandAsync("""
  202. INSERT INTO mdp_connector_relational_sync_page
  203. (run_id,ordinal,idem_key,payload_sha256,payload,position_key,next_position)
  204. VALUES (@runId,@ordinal,@id,@sha,@payload,@position,@next)
  205. """, new { runId, ordinal, id, sha = frozen.Pending.Id.PayloadSha256, payload = frozen.Payload.ToArray(),
  206. position = frozen.Pending.SourcePosition, next = frozen.Pending.NextCheckpoint });
  207. }
  208. RelationalSnapshotSummary summary;
  209. if (time is not null)
  210. {
  211. if (source is not IRelationalTimeSnapshotSource timeSource)
  212. throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  213. var capture = await timeSource.CaptureTimeAsync(profile.SyncPageSize, FreezePage, time, token);
  214. summary = new(capture.RowCount, capture.PageCount);
  215. if (snapshotKeys is not null)
  216. {
  217. var fence = capture.Fence ?? throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  218. var removed = await FreezeSnapshotDeletes(store, binding, runId, signature, snapshotKeys, fence,
  219. summary.PageCount, token);
  220. summary = summary with { RowCount = summary.RowCount + removed.Rows, PageCount = summary.PageCount + removed.Pages };
  221. }
  222. await store.Ado.ExecuteCommandAsync("""
  223. INSERT INTO mdp_connector_relational_time_window (run_id,from_utc,to_utc)
  224. VALUES (@runId,@fromUtc,@toUtc)
  225. """, new { runId, fromUtc = capture.From?.UtcDateTime, toUtc = capture.To.UtcDateTime });
  226. }
  227. else
  228. summary = await snapshot.CaptureAsync(profile.SyncPageSize, FreezePage, token, window);
  229. token.ThrowIfCancellationRequested();
  230. await store.Ado.ExecuteCommandAsync("""
  231. INSERT INTO mdp_connector_relational_sync_window (run_id,mode,from_position,to_position)
  232. VALUES (@runId,@mode,@fromPosition,@toPosition)
  233. """, new { runId, mode, fromPosition = window?.Start, toPosition = summary.UpperPosition ?? 0 });
  234. if (profile.Preflight?.SourceGeneration is > 0 and var sourceGeneration)
  235. await store.Ado.ExecuteCommandAsync("""
  236. INSERT INTO mdp_connector_relational_change_run (run_id,source_generation)
  237. VALUES (@runId,@sourceGeneration)
  238. """, new { runId, sourceGeneration });
  239. await store.Ado.ExecuteCommandAsync("""
  240. UPDATE mdp_connector_relational_sync_run
  241. SET row_count=@RowCount,page_count=@PageCount,phase='RECEIVING',updated_at_utc=UTC_TIMESTAMP(6)
  242. WHERE run_id=@runId
  243. """, new { runId, summary.RowCount, summary.PageCount });
  244. });
  245. if (!tx.IsSuccess) throw tx.ErrorException!;
  246. }
  247. private static async Task ReceiveFrozenPages(SqlSugarClient store, RelationalRun run, ConnectorBinding binding,
  248. Func<ConnectorFrozenBatch, CancellationToken, Task<MdpIngestReceipt>>? submit, CancellationToken token)
  249. {
  250. if (run.Phase != "RECEIVING") return;
  251. var lease = Guid.NewGuid().ToString("D");
  252. if (await store.Ado.ExecuteCommandAsync("""
  253. UPDATE mdp_connector_relational_sync_run SET lease_token=@lease,lease_until_utc=UTC_TIMESTAMP(6)+INTERVAL 100 SECOND
  254. WHERE run_id=@RunId AND phase='RECEIVING'
  255. AND (lease_until_utc IS NULL OR lease_until_utc<UTC_TIMESTAMP(6))
  256. """, new { run.RunId, lease }) != 1)
  257. throw new MdpIngestHttpException(409, "RELATIONAL_RUN_BUSY");
  258. try
  259. {
  260. var pages = await store.Ado.SqlQueryAsync<RelationalPage>("""
  261. SELECT ordinal,idem_key AS IdemKey,payload_sha256 AS PayloadSha256,payload,
  262. position_key AS Position,next_position AS NextPosition
  263. FROM mdp_connector_relational_sync_page WHERE run_id=@RunId AND raw_id IS NULL
  264. ORDER BY ordinal LIMIT 8
  265. """, new { run.RunId });
  266. foreach (var page in pages)
  267. {
  268. token.ThrowIfCancellationRequested();
  269. var identity = new ConnectorBatchIdentity(binding, page.IdemKey, page.IdemKey, page.PayloadSha256);
  270. var pending = new ConnectorPendingBatch(identity, page.Position, page.NextPosition);
  271. var frozen = ConnectorFrozenBatch.Restore(pending, page.Payload);
  272. var raw = await FindFrozenReceipt(store, run, page);
  273. if (raw == Guid.Empty)
  274. {
  275. if (submit is null) break;
  276. if (run.CreatedAtUtc <= DateTime.UtcNow.AddDays(-6))
  277. throw new MdpIngestHttpException(409, "RELATIONAL_RECEIPT_RECONCILIATION_REQUIRED");
  278. var receipt = await submit(frozen, token);
  279. if (receipt.BatchId == Guid.Empty || receipt.SchemaVersion != binding.SourceSchemaVersion
  280. || receipt.ReceiveStatus != "accepted" || receipt.AcceptedRecordCount <= 0)
  281. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  282. raw = receipt.BatchId;
  283. }
  284. var decision = ConnectorResume.Decide(binding, pending, new(identity, ConnectorConfirmation.CloudDurable, raw), frozen);
  285. if (decision.Action != ConnectorResumeAction.Advance)
  286. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  287. var progress = await store.Ado.UseTranAsync(async () =>
  288. {
  289. var args = new { run.RunId, page.Ordinal, previous = page.Ordinal - 1, lease,
  290. raw = raw.ToString("D"), next = decision.NextCheckpoint };
  291. if (await store.Ado.ExecuteCommandAsync("""
  292. UPDATE mdp_connector_relational_sync_run
  293. SET committed_page=@Ordinal,committed_position=@next,committed_raw_id=@raw,
  294. updated_at_utc=UTC_TIMESTAMP(6)
  295. WHERE run_id=@RunId AND lease_token=@lease AND lease_until_utc>UTC_TIMESTAMP(6)
  296. AND committed_page=@previous
  297. """, args) != 1)
  298. throw new MdpIngestHttpException(409, "RELATIONAL_RUN_LEASE_LOST");
  299. if (await store.Ado.ExecuteCommandAsync("""
  300. UPDATE mdp_connector_relational_sync_page SET raw_id=@raw
  301. WHERE run_id=@RunId AND ordinal=@Ordinal AND raw_id IS NULL
  302. """, args) != 1)
  303. throw new MdpIngestHttpException(409, "RELATIONAL_PAGE_STATE_CONFLICT");
  304. });
  305. if (!progress.IsSuccess) throw progress.ErrorException!;
  306. }
  307. await store.Ado.ExecuteCommandAsync("""
  308. UPDATE mdp_connector_relational_sync_run SET phase='RECONCILING',updated_at_utc=UTC_TIMESTAMP(6)
  309. WHERE run_id=@RunId AND lease_token=@lease AND lease_until_utc>UTC_TIMESTAMP(6) AND page_count=committed_page
  310. """, new { run.RunId, lease });
  311. }
  312. finally
  313. {
  314. await store.Ado.ExecuteCommandAsync("""
  315. UPDATE mdp_connector_relational_sync_run SET lease_token=NULL,lease_until_utc=NULL
  316. WHERE run_id=@RunId AND lease_token=@lease
  317. """, new { run.RunId, lease });
  318. }
  319. }
  320. private static async Task<Guid> FindFrozenReceipt(SqlSugarClient store, RelationalRun run, RelationalPage page)
  321. {
  322. var found = await store.Ado.SqlQuerySingleAsync<PersistedRelationalReceipt>("""
  323. SELECT batch_id AS BatchId,payload_sha256 AS PayloadSha256,source_schema_version AS SchemaVersion
  324. FROM mdp_ingest_raw_batch
  325. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
  326. AND source_id=@SourceId AND idempotency_key=@IdemKey
  327. """, new { run.TenantId, run.FactoryId, run.DatasetId, run.SourceId, page.IdemKey });
  328. if (found is null) return Guid.Empty;
  329. if (found.PayloadSha256 != page.PayloadSha256 || found.SchemaVersion != run.SchemaVersion
  330. || !Guid.TryParse(found.BatchId, out var id) || id == Guid.Empty)
  331. throw new MdpIngestHttpException(409, "RELATIONAL_RECEIPT_MISMATCH");
  332. return id;
  333. }
  334. private static Task<RelationalRun?> FindRun(SqlSugarClient store, string runId, ConnectorBinding binding, string profileId)
  335. {
  336. var scope = binding.Identity;
  337. return store.Ado.SqlQuerySingleAsync<RelationalRun>(SyncRunSelect + "\n" + """
  338. WHERE run_id=@runId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
  339. AND source_id=@SourceId AND profile_id=@profileId
  340. """, new { runId, scope.TenantId, scope.FactoryId, scope.DatasetId, scope.SourceId, profileId });
  341. }
  342. private static object MapRun(RelationalRun run) => new
  343. {
  344. run.RunId, run.ProfileId, run.Phase, run.RowCount, run.PageCount, run.CommittedPage,
  345. run.CommittedPosition, run.CommittedRawId, run.CreatedAtUtc, run.Mode, run.WindowStart, run.WindowEnd,
  346. run.ProvenPages, run.CheckedRows, run.ProofIssue, run.ProofKey, run.RecoveryReason,
  347. windowFromUtc = run.WindowFromUtc.HasValue ? DateTime.SpecifyKind(run.WindowFromUtc.Value, DateTimeKind.Utc) : (DateTime?)null,
  348. windowToUtc = run.WindowToUtc.HasValue ? DateTime.SpecifyKind(run.WindowToUtc.Value, DateTimeKind.Utc) : (DateTime?)null,
  349. };
  350. private const string SyncRunSelect = """
  351. SELECT run_id AS RunId,tenant_id AS TenantId,factory_id AS FactoryId,dataset_id AS DatasetId,source_id AS SourceId,
  352. profile_id AS ProfileId,scope_version AS ScopeVersion,schema_version AS SchemaVersion,phase,
  353. row_count AS RowCount,page_count AS PageCount,committed_page AS CommittedPage,
  354. committed_position AS CommittedPosition,committed_raw_id AS CommittedRawId,created_at_utc AS CreatedAtUtc,
  355. (SELECT COUNT(*) FROM mdp_connector_relational_sync_proof x
  356. WHERE x.run_id=mdp_connector_relational_sync_run.run_id AND x.issue_code IS NULL) AS ProvenPages,
  357. (SELECT COALESCE(SUM(x.checked_rows),0) FROM mdp_connector_relational_sync_proof x
  358. WHERE x.run_id=mdp_connector_relational_sync_run.run_id) AS CheckedRows,
  359. (SELECT x.issue_code FROM mdp_connector_relational_sync_proof x
  360. 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,
  361. (SELECT x.issue_key FROM mdp_connector_relational_sync_proof x
  362. 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,
  363. (SELECT h.reason FROM mdp_connector_relational_sync_recovery h
  364. WHERE h.run_id=mdp_connector_relational_sync_run.run_id AND h.resolved_at_utc IS NULL
  365. ORDER BY h.detected_at_utc DESC,h.reason LIMIT 1) AS RecoveryReason,
  366. (SELECT w.mode FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS Mode,
  367. (SELECT w.from_position FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowStart,
  368. (SELECT w.to_position FROM mdp_connector_relational_sync_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowEnd,
  369. (SELECT w.from_utc FROM mdp_connector_relational_time_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowFromUtc,
  370. (SELECT w.to_utc FROM mdp_connector_relational_time_window w WHERE w.run_id=mdp_connector_relational_sync_run.run_id) AS WindowToUtc
  371. FROM mdp_connector_relational_sync_run
  372. """;
  373. private sealed class RelationalRun
  374. {
  375. public string RunId { get; set; } = "";
  376. public long TenantId { get; set; }
  377. public long FactoryId { get; set; }
  378. public long DatasetId { get; set; }
  379. public long SourceId { get; set; }
  380. public string ProfileId { get; set; } = "";
  381. public string ScopeVersion { get; set; } = "";
  382. public string SchemaVersion { get; set; } = "";
  383. public string Phase { get; set; } = "";
  384. public long RowCount { get; set; }
  385. public int PageCount { get; set; }
  386. public int CommittedPage { get; set; }
  387. public int ProvenPages { get; set; }
  388. public long CheckedRows { get; set; }
  389. public string? ProofIssue { get; set; }
  390. public string? ProofKey { get; set; }
  391. public string? RecoveryReason { get; set; }
  392. public string? CommittedPosition { get; set; }
  393. public string? CommittedRawId { get; set; }
  394. public DateTime CreatedAtUtc { get; set; }
  395. public string? Mode { get; set; }
  396. public long? WindowStart { get; set; }
  397. public long? WindowEnd { get; set; }
  398. public DateTime? WindowFromUtc { get; set; }
  399. public DateTime? WindowToUtc { get; set; }
  400. }
  401. private sealed class RelationalPage
  402. {
  403. public int Ordinal { get; set; }
  404. public string IdemKey { get; set; } = "";
  405. public string PayloadSha256 { get; set; } = "";
  406. public byte[] Payload { get; set; } = [];
  407. public string Position { get; set; } = "";
  408. public string NextPosition { get; set; } = "";
  409. }
  410. private sealed class PersistedRelationalReceipt
  411. {
  412. public string BatchId { get; set; } = "";
  413. public string PayloadSha256 { get; set; } = "";
  414. public string SchemaVersion { get; set; } = "";
  415. }
  416. }