MdpRelationalSyncController.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using System.Globalization;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Text.Json;
  7. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  8. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  9. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  10. public sealed partial class MdpIngestDatasetController
  11. {
  12. [HttpGet("{id:long}/relational-sync")]
  13. public Task<IActionResult> ListRelationalSync(long id, long? factoryId, CancellationToken token) =>
  14. WithScope(factoryId, async scope =>
  15. {
  16. if (!await Can(TrialPermission)) return Forbid();
  17. var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
  18. if (dataset is null) return NotFound();
  19. var profiles = await TrialProfiles(scope, id, token);
  20. if (!profiles.Any(p => p.SyncEnabled)) return Ok(Array.Empty<object>());
  21. try
  22. {
  23. var sync = HttpContext.RequestServices.GetRequiredService<MdpRelationalSyncService>();
  24. return Ok(await sync.ListAsync(scope.TenantId, scope.FactoryId, id));
  25. }
  26. catch (MySqlConnector.MySqlException)
  27. {
  28. return StatusCode(503, new { message = "请核对数据库同步存储是否已部署" });
  29. }
  30. });
  31. [HttpPost("{id:long}/relational-sync/{profileId}/start")]
  32. public Task<IActionResult> StartRelationalSync(long id, string profileId, long? factoryId, string? mode, CancellationToken token) =>
  33. ExecuteRelationalSync(id, profileId, null, factoryId, mode ?? "FULL", token);
  34. [HttpPost("{id:long}/relational-sync/{profileId}/{runId:guid}/advance")]
  35. public Task<IActionResult> AdvanceRelationalSync(long id, string profileId, Guid runId, long? factoryId, CancellationToken token) =>
  36. ExecuteRelationalSync(id, profileId, runId, factoryId, "RESUME", token);
  37. [HttpPost("{id:long}/relational-sync/{profileId}/{runId:guid}/check-archived")]
  38. public Task<IActionResult> CheckArchivedRelationalSync(long id, string profileId, Guid runId, long? factoryId, CancellationToken token) =>
  39. WithScope(factoryId, async scope =>
  40. {
  41. if (!await Can(TrialPermission) || !await Can(PublishPermission)) return Forbid();
  42. var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
  43. if (dataset is null) return NotFound();
  44. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  45. deadline.CancelAfter(TimeSpan.FromSeconds(75));
  46. try
  47. {
  48. var sync = HttpContext.RequestServices.GetRequiredService<MdpRelationalSyncService>();
  49. return Ok(await sync.CheckArchivedRunAsync(dataset, profileId, runId, user.UserId, deadline.Token));
  50. }
  51. catch (MdpIngestHttpException error)
  52. {
  53. return StatusCode(error.StatusCode, new { message = RelationalRecoveryMessage(error.Code), code = error.Code });
  54. }
  55. catch (OperationCanceledException) when (!token.IsCancellationRequested)
  56. {
  57. return StatusCode(504, new { message = "旧批次核对超时,可继续核对" });
  58. }
  59. catch (Exception error) when (error is System.Data.Common.DbException or SqlSugarException or JsonException
  60. or ConnectorContractException or ArgumentException or InvalidOperationException)
  61. {
  62. return StatusCode(503, new { message = "请核对旧窗口的归档版本、冻结批次和 Raw 回执" });
  63. }
  64. });
  65. private static string RelationalRecoveryMessage(string code) => code switch
  66. {
  67. "RELATIONAL_REINITIALIZATION_REQUIRED" => "来源历史已过期,原水位已保留,请重新全量初始化",
  68. "RELATIONAL_PLAN_CHANGED" => "配置已变更,请核对旧批次或恢复原配置后继续",
  69. "RELATIONAL_ARCHIVE_UNAVAILABLE" => "无法取得旧窗口的归档映射",
  70. "RELATIONAL_ARCHIVE_CHECK_UNAVAILABLE" => "当前窗口没有待核对的旧配置",
  71. "RELATIONAL_RUN_BUSY" => "另一实例正在处理该窗口,请稍后再继续",
  72. _ => "同步批次尚未取得可推进的回执",
  73. };
  74. private Task<IActionResult> ExecuteRelationalSync(long id, string profileId, Guid? prior, long? factoryId, string mode, CancellationToken token) =>
  75. WithScope(factoryId, async scope =>
  76. {
  77. if (!await Can(TrialPermission) || !await Can(PublishPermission)) return Forbid();
  78. var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
  79. if (dataset is null) return NotFound();
  80. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  81. deadline.CancelAfter(TimeSpan.FromSeconds(75));
  82. var work = deadline.Token;
  83. try
  84. {
  85. var profile = (await TrialProfiles(scope, id, work)).SingleOrDefault(p => p.Id == profileId && p.SyncEnabled);
  86. if (profile is null) return NotFound();
  87. if (!prior.HasValue && mode is not ("FULL" or "INCR" or "REPLAY"))
  88. return BadRequest(new { message = "请选择全量、增量或回看窗口" });
  89. var source = await BoundSource(dataset, profile.SourceId);
  90. if (source is null)
  91. return Conflict(new { message = "请先启用已审批且绑定来源的接收版本" });
  92. var sync = HttpContext.RequestServices.GetRequiredService<MdpRelationalSyncService>();
  93. return Ok(await sync.RunAsync(profile, prior, mode, work));
  94. }
  95. catch (OperationCanceledException) when (!token.IsCancellationRequested)
  96. {
  97. return StatusCode(504, new { message = "同步操作超时。已冻结的批次可从任务记录继续" });
  98. }
  99. catch (MdpIngestHttpException error)
  100. {
  101. return StatusCode(error.StatusCode, new { message = RelationalRecoveryMessage(error.Code), code = error.Code });
  102. }
  103. catch (ConnectorContractException error)
  104. {
  105. return Conflict(new { message = "数据库同步未通过检查", code = error.Code.ToString() });
  106. }
  107. catch (MySqlConnector.MySqlException error) when (error.Number == 1062)
  108. {
  109. return Conflict(new { message = "当前来源已有未结束的同步运行,继续已有运行即可" });
  110. }
  111. catch (Exception error) when (error is System.Data.Common.DbException or IOException or JsonException or
  112. HttpRequestException or ArgumentException or UnauthorizedAccessException or InvalidOperationException or NotSupportedException)
  113. {
  114. return StatusCode(503, new { message = "请核对同步存储、只读快照能力和接收配置" });
  115. }
  116. });
  117. }