MdpEdgeDeviceService.ApiRecovery.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. using System.Text;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed record MdpEdgePagePreviewInput(Guid BatchId, string ResponsePath);
  7. public sealed record MdpEdgePageApproval(Guid BatchId, string Digest, string Mode, string Reason, string? ResponsePath, string? PreviewToken);
  8. public sealed record MdpEdgePagePreview(Guid BatchId, string Digest, int Count, int Valid, int Isolated, bool HasNext, string Token);
  9. public sealed partial class MdpEdgeDeviceService
  10. {
  11. public async Task<MdpEdgePagePreview> PreviewPageAsync(long tenant, long factory, long dataset, Guid id, MdpEdgePagePreviewInput input)
  12. {
  13. RequireEnabled();
  14. using var db = MdpIngestDatabase.Open(host);
  15. var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, false);
  16. var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: false);
  17. return shadow.Preview;
  18. }
  19. public async Task RecoverPageAsync(long tenant, long factory, long dataset, Guid id, long actor,
  20. MdpEdgePageApproval input, CancellationToken token)
  21. {
  22. RequireEnabled();
  23. var reason = input.Reason?.Trim();
  24. Require(actor > 0 && reason is { Length: > 0 and <= 240 } && !reason.Any(char.IsControl)
  25. && (input.Mode == "reparse" || input.Mode == "refetch" && input.ResponsePath is null && input.PreviewToken is null),
  26. "EDGE_RECOVERY_INVALID");
  27. using var db = MdpIngestDatabase.Open(host);
  28. await Tx(db, async () =>
  29. {
  30. var (device, task, page, batch) = await RecoveryContextAsync(db, tenant, factory, dataset, id, input.BatchId, true);
  31. Require(input.Digest == batch.Digest, "EDGE_CAPTURE_MISMATCH");
  32. if (input.Mode == "refetch")
  33. {
  34. var scope = await BoundAsync(db, tenant, factory, dataset, device.SourceId, true);
  35. Require(scope.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
  36. await RequireWriterAsync(db, device, scope.SourceCode);
  37. await db.Ado.ExecuteCommandAsync("""
  38. UPDATE mdp_edge_device SET task_phase='READY' WHERE device_id=@DeviceId
  39. """, new { device.DeviceId });
  40. }
  41. else
  42. {
  43. var shadow = await ReparseAsync(db, device, task, page, batch, input.ResponsePath, lockDataset: true);
  44. Require(shadow.Preview.Token == input.PreviewToken, "EDGE_RECOVERY_PREVIEW_REQUIRED");
  45. var count = shadow.Result.Prepared.Events.Count;
  46. if (count > 0)
  47. {
  48. var originalTime = new DateTimeOffset(DateTime.SpecifyKind(page.ReceivedAt, DateTimeKind.Utc));
  49. var prepared = shadow.Result.Prepared with
  50. {
  51. Batch = shadow.Result.Prepared.Batch with { BatchId = batch.BatchId, ReceivedAt = originalTime },
  52. Events = shadow.Result.Prepared.Events.Select(row => row with { BatchId = batch.BatchId }).ToArray()
  53. };
  54. var key = Encoding.ASCII.GetBytes("\0edge-" + page.BatchId);
  55. await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, prepared, key, factory, token, useCapturedRaw: true);
  56. }
  57. var next = shadow.Result.ConfirmedPosition;
  58. var receipt = new EdgeReceipt(batch.BatchId, batch.Digest,
  59. count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted, batch.BatchId, next, SourcePosition: batch.Position);
  60. await db.Ado.ExecuteCommandAsync("""
  61. UPDATE mdp_edge_receipt SET receipt_json=@receipt WHERE batch_id=@BatchId AND device_id=@DeviceId
  62. """, new { page.BatchId, device.DeviceId, receipt = JsonSerializer.Serialize(receipt, EdgeProtocol.Json) });
  63. await db.Ado.ExecuteCommandAsync("""
  64. UPDATE mdp_edge_device SET position_text=@next,task_phase=@phase,
  65. page_count=page_count+1,row_count=row_count+@count WHERE device_id=@DeviceId
  66. """, new { device.DeviceId, next, phase = next is null ? "COMPLETE" : "READY", count });
  67. }
  68. await db.Ado.ExecuteCommandAsync("""
  69. UPDATE mdp_edge_api_rejected_page SET settlement=@Mode,response_path=@ResponsePath,settled_at=UTC_TIMESTAMP(6)
  70. WHERE batch_id=@BatchId AND device_id=@DeviceId AND settled_at IS NULL
  71. """, new { page.BatchId, device.DeviceId, input.Mode, input.ResponsePath });
  72. await AuditAsync(db, dataset, actor, "EDGE_PAGE_RECOVERY", $"{page.BatchId} {input.Mode} {reason}");
  73. token.ThrowIfCancellationRequested();
  74. return true;
  75. });
  76. }
  77. private static async Task<(Device Device, EdgeTask Task, RejectedPage Page, EdgeBatch Batch)> RecoveryContextAsync(
  78. ISqlSugarClient db, long tenant, long factory, long dataset, Guid id, Guid raw, bool locked)
  79. {
  80. var deviceId = id.ToString("D");
  81. var batchId = raw.ToString("D");
  82. var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  83. WHERE device_id=@deviceId AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  84. AND state='ACTIVE' AND task_phase='BLOCKED'
  85. """ + (locked ? " FOR UPDATE" : ""), new { deviceId, tenant, factory, dataset })
  86. ?? throw new EdgeContractException("EDGE_PAGE_NOT_BLOCKED");
  87. var task = ReadTask(device);
  88. Require(task.Mode == EdgeProtocol.ApiPull && task.Position is not null, "EDGE_PAGE_NOT_BLOCKED");
  89. var page = await db.Ado.SqlQuerySingleAsync<RejectedPage>("""
  90. SELECT p.batch_id AS BatchId,p.effective_url AS EffectiveUrl,p.next_link AS NextLink,p.link_diagnostic AS LinkDiagnostic,
  91. r.idem_key AS IdemKey,r.digest AS Digest,r.receipt_json AS ReceiptJson,b.payload AS Body,b.received_at AS ReceivedAt
  92. 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
  93. 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
  94. AND b.dataset_id=r.dataset_id AND b.source_id=r.source_id AND b.payload_sha256=r.digest
  95. WHERE p.batch_id=@batchId AND p.device_id=@deviceId AND p.generation=@Generation AND p.position_hash=@positionHash
  96. AND p.settled_at IS NULL AND r.tenant_id=@tenant AND r.factory_id=@factory AND r.dataset_id=@dataset
  97. AND r.source_id=@SourceId AND b.accepted_record_count=0
  98. """, new { batchId, deviceId, tenant, factory, dataset, device.Generation, device.SourceId, positionHash = HashText(task.Position!) })
  99. ?? throw new EdgeContractException("EDGE_CAPTURE_MISSING");
  100. var batch = EdgeBatch.Create(task.Stream, Encoding.ASCII.GetString(page.IdemKey), task.Position, null, page.Body) with
  101. {
  102. EffectiveUrl = page.EffectiveUrl, NextLink = page.NextLink, Diagnostic = page.LinkDiagnostic, ReceiverConfirmsNext = true
  103. };
  104. var receipt = JsonSerializer.Deserialize<EdgeReceipt>(page.ReceiptJson, EdgeProtocol.Json);
  105. Require(batch.BatchId == raw && batch.Digest == page.Digest && receipt?.Rejects(batch) == true, "EDGE_CAPTURE_MISMATCH");
  106. return (device, task, page, batch);
  107. }
  108. private static async Task<(MdpEdgePagePreview Preview, PageResult Result)> ReparseAsync(ISqlSugarClient db, Device device, EdgeTask task,
  109. RejectedPage page, EdgeBatch batch, string? path, bool lockDataset)
  110. {
  111. Require(path is { Length: <= 112 }, "EDGE_RECOVERY_INVALID");
  112. var plan = ParseApiPlan(task.ApiPlan) with { ResponsePath = path! };
  113. plan.Validate();
  114. var bound = await BoundAsync(db, task.TenantId, task.FactoryId, task.DatasetId, task.SourceId, lockDataset);
  115. Require(bound.SourceSchemaVersion == task.SchemaVersion, "EDGE_CONFIGURATION_STALE");
  116. if (lockDataset) await RequireWriterAsync(db, device, bound.SourceCode);
  117. var (schemas, contract) = await new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db)).ReadContractAsync(bound);
  118. Require(contract.ConfigVersion == task.ConfigVersion, "EDGE_CONFIGURATION_STALE");
  119. var scope = new IngestDatasetIdentity(task.TenantId, task.FactoryId, task.SourceId, task.DatasetId, bound.SourceCode, bound.DatasetKey);
  120. var window = new IngestSourceWindow(null, null, IngestSourceWindow.PurchaseApiTime);
  121. var result = await ParseApiPageAsync(db, device, task, batch, new IngestBatchPreparer(schemas), scope, window, plan);
  122. Require(MdpBatchFactory.RowsMatch(result.Prepared), "EDGE_BATCH_SCOPE_INVALID");
  123. var count = result.Prepared.Events.Count;
  124. var processed = count == 0 ? null : PurchaseBatchProcessor.Process(result.Prepared, "");
  125. var valid = processed?.Package.Items.Count ?? 0;
  126. var isolated = processed?.Quarantines.Select(row => row.RawEventId).Distinct().Count() ?? 0;
  127. var evidence = JsonSerializer.SerializeToUtf8Bytes(new { task.Stream, task.Position, task.ConfigVersion,
  128. page.BatchId, batch.Digest, Path = path, count, valid, isolated, result.ConfirmedPosition }, EdgeProtocol.Json);
  129. return (new MdpEdgePagePreview(batch.BatchId, batch.Digest, count, valid, isolated, result.ConfirmedPosition is not null,
  130. EdgeProtocol.Digest(evidence)), result);
  131. }
  132. private static async Task<PageResult> ParseApiPageAsync(ISqlSugarClient db, Device device, EdgeTask task, EdgeBatch batch,
  133. IngestBatchPreparer preparer, IngestDatasetIdentity scope, IngestSourceWindow window, MdpApiPullPlan plan)
  134. {
  135. Require(device.PageCount < plan.MaxPages, "PULL_PAGE_LIMIT");
  136. if (batch.Diagnostic is not null) throw new EdgeContractException("PULL_LINK_INVALID");
  137. var prepared = preparer.PrepareApiPage(scope, task.SchemaVersion, batch.Body, MdpIngestProtocol.Limits,
  138. MdpApiPullPlan.Path(plan.ResponsePath), window);
  139. using var json = JsonDocument.Parse(batch.Body);
  140. Require(Uri.TryCreate(batch.EffectiveUrl, UriKind.Absolute, out var effective) && MdpApiPullEgress.SameOrigin(plan.Endpoint, effective),
  141. "PULL_LINK_FORBIDDEN");
  142. var next = plan.Next(JsonSerializer.Deserialize<MdpApiPullPosition>(batch.Position!, EdgeProtocol.Json)!,
  143. json.RootElement, prepared.Events.Count, effective!, batch.NextLink, device.RowCount);
  144. var position = next is null ? null : JsonSerializer.Serialize(next, EdgeProtocol.Json);
  145. if (position is not null)
  146. Require(await db.Ado.GetIntAsync("""
  147. SELECT COUNT(*) FROM mdp_edge_receipt WHERE device_id=@DeviceId AND generation=@Generation AND position_hash=@hash
  148. """, new { device.DeviceId, device.Generation, hash = HashText(position) }) == 0, "PULL_POSITION_STALLED");
  149. return new PageResult(prepared, position);
  150. }
  151. private static Task<int> RecordRejectedPageAsync(ISqlSugarClient db, Device device, EdgeBatch batch) =>
  152. db.Ado.ExecuteCommandAsync("""
  153. INSERT INTO mdp_edge_api_rejected_page(batch_id,device_id,generation,position_hash,effective_url,next_link,link_diagnostic)
  154. VALUES (@id,@DeviceId,@Generation,@position,@EffectiveUrl,@NextLink,@Diagnostic)
  155. """, new { id = batch.BatchId.ToString("D"), device.DeviceId, device.Generation, position = HashText(batch.Position!),
  156. batch.EffectiveUrl, batch.NextLink, batch.Diagnostic });
  157. private static async Task<EdgeTask> RecoveryTaskAsync(ISqlSugarClient db, Device device, bool includeSettled)
  158. {
  159. var task = ReadTask(device);
  160. var attempt = task.Mode == EdgeProtocol.ApiPull && task.Position is not null ? await db.Ado.GetIntAsync("""
  161. SELECT COUNT(*) FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND generation=@Generation
  162. AND position_hash=@hash AND settlement='refetch'
  163. """, new { device.DeviceId, device.Generation, hash = HashText(task.Position) }) : 0;
  164. var settled = includeSettled ? await db.Ado.SqlQueryAsync<string>("""
  165. SELECT CONCAT(batch_id,'') FROM mdp_edge_api_rejected_page WHERE device_id=@DeviceId AND settled_at IS NOT NULL
  166. ORDER BY settled_at DESC LIMIT 100
  167. """, new { device.DeviceId }) : [];
  168. return task with { RecoveryAttempt = attempt, SettledPages = settled.Select(Guid.Parse).ToArray() };
  169. }
  170. private sealed record PageResult(PreparedIngestBatch Prepared, string? ConfirmedPosition);
  171. private sealed class RejectedPage
  172. {
  173. public string BatchId { get; set; } = "";
  174. public string? EffectiveUrl { get; set; }
  175. public string? NextLink { get; set; }
  176. public string? LinkDiagnostic { get; set; }
  177. public byte[] IdemKey { get; set; } = [];
  178. public string Digest { get; set; } = "";
  179. public string ReceiptJson { get; set; } = "";
  180. public byte[] Body { get; set; } = [];
  181. public DateTime ReceivedAt { get; set; }
  182. }
  183. }