MdpRelationalSyncService.cs 28 KB

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