MdpIngestDatasetController.ApiPull.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.DependencyInjection;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed partial class MdpIngestDatasetController
  7. {
  8. [HttpGet("{id:long}/api-pull")]
  9. public Task<IActionResult> ReadApiPull(long id, long? factoryId) =>
  10. ApiPullAction(id, factoryId, TrialPermission, async (service, scope) =>
  11. Ok(new
  12. {
  13. profiles = await service.ListProfilesAsync(scope.TenantId, scope.FactoryId, id),
  14. runs = await service.ListRunsAsync(scope.TenantId, scope.FactoryId, id),
  15. canApprove = await Can(PublishPermission)
  16. }));
  17. [HttpPost("{id:long}/api-pull/import"), RequestSizeLimit(524288)]
  18. public Task<IActionResult> ImportApiPull(long id, long? factoryId, MdpApiPullImportInput input) =>
  19. ApiPullAction(id, factoryId, TrialPermission, (_, _) =>
  20. Task.FromResult<IActionResult>(Ok(MdpApiPullImport.Read(input.Kind, input.Text, input.Selection))));
  21. [HttpPost("{id:long}/api-pull/profiles"), RequestSizeLimit(65536)]
  22. public Task<IActionResult> CreateApiPull(long id, long? factoryId, MdpApiPullCreateInput input, CancellationToken token) =>
  23. ApiPullAction(id, factoryId, TrialPermission, async (service, scope) =>
  24. Ok(new { id = await service.CreateAsync(scope.TenantId, scope.FactoryId, id, input.SourceId, user.UserId, input.Plan, token) }));
  25. [HttpPost("{id:long}/api-pull/profiles/{profile:long}/preflight")]
  26. public Task<IActionResult> PreflightApiPull(long id, long profile, long? factoryId, CancellationToken token) =>
  27. ApiPullAction(id, factoryId, TrialPermission, async (service, scope) =>
  28. Ok(await service.PreflightAsync(scope.TenantId, scope.FactoryId, id, profile, user.UserId, token)));
  29. [HttpPost("{id:long}/api-pull/profiles/{profile:long}/activate")]
  30. public Task<IActionResult> ActivateApiPull(long id, long profile, long? factoryId, CancellationToken token) =>
  31. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  32. {
  33. await service.ActivateAsync(scope.TenantId, scope.FactoryId, id, profile, user.UserId, token);
  34. return NoContent();
  35. });
  36. [HttpPost("{id:long}/api-pull/profiles/{profile:long}/pause")]
  37. public Task<IActionResult> PauseApiPull(long id, long profile, long? factoryId) =>
  38. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  39. {
  40. await service.PauseAsync(scope.TenantId, scope.FactoryId, id, profile);
  41. return NoContent();
  42. });
  43. [HttpPost("{id:long}/api-pull/profiles/{profile:long}/runs")]
  44. public Task<IActionResult> StartApiPull(long id, long profile, long? factoryId, CancellationToken token) =>
  45. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  46. Ok(new { runId = await service.StartAsync(scope.TenantId, scope.FactoryId, id, profile, token) }));
  47. [HttpPost("{id:long}/api-pull/runs/{run:guid}/advance")]
  48. public Task<IActionResult> AdvanceApiPull(long id, Guid run, long? factoryId, CancellationToken token) =>
  49. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  50. Ok(new { phase = await service.AdvanceAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"), token) }));
  51. [HttpGet("{id:long}/api-pull/runs/{run:guid}/pages/{ordinal:int}/history")]
  52. public Task<IActionResult> ReadApiPullRecoveryHistory(long id, Guid run, int ordinal, long? factoryId) =>
  53. ApiPullAction(id, factoryId, TrialPermission, async (service, scope) =>
  54. Ok(await service.ReadRecoveryHistoryAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"), ordinal)));
  55. [HttpPost("{id:long}/api-pull/runs/{run:guid}/pages/{ordinal:int}/attempts/{attempt:int}/raw")]
  56. public Task<IActionResult> ExportApiPullRaw(long id, Guid run, int ordinal, int attempt, long? factoryId, CancellationToken token) =>
  57. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  58. {
  59. var capture = await service.ExportCaptureAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"),
  60. ordinal, attempt, user.UserId, token);
  61. Response.Headers.CacheControl = "no-store";
  62. Response.Headers["X-Content-Type-Options"] = "nosniff";
  63. return File(capture.Payload, "application/octet-stream", $"{capture.BatchId}.raw");
  64. });
  65. [HttpPost("{id:long}/api-pull/runs/{run:guid}/recovery/preview"), RequestSizeLimit(4096)]
  66. public Task<IActionResult> PreviewApiPullRecovery(long id, Guid run, long? factoryId, MdpApiPullRecoveryPreviewInput input,
  67. CancellationToken token) =>
  68. ApiPullAction(id, factoryId, TrialPermission, async (service, scope) =>
  69. Ok(await service.PreviewRecoveryAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"), input.ResponsePath, token)));
  70. [HttpPost("{id:long}/api-pull/runs/{run:guid}/recovery"), RequestSizeLimit(4096)]
  71. public Task<IActionResult> RecoverApiPull(long id, Guid run, long? factoryId, MdpApiPullRecoveryInput input, CancellationToken token) =>
  72. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  73. {
  74. await service.RecoverAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"), user.UserId, input, token);
  75. return NoContent();
  76. });
  77. [HttpPost("{id:long}/api-pull/runs/{run:guid}/cancel")]
  78. public Task<IActionResult> CancelApiPull(long id, Guid run, long? factoryId) =>
  79. ApiPullAction(id, factoryId, PublishPermission, async (service, scope) =>
  80. {
  81. await service.CancelAsync(scope.TenantId, scope.FactoryId, id, run.ToString("D"));
  82. return NoContent();
  83. });
  84. private Task<IActionResult> ApiPullAction(long id, long? factoryId, string permission,
  85. Func<MdpApiPullService, DatasetScope, Task<IActionResult>> action)
  86. => WithScope(factoryId, async scope =>
  87. {
  88. if (!await Can(permission)) return Forbid();
  89. if (!await Datasets(scope).AnyAsync(row => row.Id == id)) return NotFound();
  90. try { return await action(HttpContext.RequestServices.GetRequiredService<MdpApiPullService>(), scope); }
  91. catch (MdpApiPullException error)
  92. {
  93. var status = error.Code switch
  94. {
  95. "PULL_PROFILE_NOT_FOUND" or "PULL_CAPTURE_NOT_FOUND" => 404,
  96. "RAW_PAYLOAD_EXPIRED" => 410,
  97. "PULL_TARGET_FORBIDDEN" or "PULL_ADDRESS_FORBIDDEN" or "PULL_SOURCE_NOT_AUTHORIZED" or "PULL_CREDENTIAL_FORBIDDEN" => 403,
  98. "PULL_LOCAL_RATE_LIMITED" or "PULL_SOURCE_RATE_LIMITED" => 429,
  99. "PULL_TIMEOUT" => 504,
  100. "PULL_TEMPORARY" => 503,
  101. _ when error.Code.StartsWith("PULL_IMPORT", StringComparison.Ordinal) || error.Code is "PULL_CONFIG_INVALID" or "PULL_RECOVERY_INVALID" => 400,
  102. _ => 409
  103. };
  104. if (error.Retry is { } retry) Response.Headers.RetryAfter = Math.Clamp((int)retry.TotalSeconds, 1, 3600).ToString();
  105. return StatusCode(status, new { code = error.Code, traceId = HttpContext.TraceIdentifier });
  106. }
  107. catch (MdpIngestHttpException error) { return StatusCode(error.StatusCode, new { code = error.Code }); }
  108. catch (IngestContractException error) { return UnprocessableEntity(new { code = error.Code.ToString() }); }
  109. catch (Exception error) when (error is JsonException or ArgumentException)
  110. {
  111. return BadRequest(new { code = "PULL_CONFIG_INVALID" });
  112. }
  113. catch (Exception error) when (error is System.Data.Common.DbException or SqlSugarException)
  114. {
  115. return StatusCode(503, new { code = "PULL_STORE_UNAVAILABLE", traceId = HttpContext.TraceIdentifier });
  116. }
  117. });
  118. }
  119. public sealed record MdpApiPullImportInput(string Kind, string Text, string? Selection);
  120. public sealed record MdpApiPullCreateInput(long SourceId, MdpApiPullPlan Plan);
  121. public sealed record MdpApiPullRecoveryPreviewInput(string ResponsePath);