MdpApiPullService.Capture.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using System.Text;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. public sealed partial class MdpApiPullService
  6. {
  7. internal async Task<MdpApiPullRawExport> ExportCaptureAsync(long tenant, long factory, long dataset, string runId,
  8. int ordinal, int attempt, long actor, CancellationToken token)
  9. {
  10. Require(ordinal > 0 && attempt > 0 && actor > 0, "PULL_RECOVERY_INVALID");
  11. using var db = MdpIngestDatabase.Open(host);
  12. return await Tx(db, async () =>
  13. {
  14. var capture = await db.Ado.SqlQuerySingleAsync<ExportRow>("""
  15. SELECT b.batch_id AS BatchId,b.payload AS Payload,b.payload_sha256 AS Digest,c.release_id AS ReleaseId
  16. FROM mdp_connector_api_pull_capture c JOIN mdp_connector_api_pull_run r ON r.run_id=c.run_id
  17. JOIN mdp_ingest_raw_batch b ON b.batch_id=c.batch_id AND b.tenant_id=r.tenant_id
  18. AND b.factory_id=r.factory_id AND b.dataset_id=r.dataset_id AND b.source_id=r.source_id
  19. WHERE r.tenant_id=@tenant AND r.factory_id=@factory AND r.dataset_id=@dataset
  20. AND r.run_id=@runId AND c.ordinal=@ordinal AND c.attempt=@attempt
  21. """, new { tenant, factory, dataset, runId, ordinal, attempt })
  22. ?? throw new MdpApiPullException("PULL_CAPTURE_NOT_FOUND");
  23. Require(capture.Digest == Hash(capture.Payload), "PULL_FROZEN_PAGE_INVALID");
  24. await db.Ado.ExecuteCommandAsync("""
  25. INSERT INTO mdp_ingest_release_log (dataset_id,release_id,action,actor,detail,created_at)
  26. VALUES (@dataset,@ReleaseId,'API_PULL_RAW_EXPORT',@actor,@detail,UTC_TIMESTAMP(6))
  27. """, new { dataset, capture.ReleaseId, actor, detail = $"{runId}/{ordinal}/{attempt}/{capture.BatchId}" });
  28. token.ThrowIfCancellationRequested();
  29. return new MdpApiPullRawExport(capture.BatchId, capture.Payload);
  30. });
  31. }
  32. private sealed class ExportRow
  33. {
  34. public string BatchId { get; set; } = "";
  35. public byte[] Payload { get; set; } = [];
  36. public string Digest { get; set; } = "";
  37. public long ReleaseId { get; set; }
  38. }
  39. private static Task<FrozenPage?> ReadFrozenPageAsync(ISqlSugarClient db, Profile profile, string runId, int ordinal) =>
  40. db.Ado.SqlQuerySingleAsync<FrozenPage>("""
  41. SELECT COALESCE(b.payload,p.response_body) AS Body,p.response_sha256 AS Digest,p.position_sha256 AS PositionDigest,
  42. p.effective_url AS Effective,p.next_link AS NextLink,c.link_diagnostic AS LinkDiagnostic,c.attempt AS Attempt,
  43. c.batch_id AS CaptureId,b.received_at AS ReceivedAt,c.state AS CaptureState,p.frozen_at AS FrozenAt
  44. FROM mdp_connector_api_pull_page p
  45. LEFT JOIN mdp_connector_api_pull_capture c ON c.run_id=p.run_id AND c.ordinal=p.ordinal
  46. AND c.attempt=(SELECT MAX(a.attempt) FROM mdp_connector_api_pull_capture a WHERE a.run_id=p.run_id AND a.ordinal=p.ordinal)
  47. LEFT JOIN mdp_ingest_raw_batch b ON b.batch_id=c.batch_id AND b.tenant_id=@TenantId AND b.factory_id=@FactoryId
  48. AND b.dataset_id=@DatasetId AND b.source_id=@SourceId AND b.payload_sha256=p.response_sha256
  49. AND c.profile_id=@Id AND c.release_id=@ReleaseId
  50. WHERE p.run_id=@runId AND p.ordinal=@ordinal
  51. """, new { runId, ordinal, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, profile.ReleaseId });
  52. private static void VerifyFrozenPage(FrozenPage page, string positionHash) =>
  53. Require(page.Body is not null && page.PositionDigest == positionHash && page.Digest == Hash(page.Body), "PULL_FROZEN_PAGE_INVALID");
  54. private static async Task LockPageLeaseAsync(ISqlSugarClient db, string runId, string lease, int ordinal)
  55. {
  56. var locked = await db.Ado.GetIntAsync("""
  57. SELECT page_no+1 FROM mdp_connector_api_pull_run
  58. WHERE run_id=@runId AND lease_token=@lease AND lease_until>UTC_TIMESTAMP(6) FOR UPDATE
  59. """, new { runId, lease });
  60. Require(locked == ordinal, "PULL_LEASE_LOST");
  61. }
  62. private static async Task StoreCaptureAsync(ISqlSugarClient db, Profile profile, Published bound, string runId, int ordinal,
  63. FrozenPage page, bool existingPage, CancellationToken token)
  64. {
  65. var preparer = await PagePreparerAsync(db, profile, bound);
  66. var raw = preparer.CaptureApiPage(PageIdentity(profile, bound), bound.Version, page.Body!, MdpIngestProtocol.Limits, PurchaseApiWindow);
  67. var captureId = raw.BatchId.ToString("D");
  68. // The binary prefix is reserved for unaccepted captures; client receipt keys are printable ASCII.
  69. var captureKey = Encoding.ASCII.GetBytes("\0api-pull-" + captureId);
  70. var capturedAt = page.FrozenAt is { } frozen ? DateTime.SpecifyKind(frozen, DateTimeKind.Utc) : raw.ReceivedAt.UtcDateTime;
  71. var receivedAt = new DateTimeOffset(capturedAt.Ticks / 10 * 10, TimeSpan.Zero);
  72. await MdpIngestReceiveService.PersistRawAsync(db, raw, [], page.Body!, captureKey, receivedAt, token);
  73. var args = new { runId, ordinal, Attempt = checked(page.Attempt + 1), captureId, profile.Id, profile.ReleaseId,
  74. page.PositionDigest, page.Digest, page.Effective, page.NextLink, page.LinkDiagnostic, FrozenAt = receivedAt.UtcDateTime };
  75. await db.Ado.ExecuteCommandAsync("""
  76. INSERT INTO mdp_connector_api_pull_capture
  77. (run_id,ordinal,attempt,batch_id,profile_id,release_id,effective_url,next_link,link_diagnostic,state)
  78. VALUES (@runId,@ordinal,@Attempt,@captureId,@Id,@ReleaseId,@Effective,@NextLink,@LinkDiagnostic,'CAPTURED')
  79. """, args);
  80. var changed = existingPage
  81. ? await db.Ado.ExecuteCommandAsync("""
  82. UPDATE mdp_connector_api_pull_page SET response_body=NULL,response_sha256=@Digest,effective_url=@Effective,
  83. next_link=@NextLink,frozen_at=@FrozenAt
  84. WHERE run_id=@runId AND ordinal=@ordinal AND position_sha256=@PositionDigest AND raw_batch_id IS NULL
  85. AND row_count IS NULL
  86. """, args)
  87. : await db.Ado.ExecuteCommandAsync("""
  88. INSERT INTO mdp_connector_api_pull_page
  89. (run_id,ordinal,position_sha256,response_sha256,effective_url,next_link,frozen_at)
  90. VALUES (@runId,@ordinal,@PositionDigest,@Digest,@Effective,@NextLink,@FrozenAt)
  91. """, args);
  92. Require(changed == 1, "PULL_CAPTURE_CHANGED");
  93. page.CaptureId = captureId;
  94. page.Attempt = args.Attempt;
  95. page.ReceivedAt = receivedAt.UtcDateTime;
  96. page.CaptureState = "CAPTURED";
  97. }
  98. private static async Task<(PreparedIngestBatch Prepared, MdpApiPullPosition? Next)> ParsePageAsync(ISqlSugarClient db,
  99. Profile profile, Published bound, Run run, MdpApiPullPlan plan, MdpApiPullPosition position, FrozenPage page)
  100. {
  101. if (page.LinkDiagnostic is { } diagnostic)
  102. throw new MdpApiPullException(diagnostic);
  103. var prepared = await PrepareAsync(db, profile, bound, plan, page.Body!);
  104. using var json = JsonDocument.Parse(page.Body!);
  105. var next = plan.Next(position, json.RootElement, prepared.Events.Count, new Uri(page.Effective), page.NextLink, run.RowCount);
  106. if (next is not null)
  107. {
  108. var nextHash = Hash(JsonSerializer.SerializeToUtf8Bytes(next, Wire));
  109. var known = await db.Ado.GetIntAsync("""
  110. SELECT COUNT(*) FROM mdp_connector_api_pull_page WHERE run_id=@RunId AND position_sha256=@nextHash
  111. """, new { run.RunId, nextHash });
  112. Require(known == 0, "PULL_POSITION_STALLED");
  113. }
  114. return (prepared, next);
  115. }
  116. private static async Task FinishCaptureAsync(ISqlSugarClient db, FrozenPage page, PreparedIngestBatch prepared,
  117. string runId, int ordinal, long factory, CancellationToken token)
  118. {
  119. Require(Guid.TryParseExact(page.CaptureId, "D", out var id) && page.ReceivedAt.HasValue, "PULL_CAPTURE_CHANGED");
  120. var changed = await db.Ado.ExecuteCommandAsync("""
  121. UPDATE mdp_connector_api_pull_capture SET state=@state,changed_at=UTC_TIMESTAMP(6)
  122. WHERE run_id=@runId AND ordinal=@ordinal AND batch_id=@CaptureId AND state IN ('CAPTURED','REJECTED')
  123. """, new { runId, ordinal, page.CaptureId, state = prepared.Events.Count == 0 ? "EMPTY" : "ACCEPTED" });
  124. Require(changed == 1, "PULL_CAPTURE_CHANGED");
  125. if (prepared.Events.Count == 0)
  126. return;
  127. var batch = prepared.Batch with { BatchId = id, ReceivedAt = new(DateTime.SpecifyKind(page.ReceivedAt!.Value, DateTimeKind.Utc)) };
  128. var events = prepared.Events.Select(row => row with { BatchId = id }).ToArray();
  129. var key = Encoding.ASCII.GetBytes($"\0api-pull-page-{runId}-{ordinal}");
  130. await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, new(batch, events), key, factory, token, useCapturedRaw: true);
  131. }
  132. }
  133. internal sealed record MdpApiPullRawExport(string BatchId, byte[] Payload);