MdpInboundController.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. using System.Security.Claims;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
  4. using Microsoft.AspNetCore.Http;
  5. namespace Admin.NET.Plugin.AiDOP.Controllers;
  6. /// <summary>第三方标准 API 推数入站。类级仅指定 InboundSignature,不加裸 [Authorize]、不加 [AllowAnonymous]。</summary>
  7. [ApiController]
  8. [Route("api/mdp/inbound")]
  9. [NonUnify]
  10. [Authorize(AuthenticationSchemes = InboundSignatureDefaults.AuthenticationScheme)]
  11. [ApiDescriptionSettings(Order = 331, Description = "MDP API_INBOUND 推数入站")]
  12. public class MdpInboundController : ControllerBase
  13. {
  14. private readonly MdpInboundReceiveService _receive;
  15. private readonly MdpInboundSnapshotService _snapshots;
  16. public MdpInboundController(MdpInboundReceiveService receive, MdpInboundSnapshotService snapshots)
  17. {
  18. _receive = receive;
  19. _snapshots = snapshots;
  20. }
  21. /// <summary>接收推数。签名串 POST&amp;{path}&amp;...(方案 §5.2)。</summary>
  22. [HttpPost("{entityCode}")]
  23. public async Task<IActionResult> Receive(string entityCode, CancellationToken ct)
  24. {
  25. Request.EnableBuffering();
  26. using var ms = new MemoryStream();
  27. await Request.Body.CopyToAsync(ms);
  28. Request.Body.Position = 0;
  29. var outcome = await _receive.ReceiveAsync(new MdpInboundReceiveArgs
  30. {
  31. EntityCode = entityCode,
  32. RawBody = ms.ToArray(),
  33. AccessKey = AccessKey(),
  34. TenantId = TenantId(),
  35. IdempotencyKey = Header(InboundSignatureDefaults.IdempotencyKeyHeader),
  36. ClientIp = ClientIp(),
  37. Path = Request.Path.Value ?? string.Empty,
  38. Headers = Request.Headers.ToDictionary(
  39. h => h.Key,
  40. h => h.Value.ToString(),
  41. StringComparer.OrdinalIgnoreCase)
  42. }, ct);
  43. return JsonOutcome(outcome);
  44. }
  45. /// <summary>对外规范字段 JSON Schema。签名串 GET&amp;{path}&amp;...,须带与 POST 相同的签名头(空 body 摘要)。</summary>
  46. [HttpGet("{entityCode}/schema")]
  47. public async Task<IActionResult> Schema(string entityCode, CancellationToken ct)
  48. {
  49. var outcome = await _receive.SchemaAsync(
  50. entityCode, AccessKey(), TenantId(), ClientIp(), ct, ContractVersion());
  51. return JsonOutcome(outcome);
  52. }
  53. /// <summary>按批次查回执。非本 AccessKey 的批次返回 404。</summary>
  54. [HttpGet("receipts/{syncBatchId}")]
  55. public async Task<IActionResult> Receipt(string syncBatchId, CancellationToken ct)
  56. {
  57. var outcome = await _receive.ReceiptAsync(syncBatchId, AccessKey(), ct);
  58. return JsonOutcome(outcome);
  59. }
  60. /// <summary>开启全量快照。同一 (tenant, access_key, entity) 已有 OPEN → 409。</summary>
  61. [HttpPost("{entityCode}/snapshots")]
  62. public async Task<IActionResult> OpenSnapshot(string entityCode, CancellationToken ct)
  63. {
  64. var outcome = await _snapshots.OpenAsync(entityCode, AccessKey(), TenantId(), ClientIp(), ct);
  65. return JsonOutcome(outcome);
  66. }
  67. /// <summary>提交快照差集。?force=true 仅当状态为 DIFF_BLOCKED。</summary>
  68. [HttpPost("{entityCode}/snapshots/{snapshotId}/commit")]
  69. public async Task<IActionResult> CommitSnapshot(string entityCode, string snapshotId, [FromQuery] bool force, CancellationToken ct)
  70. {
  71. try
  72. {
  73. var outcome = await _snapshots.CommitAsync(
  74. entityCode, snapshotId, AccessKey(), TenantId(), ClientIp(), force, ct);
  75. return JsonOutcome(outcome);
  76. }
  77. catch (MdpInboundBatchException ex)
  78. {
  79. return JsonOutcome(new MdpInboundOutcome
  80. {
  81. HttpStatus = ex.HttpStatus,
  82. Body = new { code = ex.HttpStatus, message = ex.Message, data = (object)null }
  83. });
  84. }
  85. }
  86. /// <summary>NDJSON 分块推送。每行独立 idempotencyKey,整包仍走一次入站签名。</summary>
  87. [HttpPost("{entityCode}/bulk")]
  88. public async Task<IActionResult> Bulk(string entityCode, CancellationToken ct)
  89. {
  90. Request.EnableBuffering();
  91. using var ms = new MemoryStream();
  92. await Request.Body.CopyToAsync(ms);
  93. Request.Body.Position = 0;
  94. var outcome = await _receive.BulkAsync(new MdpInboundReceiveArgs
  95. {
  96. EntityCode = entityCode,
  97. RawBody = ms.ToArray(),
  98. AccessKey = AccessKey(),
  99. TenantId = TenantId(),
  100. IdempotencyKey = Header(InboundSignatureDefaults.IdempotencyKeyHeader),
  101. ClientIp = ClientIp(),
  102. Path = Request.Path.Value ?? string.Empty,
  103. Headers = Request.Headers.ToDictionary(
  104. h => h.Key,
  105. h => h.Value.ToString(),
  106. StringComparer.OrdinalIgnoreCase)
  107. }, ct);
  108. return JsonOutcome(outcome);
  109. }
  110. /// <summary>日终对账。query 用 date 或 bizDate(yyyy-MM-dd)。</summary>
  111. [HttpGet("{entityCode}/digest")]
  112. public async Task<IActionResult> Digest(string entityCode, [FromQuery] string date, [FromQuery] string bizDate, CancellationToken ct)
  113. {
  114. var raw = !string.IsNullOrWhiteSpace(date) ? date : bizDate;
  115. var outcome = await _receive.DigestAsync(entityCode, AccessKey(), TenantId(), ClientIp(), raw, ct);
  116. return JsonOutcome(outcome);
  117. }
  118. private IActionResult JsonOutcome(MdpInboundOutcome outcome) =>
  119. new ContentResult
  120. {
  121. Content = JsonSerializer.Serialize(outcome.Body, MdpInboundJson.Options),
  122. ContentType = "application/json",
  123. StatusCode = outcome.HttpStatus
  124. };
  125. private string AccessKey() =>
  126. User.FindFirstValue(InboundSignatureDefaults.AccessKeyClaim) ?? string.Empty;
  127. private long TenantId()
  128. {
  129. var raw = User.FindFirstValue(ClaimConst.TenantId);
  130. return long.TryParse(raw, out var id) ? id : 0;
  131. }
  132. private string Header(string name) => Request.Headers[name].FirstOrDefault() ?? string.Empty;
  133. private string ContractVersion() =>
  134. MdpInboundFieldMapper.NormalizeVersion(Header(MdpInboundFieldMapper.ContractVersionHeader));
  135. private string ClientIp()
  136. {
  137. var xff = Request.Headers["X-Forwarded-For"].FirstOrDefault();
  138. if (!string.IsNullOrWhiteSpace(xff))
  139. return xff.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()
  140. ?? string.Empty;
  141. return HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
  142. }
  143. }