MdpApiPullService.Capture.cs 9.4 KB

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