MdpIngestController.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  7. [ApiController]
  8. [Route("api/v1/ingest")]
  9. [NonUnify]
  10. [Authorize(AuthenticationSchemes = MdpIngestProtocol.AuthenticationScheme)]
  11. public sealed class MdpIngestController(MdpIngestReceiveService receiver) : ControllerBase
  12. {
  13. private static readonly JsonSerializerOptions ResponseJson = new(JsonSerializerDefaults.Web);
  14. [HttpPost("{datasetKey}")]
  15. [ProducesResponseType(typeof(MdpIngestReceipt), StatusCodes.Status202Accepted)]
  16. public async Task<IActionResult> Receive([FromRoute] string datasetKey, CancellationToken cancellationToken)
  17. {
  18. if (HttpContext.Items[typeof(MdpIngestSubmission)] is not MdpIngestSubmission submission)
  19. return Error(StatusCodes.Status401Unauthorized, "AUTHENTICATION_REQUIRED");
  20. if (!string.Equals(submission.DatasetKey, datasetKey, StringComparison.Ordinal))
  21. return Error(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
  22. try
  23. {
  24. var receipt = await receiver.ReceiveAsync(submission, cancellationToken);
  25. return IngestJson(StatusCodes.Status202Accepted, receipt);
  26. }
  27. catch (MdpIngestHttpException error)
  28. {
  29. return Error(error.StatusCode, error.Code);
  30. }
  31. catch (IngestContractException error)
  32. {
  33. var (status, code) = error.Code switch
  34. {
  35. IngestContractError.DatasetUnavailable => (StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE"),
  36. IngestContractError.UnknownSchema => (StatusCodes.Status422UnprocessableEntity, "UNKNOWN_SCHEMA"),
  37. IngestContractError.BodyTooLarge => (StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE"),
  38. IngestContractError.TooManyRecords => (StatusCodes.Status422UnprocessableEntity, "TOO_MANY_RECORDS"),
  39. IngestContractError.JsonTooDeep => (StatusCodes.Status422UnprocessableEntity, "JSON_TOO_DEEP"),
  40. IngestContractError.InvalidJson => (StatusCodes.Status400BadRequest, "INVALID_JSON"),
  41. _ => (StatusCodes.Status400BadRequest, "INVALID_ENVELOPE")
  42. };
  43. return Error(status, code);
  44. }
  45. }
  46. private ContentResult Error(int status, string code) =>
  47. IngestJson(status, new { code, traceId = HttpContext.TraceIdentifier });
  48. // 接收契约的字段名和 UTC 时间格式独立于后台页面的序列化设置。
  49. private static ContentResult IngestJson(int status, object body) => new()
  50. {
  51. Content = JsonSerializer.Serialize(body, ResponseJson),
  52. ContentType = "application/json; charset=utf-8",
  53. StatusCode = status
  54. };
  55. }