MdpRelationalTrialController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
  2. using System.Globalization;
  3. using System.Net;
  4. using System.Net.Http.Json;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Text.Json;
  8. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  9. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  10. using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
  11. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  12. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  13. public sealed partial class MdpIngestDatasetController
  14. {
  15. private const int RelationalTrialPages = 5;
  16. private async Task<RelationalTrialProfile[]> TrialProfiles(DatasetScope scope, long id, CancellationToken token) =>
  17. (await ReadProfiles(Settings["MDP_RELATIONAL_TRIALS_FILE"], token)).Where(profile =>
  18. profile.TenantId == scope.TenantId && profile.FactoryId == scope.FactoryId && profile.DatasetId == id).ToArray();
  19. [HttpGet("{id:long}/relational-trials")]
  20. public Task<IActionResult> ListRelationalTrials(long id, long? factoryId, CancellationToken token) =>
  21. WithScope(factoryId, async scope =>
  22. {
  23. if (!await Datasets(scope).AnyAsync(d => d.Id == id)) return NotFound();
  24. if (!await Can(TrialPermission)) return Ok(Array.Empty<object>());
  25. try
  26. {
  27. return Ok((await TrialProfiles(scope, id, token)).Select(p => new { p.Id, p.Name, p.Driver }));
  28. }
  29. catch (Exception error) when (error is IOException or JsonException or UnauthorizedAccessException)
  30. {
  31. return StatusCode(503, new { message = "数据库连接器试跑配置无法读取" });
  32. }
  33. });
  34. [HttpGet("{id:long}/relational-trials/{profileId}/probe")]
  35. public Task<IActionResult> ProbeRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
  36. ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: true, token);
  37. [HttpGet("{id:long}/relational-trials/{profileId}/catalog")]
  38. public Task<IActionResult> InspectRelationalTrial(long id, string profileId, long? factoryId, string? objectName, CancellationToken token) =>
  39. WithScope(factoryId, async scope =>
  40. {
  41. if (!await Can(TrialPermission)) return Forbid();
  42. var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
  43. if (dataset is null) return NotFound();
  44. try
  45. {
  46. var profile = (await TrialProfiles(scope, id, token)).SingleOrDefault(p => p.Id == profileId);
  47. if (profile is null) return NotFound();
  48. var source = await BoundSource(dataset, profile.SourceId);
  49. if (source is null) return NotFound();
  50. var binding = new ConnectorBinding(new(scope.TenantId, scope.FactoryId, source.Id, id,
  51. source.SourceCode, dataset.DatasetKey), dataset.ActiveSchemaVersion ?? "draft",
  52. dataset.Revision.ToString(CultureInfo.InvariantCulture));
  53. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  54. deadline.CancelAfter(TimeSpan.FromSeconds(20));
  55. var report = await InspectProfile(profile, binding, deadline.Token, objectName);
  56. return Ok(new { dataset.Revision, report, canMeasureCapacity = string.IsNullOrWhiteSpace(objectName) || string.Equals(objectName, profile.Table, StringComparison.Ordinal) });
  57. }
  58. catch (OperationCanceledException) when (!token.IsCancellationRequested)
  59. {
  60. return StatusCode(504, new { message = "来源预检超时" });
  61. }
  62. catch (Exception error) when (error is ConnectorContractException or System.Data.Common.DbException or
  63. IOException or JsonException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
  64. {
  65. return StatusCode(503, new { message = "请核对来源配置、连通性或只读授权" });
  66. }
  67. });
  68. [HttpPost("{id:long}/relational-trials/{profileId}")]
  69. public Task<IActionResult> RunRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
  70. ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: false, token);
  71. private Task<IActionResult> ExecuteRelationalTrial(long id, string profileId, long? factoryId, bool probeOnly,
  72. CancellationToken token) =>
  73. WithScope(factoryId, async scope =>
  74. {
  75. if (!await Can(TrialPermission)) return Forbid();
  76. var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
  77. if (dataset is null) return NotFound();
  78. try
  79. {
  80. var profile = (await TrialProfiles(scope, id, token)).SingleOrDefault(p => p.Id == profileId);
  81. if (profile is null) return NotFound();
  82. var source = await BoundSource(dataset, profile.SourceId);
  83. if (source is null || !dataset.Enabled || dataset.ActiveSchemaVersion is null || await Lifecycle(id) != "ACTIVE")
  84. return Conflict(new { message = "请先启用已绑定来源的采购接收版本" });
  85. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  86. deadline.CancelAfter(TimeSpan.FromSeconds(25));
  87. var (runtime, binding, _) = await CreateRelationalTrial(db, profile, dataset, source);
  88. var probe = await runtime.ProbeAsync(deadline.Token);
  89. if (probeOnly) return Ok(probe);
  90. if (!probe.Supported)
  91. return Conflict(new { message = "数据库读取能力未通过检查", code = "UnsupportedCapability", probe.Reason });
  92. if (profile.Preflight is not null || profile.SyncEnabled)
  93. {
  94. var report = await InspectProfile(profile, binding, deadline.Token);
  95. var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
  96. if (blocked is not null)
  97. return Conflict(new { message = blocked.Message, code = blocked.Code });
  98. }
  99. return Ok(await ReadRelationalTrial(profile, dataset, runtime, binding, deadline.Token));
  100. }
  101. catch (ConnectorContractException error)
  102. {
  103. if (probeOnly && error.Code is ConnectorError.SourceUnavailable or ConnectorError.ScopeMismatch
  104. or ConnectorError.InvalidManifest or ConnectorError.UnsupportedCapability or ConnectorError.UnsupportedVersion)
  105. return Ok(new ConnectorProbeResult(false, error.Code switch
  106. {
  107. ConnectorError.SourceUnavailable => "source-unavailable",
  108. ConnectorError.ScopeMismatch => "database-scope-mismatch",
  109. _ => "driver-configuration-invalid",
  110. }));
  111. return Conflict(new { message = "数据库连接器校验失败", code = error.Code.ToString() });
  112. }
  113. catch (MdpIngestHttpException error)
  114. {
  115. return StatusCode(error.StatusCode, new { message = "统一接收未返回可推进的回执", code = error.Code });
  116. }
  117. catch (OperationCanceledException) when (!token.IsCancellationRequested)
  118. {
  119. return StatusCode(504, new { message = "数据库连接器试跑超时,请核对已有批次" });
  120. }
  121. catch (Exception error) when (error is IOException or JsonException or HttpRequestException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
  122. {
  123. return StatusCode(503, new { message = "请核对试跑配置、只读连接和接收凭据" });
  124. }
  125. });
  126. private async Task CheckConfiguredSourcePreflight(MdpIngestDataset dataset, MdpSource source, Release candidate, CancellationToken token)
  127. {
  128. var scope = new DatasetScope(dataset.TenantId, dataset.FactoryId, "");
  129. var profiles = (await TrialProfiles(scope, dataset.Id, token))
  130. .Where(p => p.SourceId == source.Id && (p.SyncEnabled || p.Preflight is not null)).ToArray();
  131. if (profiles.Length == 0) return;
  132. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  133. deadline.CancelAfter(TimeSpan.FromSeconds(20));
  134. var binding = new ConnectorBinding(new(dataset.TenantId, dataset.FactoryId, source.Id, dataset.Id,
  135. source.SourceCode, dataset.DatasetKey), candidate.Version, dataset.Revision.ToString(CultureInfo.InvariantCulture));
  136. try
  137. {
  138. foreach (var profile in profiles)
  139. {
  140. var report = await InspectProfile(profile, binding, deadline.Token);
  141. var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
  142. Require(blocked is null, blocked?.Message ?? "来源预检通过");
  143. }
  144. }
  145. catch (Exception error) when (!token.IsCancellationRequested && error is System.Data.Common.DbException or ConnectorContractException or OperationCanceledException)
  146. {
  147. Require(false, "数据库来源预检未通过,请核对连通性、驱动与只读授权");
  148. }
  149. }
  150. private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset,
  151. RelationalConnectorRuntime runtime, ConnectorBinding binding, CancellationToken token)
  152. {
  153. var (address, key) = await LoadRelationalReceiver(db, profile, dataset, token);
  154. var version = binding.SourceSchemaVersion;
  155. string? position = null;
  156. var receipts = new List<MdpIngestReceipt>();
  157. var complete = false;
  158. for (var page = 0; page < RelationalTrialPages; page++)
  159. {
  160. var read = await runtime.ReadAsync(new(position, 2), token);
  161. if (read is null) { complete = true; break; }
  162. var pending = read.Batch.Pending;
  163. var digest = SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new[]
  164. { profile.Id, version, pending.SourcePosition, pending.Id.PayloadSha256 }));
  165. var trialKey = "relational-trial-" + Convert.ToHexString(digest).ToLowerInvariant();
  166. var batch = ConnectorFrozenBatch.Capture(binding, new(trialKey, trialKey, read.Batch.Payload,
  167. pending.SourcePosition, pending.NextCheckpoint, read.HasMore));
  168. var receipt = await SubmitRelationalTrial(address, dataset.DatasetKey, batch, key, token);
  169. if (receipt.BatchId == Guid.Empty || receipt.SchemaVersion != version || receipt.ReceiveStatus != "accepted"
  170. || receipt.AcceptedRecordCount <= 0)
  171. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  172. var decision = ConnectorResume.Decide(binding, batch.Pending,
  173. new(batch.Pending.Id, ConnectorConfirmation.CloudDurable, receipt.BatchId), batch);
  174. if (decision.Action != ConnectorResumeAction.Advance)
  175. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  176. position = decision.NextCheckpoint;
  177. receipts.Add(receipt);
  178. if (!read.HasMore) { complete = true; break; }
  179. }
  180. return new { profile.Driver, position, complete, receipts };
  181. }
  182. }