| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed record MdpEdgePagePreviewInput(Guid BatchId, string ResponsePath);
- public sealed record MdpEdgePageApproval(Guid BatchId, string Digest, string Mode, string Reason, string? ResponsePath, string? PreviewToken);
- public sealed record MdpEdgePagePreview(Guid BatchId, string Digest, int Count, int Valid, int Isolated, bool HasNext, string Token);
- public sealed partial class MdpEdgeDeviceService
- {
- public async Task<MdpEdgePagePreview> PreviewPageAsync(long tenant, long factory, long dataset, Guid id, MdpEdgePagePreviewInput input)
- {
- RequireEnabled();
- using var db = MdpIngestDatabase.Open(host);
- var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, false);
- var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: false);
- return shadow.Preview;
- }
- public async Task RecoverPageAsync(long tenant, long factory, long dataset, Guid id, long actor,
- MdpEdgePageApproval input, CancellationToken token)
- {
- RequireEnabled();
- var reason = input.Reason?.Trim();
- Require(actor > 0 && reason is { Length: > 0 and <= 240 } && !reason.Any(char.IsControl)
- && (input.Mode == "reparse" || input.Mode == "refetch" && input.ResponsePath is null && input.PreviewToken is null),
- "EDGE_RECOVERY_INVALID");
- using var db = MdpIngestDatabase.Open(host);
- await Tx(db, async () =>
- {
- var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, true);
- Require(input.Digest == batch.Digest, "EDGE_CAPTURE_MISMATCH");
- if (input.Mode == "refetch")
- {
- var scope = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
- Require(scope.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
- await RequireWriterAsync(db, device, scope.SourceCode);
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_device SET task_phase='READY' WHERE device_id=@DeviceId
- """, new { device.DeviceId });
- }
- else
- {
- var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: true);
- Require(shadow.Preview.Token == input.PreviewToken, "EDGE_RECOVERY_PREVIEW_REQUIRED");
- var count = shadow.Result.Prepared.Events.Count;
- if (count > 0)
- {
- var originalTime = new DateTimeOffset(DateTime.SpecifyKind(page.ReceivedAt, DateTimeKind.Utc));
- var prepared = shadow.Result.Prepared with
- {
- Batch = shadow.Result.Prepared.Batch with { BatchId = batch.BatchId, ReceivedAt = originalTime },
- Events = shadow.Result.Prepared.Events.Select(row => row with { BatchId = batch.BatchId }).ToArray()
- };
- var key = Encoding.ASCII.GetBytes("\0edge-" + page.BatchId);
- await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, prepared, key, factory, token, useCapturedRaw: true);
- }
- var next = shadow.Result.ConfirmedPosition;
- var receipt = new EdgeReceipt(batch.BatchId, batch.Digest,
- count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted, batch.BatchId, next, SourcePosition: batch.Position);
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_receipt SET receipt_json=@receipt WHERE batch_id=@BatchId AND device_id=@DeviceId
- """, new { page.BatchId, device.DeviceId, receipt = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) });
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_device SET position_text=@next,task_phase=@phase,
- page_count=page_count+1,row_count=row_count+@count WHERE device_id=@DeviceId
- """, new { device.DeviceId, next, phase = next is null ? "COMPLETE" : "READY", count });
- }
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_edge_api_rejected_page SET settlement=@Mode,response_path=@ResponsePath,settled_at=UTC_TIMESTAMP(6)
- WHERE batch_id=@BatchId AND device_id=@DeviceId AND settled_at IS NULL
- """, new { page.BatchId, device.DeviceId, input.Mode, input.ResponsePath });
- await AuditAsync(db, dataset, actor, "EDGE_PAGE_RECOVERY", $"{page.BatchId} {input.Mode} {reason}");
- token.ThrowIfCancellationRequested();
- return true;
- });
- }
- private static async Task<(Device Device, EdgeTask Task, RejectedPage Page, EdgeBatch Batch)> RecoveryContextAsync(
- ISqlSugarClient db, long tenant, long factory, long dataset, Guid id, Guid raw, bool locked)
- {
- var deviceId = id.ToString("D");
- var batchId = raw.ToString("D");
- var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
- WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
- AND state='ACTIVE' AND task_phase='BLOCKED'
- """ + (locked ? " FOR UPDATE" : ""), new { deviceId, tenant, factory, dataset })
- ?? throw new EdgeContractException("EDGE_PAGE_NOT_BLOCKED");
- var task = ReadTask(device);
- Require(task.Mode == EdgeProtocol.ApiPull && task.Position is not null, "EDGE_PAGE_NOT_BLOCKED");
- var page = await db.Ado.SqlQuerySingleAsync<RejectedPage>("""
- SELECT p.batch_id AS BatchId,p.effective_url AS EffectiveUrl,p.next_link AS NextLink,p.link_diagnostic AS LinkDiagnostic,
- r.idem_key AS IdemKey,r.digest AS Digest,r.receipt_json AS ReceiptJson,b.payload AS Body,b.received_at AS ReceivedAt
- FROM mdp_edge_api_rejected_page p JOIN mdp_edge_receipt r ON r.batch_id=p.batch_id AND r.device_id=p.device_id
- JOIN mdp_ingest_raw_batch b ON b.batch_id=r.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 AND b.payload_sha256=r.digest
- WHERE p.batch_id=@batchId AND p.device_id=@deviceId AND p.generation=@Generation AND p.position_hash=@positionHash
- AND p.settled_at IS NULL AND r.tenant_id=@tenant AND r.factory_id=@factory AND r.dataset_id=@dataset
- AND r.source_id=@SourceId AND b.accepted_record_count=0
- """, new { batchId, deviceId, tenant, factory, dataset, device.Generation, device.SourceId, positionHash = HashText(task.Position!) })
- ?? throw new EdgeContractException("EDGE_CAPTURE_MISSING");
- var batch = EdgeBatch.Create(task.Stream, Encoding.ASCII.GetString(page.IdemKey), task.Position, null, page.Body) with
- {
- EffectiveUrl = page.EffectiveUrl, NextLink = page.NextLink, Diagnostic = page.LinkDiagnostic, ReceiverConfirmsNext = true
- };
- var receipt = JsonSerializer.Deserialize<EdgeReceipt>(page.ReceiptJson, EdgeProtocol.Json);
- Require(batch.BatchId == raw && batch.Digest == page.Digest && receipt?.Rejects(batch) == true, "EDGE_CAPTURE_MISMATCH");
- return (device, task, page, batch);
- }
- private static async Task<(MdpEdgePagePreview Preview, PageResult Result)> ReparseAsync(ISqlSugarClient db, Device device, EdgeTask task,
- RejectedPage page, EdgeBatch batch, string? path, bool lockDataset)
- {
- Require(path is { Length: <= 112 }, "EDGE_RECOVERY_INVALID");
- var plan = ParseApiPlan(task.ApiPlan) with { ResponsePath = path! };
- plan.Validate();
- var bound = await BoundAsync(db, task.TenantId, task.FactoryId, task.DatasetId, task.SourceId, lockDataset);
- Require(bound.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
- if (lockDataset) await RequireWriterAsync(db, device, bound.SourceCode);
- var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(bound);
- Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE");
- var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, bound.SourceCode, bound.DatasetKey);
- var window = new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime);
- var result = await ParseApiPageAsync(db, device, task, batch, new IngestBatchPreparer(schemas), scope, window, plan);
- Require(MdpBatchFactory.RowsMatch(result.Prepared), "EDGE_BATCH_SCOPE_INVALID");
- var count = result.Prepared.Events.Count;
- var processed = count == 0 ? null : PurchaseBatchProcessor.Process(result.Prepared, "");
- var valid = processed?.Package.Items.Count ?? 0;
- var isolated = processed?.Quarantines.Select(row => row.RawEventId).Distinct().Count() ?? 0;
- var evidence = JsonSerializer.SerializeToUtf8Bytes(new { task.Stream, task.Position, task.ConfigVersion,
- page.BatchId, batch.Digest, Path = path, count, valid, isolated, result.ConfirmedPosition }, EdgeProtocol.Json);
- return (new MdpEdgePagePreview(batch.BatchId, batch.Digest, count, valid, isolated, result.ConfirmedPosition is not null,
- EdgeProtocol.Digest(evidence)), result);
- }
- private static async Task<PageResult> ParseApiPageAsync(ISqlSugarClient db, Device device, EdgeTask task, EdgeBatch batch,
- IngestBatchPreparer preparer, IngestDatasetIdentity scope, IngestSourceWindow window, MdpApiPullPlan plan)
- {
- Require(device.PageCount < plan.MaxPages, "PULL_PAGE_LIMIT");
- if (batch.Diagnostic is not null) throw new EdgeContractException("PULL_LINK_INVALID");
- var prepared = preparer.PrepareApiPage(scope, task.SchemaVersion, batch.Body, MdpIngestProtocol.Limits,
- MdpApiPullPlan.Path(plan.ResponsePath), window);
- using var json = JsonDocument.Parse(batch.Body);
- Require(Uri.TryCreate(batch.EffectiveUrl, UriKind.Absolute, out var effective) && MdpApiPullEgress.SameOrigin(plan.Endpoint, effective),
- "PULL_LINK_FORBIDDEN");
- var next = plan.Next(JsonSerializer.Deserialize<MdpApiPullPosition>(batch.Position!, EdgeProtocol.Json)!,
- json.RootElement, prepared.Events.Count, effective!, batch.NextLink, device.RowCount);
- var position = next is null ? null : JsonSerializer.Serialize(next, EdgeProtocol.Json);
- if (position is not null)
- Require(await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_edge_receipt WHERE device_id=@DeviceId AND generation=@Generation AND position_hash=@hash
- """, new { device.DeviceId, device.Generation, hash = HashText(position) }) == 0, "PULL_POSITION_STALLED");
- return new PageResult(prepared, position);
- }
- private static Task<int> RecordRejectedPageAsync(ISqlSugarClient db, Device device, EdgeBatch batch) =>
- db.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_edge_api_rejected_page(batch_id,device_id,generation,position_hash,effective_url,next_link,link_diagnostic)
- VALUES (@id,@DeviceId,@Generation,@position,@EffectiveUrl,@NextLink,@Diagnostic)
- """, new { id = batch.BatchId.ToString("D"), device.DeviceId, device.Generation, position = HashText(batch.Position!),
- batch.EffectiveUrl, batch.NextLink, batch.Diagnostic });
- private static async Task<EdgeTask> RecoveryTaskAsync(ISqlSugarClient db, Device device, bool includeSettled)
- {
- var task = ReadTask(device);
- var attempt = task.Mode == EdgeProtocol.ApiPull && task.Position is not null ? await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND generation=@Generation
- AND position_hash=@hash AND settlement='refetch'
- """, new { device.DeviceId, device.Generation, hash = HashText(task.Position) }) : 0;
- var settled = includeSettled ? await db.Ado.SqlQueryAsync<string>("""
- SELECT CONCAT(batch_id,'') FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND settled_at IS NOT NULL
- ORDER BY settled_at DESC LIMIT 100
- """, new { device.DeviceId }) : [];
- return task with { RecoveryAttempt = attempt, SettledPages = settled.Select(Guid.Parse).ToArray() };
- }
- private sealed record PageResult(PreparedIngestBatch Prepared, string? ConfirmedPosition);
- private sealed class RejectedPage
- {
- public string BatchId { get; set; } = "";
- public string? EffectiveUrl { get; set; }
- public string? NextLink { get; set; }
- public string? LinkDiagnostic { get; set; }
- public byte[] IdemKey { get; set; } = [];
- public string Digest { get; set; } = "";
- public string ReceiptJson { get; set; } = "";
- public byte[] Body { get; set; } = [];
- public DateTime ReceivedAt { get; set; }
- }
- }
|