| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed partial class MdpApiPullService
- {
- internal async Task<MdpApiPullRawExport> ExportCaptureAsync(long tenant, long factory, long dataset, string runId,
- int ordinal, int attempt, long actor, CancellationToken token)
- {
- Require(ordinal > 0 && attempt > 0 && actor > 0, "PULL_RECOVERY_INVALID");
- using var db = MdpIngestDatabase.Open(host);
- return await Tx(db, async () =>
- {
- var capture = await db.Ado.SqlQuerySingleAsync<ExportRow>("""
- 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
- FROM mdp_connector_api_pull_capture c JOIN mdp_connector_api_pull_run r ON r.run_id=c.run_id
- JOIN mdp_ingest_raw_batch b ON b.batch_id=c.batch_id AND b.tenant_id=r.tenant_id
- AND b.factory_id=r.factory_id AND b.dataset_id=r.dataset_id AND b.source_id=r.source_id
- WHERE r.tenant_id=@tenant AND r.factory_id=@factory AND r.dataset_id=@dataset
- AND r.run_id=@runId AND c.ordinal=@ordinal AND c.attempt=@attempt
- """, new { tenant, factory, dataset, runId, ordinal, attempt })
- ?? throw new MdpApiPullException("PULL_CAPTURE_NOT_FOUND");
- Require(!capture.ExpiredAt.HasValue, "RAW_PAYLOAD_EXPIRED");
- Require(capture.Digest == Hash(capture.Payload), "PULL_FROZEN_PAGE_INVALID");
- await db.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_ingest_release_log (dataset_id,release_id,action,actor,detail,created_at)
- VALUES (@dataset,@ReleaseId,'API_PULL_RAW_EXPORT',@actor,@detail,UTC_TIMESTAMP(6))
- """, new { dataset, capture.ReleaseId, actor, detail = $"{runId}/{ordinal}/{attempt}/{capture.BatchId}" });
- token.ThrowIfCancellationRequested();
- return new MdpApiPullRawExport(capture.BatchId, capture.Payload);
- });
- }
- private sealed class ExportRow
- {
- public DateTime? ExpiredAt { get; set; }
- public string BatchId { get; set; } = "";
- public byte[] Payload { get; set; } = [];
- public string Digest { get; set; } = "";
- public long ReleaseId { get; set; }
- }
- private static Task<FrozenPage?> ReadFrozenPageAsync(ISqlSugarClient db, Profile profile, string runId, int ordinal) =>
- db.Ado.SqlQuerySingleAsync<FrozenPage>("""
- SELECT COALESCE(b.payload,p.response_body) AS Body,p.response_sha256 AS Digest,p.position_sha256 AS PositionDigest,
- p.effective_url AS Effective,p.next_link AS NextLink,c.link_diagnostic AS LinkDiagnostic,c.attempt AS Attempt,
- c.batch_id AS CaptureId,b.received_at AS ReceivedAt,c.state AS CaptureState,p.frozen_at AS FrozenAt
- FROM mdp_connector_api_pull_page p
- LEFT JOIN mdp_connector_api_pull_capture c ON c.run_id=p.run_id AND c.ordinal=p.ordinal
- 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)
- LEFT JOIN mdp_ingest_raw_batch b ON b.batch_id=c.batch_id AND b.tenant_id=@TenantId AND b.factory_id=@FactoryId
- AND b.dataset_id=@DatasetId AND b.source_id=@SourceId AND b.payload_sha256=p.response_sha256
- AND c.profile_id=@Id AND c.release_id=@ReleaseId
- WHERE p.run_id=@runId AND p.ordinal=@ordinal
- """, new { runId, ordinal, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, profile.ReleaseId });
- private static void VerifyFrozenPage(FrozenPage page, string positionHash) =>
- Require(page.Body is not null && page.PositionDigest == positionHash && page.Digest == Hash(page.Body), "PULL_FROZEN_PAGE_INVALID");
- private static async Task LockPageLeaseAsync(ISqlSugarClient db, string runId, string lease, int ordinal)
- {
- var locked = await db.Ado.GetIntAsync("""
- SELECT page_no+1 FROM mdp_connector_api_pull_run
- WHERE run_id=@runId AND lease_token=@lease AND lease_until>UTC_TIMESTAMP(6) FOR UPDATE
- """, new { runId, lease });
- Require(locked == ordinal, "PULL_LEASE_LOST");
- }
- private static async Task StoreCaptureAsync(ISqlSugarClient db, Profile profile, Published bound, string runId, int ordinal,
- FrozenPage page, bool existingPage, CancellationToken token)
- {
- var preparer = await PagePreparerAsync(db, profile, bound);
- var raw = preparer.CaptureApiPage(PageIdentity(profile, bound), bound.Version, page.Body!, MdpIngestProtocol.Limits, PurchaseApiWindow);
- var captureId = raw.BatchId.ToString("D");
- // The binary prefix is reserved for unaccepted captures; client receipt keys are printable ASCII.
- var captureKey = Encoding.ASCII.GetBytes("\0api-pull-" + captureId);
- var capturedAt = page.FrozenAt is { } frozen ? DateTime.SpecifyKind(frozen, DateTimeKind.Utc) : raw.ReceivedAt.UtcDateTime;
- var receivedAt = new DateTimeOffset(capturedAt.Ticks / 10 * 10, TimeSpan.Zero);
- await MdpIngestReceiveService.PersistRawWithJournalAsync(db, raw, [], page.Body!, captureKey, receivedAt, token);
- var args = new { runId, ordinal, Attempt = checked(page.Attempt + 1), captureId, profile.Id, profile.ReleaseId,
- page.PositionDigest, page.Digest, page.Effective, page.NextLink, page.LinkDiagnostic, FrozenAt = receivedAt.UtcDateTime };
- await db.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_api_pull_capture
- (run_id,ordinal,attempt,batch_id,profile_id,release_id,effective_url,next_link,link_diagnostic,state)
- VALUES (@runId,@ordinal,@Attempt,@captureId,@Id,@ReleaseId,@Effective,@NextLink,@LinkDiagnostic,'CAPTURED')
- """, args);
- var changed = existingPage
- ? await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_page SET response_body=NULL,response_sha256=@Digest,effective_url=@Effective,
- next_link=@NextLink,frozen_at=@FrozenAt
- WHERE run_id=@runId AND ordinal=@ordinal AND position_sha256=@PositionDigest AND raw_batch_id IS NULL
- AND row_count IS NULL
- """, args)
- : await db.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_api_pull_page
- (run_id,ordinal,position_sha256,response_sha256,effective_url,next_link,frozen_at)
- VALUES (@runId,@ordinal,@PositionDigest,@Digest,@Effective,@NextLink,@FrozenAt)
- """, args);
- Require(changed == 1, "PULL_CAPTURE_CHANGED");
- page.CaptureId = captureId;
- page.Attempt = args.Attempt;
- page.ReceivedAt = receivedAt.UtcDateTime;
- page.CaptureState = "CAPTURED";
- }
- private static async Task<(PreparedIngestBatch Prepared, MdpApiPullPosition? Next)> ParsePageAsync(ISqlSugarClient db,
- Profile profile, Published bound, Run run, MdpApiPullPlan plan, MdpApiPullPosition position, FrozenPage page)
- {
- if (page.LinkDiagnostic is { } diagnostic)
- throw new MdpApiPullException(diagnostic);
- var prepared = await PrepareAsync(db, profile, bound, plan, page.Body!);
- using var json = JsonDocument.Parse(page.Body!);
- var next = plan.Next(position, json.RootElement, prepared.Events.Count, new Uri(page.Effective), page.NextLink, run.RowCount);
- if (next is not null)
- {
- var nextHash = Hash(JsonSerializer.SerializeToUtf8Bytes(next, Wire));
- var known = await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_connector_api_pull_page WHERE run_id=@RunId AND position_sha256=@nextHash
- """, new { run.RunId, nextHash });
- Require(known == 0, "PULL_POSITION_STALLED");
- }
- return (prepared, next);
- }
- private static async Task FinishCaptureAsync(ISqlSugarClient db, FrozenPage page, PreparedIngestBatch prepared,
- string runId, int ordinal, long factory, CancellationToken token)
- {
- Require(Guid.TryParseExact(page.CaptureId, "D", out var id) && page.ReceivedAt.HasValue, "PULL_CAPTURE_CHANGED");
- var changed = await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_capture SET state=@state,changed_at=UTC_TIMESTAMP(6)
- WHERE run_id=@runId AND ordinal=@ordinal AND batch_id=@CaptureId AND state IN ('CAPTURED','REJECTED')
- """, new { runId, ordinal, page.CaptureId, state = prepared.Events.Count == 0 ? "EMPTY" : "ACCEPTED" });
- Require(changed == 1, "PULL_CAPTURE_CHANGED");
- if (prepared.Events.Count == 0)
- {
- await MdpIngestBatchJournal.AppendAsync(db, id, prepared.Batch.Identity, IngestBatchJournal.RawEmpty, 0);
- return;
- }
- var batch = prepared.Batch with { BatchId = id, ReceivedAt = new(DateTime.SpecifyKind(page.ReceivedAt!.Value, DateTimeKind.Utc)) };
- var events = prepared.Events.Select(row => row with { BatchId = id }).ToArray();
- var key = Encoding.ASCII.GetBytes($"\0api-pull-page-{runId}-{ordinal}");
- await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, new(batch, events), key, factory, token, useCapturedRaw: true);
- }
- }
- internal sealed record MdpApiPullRawExport(string BatchId, byte[] Payload);
|