MdpRelationalTrialController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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, p.SyncEnabled, incrementalEnabled = HasAppendLog(p) || HasTimeSource(p) }));
  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.FieldRules is { Length: > 0 } || profile.Preflight?.SourceGeneration > 0)
  93. return Conflict(new { message = "此来源使用数据库同步入口,以保留原值、来源版本和隔离证据" });
  94. return Ok(await ReadRelationalTrial(profile, dataset, runtime, binding, deadline.Token));
  95. }
  96. catch (ConnectorContractException error)
  97. {
  98. if (probeOnly && error.Code is ConnectorError.SourceUnavailable or ConnectorError.ScopeMismatch
  99. or ConnectorError.InvalidManifest or ConnectorError.UnsupportedCapability or ConnectorError.UnsupportedVersion)
  100. return Ok(new ConnectorProbeResult(false, error.Code switch
  101. {
  102. ConnectorError.SourceUnavailable => "source-unavailable",
  103. ConnectorError.ScopeMismatch => "database-scope-mismatch",
  104. _ => "driver-configuration-invalid",
  105. }));
  106. return Conflict(new { message = "数据库连接器校验失败", code = error.Code.ToString() });
  107. }
  108. catch (MdpIngestHttpException error)
  109. {
  110. return StatusCode(error.StatusCode, new { message = "统一接收未返回可推进的回执", code = error.Code });
  111. }
  112. catch (OperationCanceledException) when (!token.IsCancellationRequested)
  113. {
  114. return StatusCode(504, new { message = "数据库连接器试跑超时,请核对已有批次" });
  115. }
  116. catch (Exception error) when (error is IOException or JsonException or HttpRequestException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
  117. {
  118. return StatusCode(503, new { message = "请核对试跑配置、只读连接和接收凭据" });
  119. }
  120. });
  121. private async Task CheckConfiguredSourcePreflight(MdpIngestDataset dataset, MdpSource source, Release candidate, CancellationToken token)
  122. {
  123. var scope = new DatasetScope(dataset.TenantId, dataset.FactoryId, "");
  124. var profiles = (await TrialProfiles(scope, dataset.Id, token))
  125. .Where(p => p.SourceId == source.Id && p.SyncEnabled).ToArray();
  126. if (profiles.Length == 0) return;
  127. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
  128. deadline.CancelAfter(TimeSpan.FromSeconds(20));
  129. var binding = new ConnectorBinding(new(dataset.TenantId, dataset.FactoryId, source.Id, dataset.Id,
  130. source.SourceCode, dataset.DatasetKey), candidate.Version, dataset.Revision.ToString(CultureInfo.InvariantCulture));
  131. try
  132. {
  133. foreach (var profile in profiles)
  134. {
  135. var report = await InspectProfile(profile, binding, deadline.Token);
  136. var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
  137. Require(blocked is null, blocked?.Message ?? "来源预检通过");
  138. }
  139. }
  140. catch (Exception error) when (!token.IsCancellationRequested && error is System.Data.Common.DbException or ConnectorContractException or OperationCanceledException)
  141. {
  142. Require(false, "数据库来源预检未通过,请核对连通性、驱动与只读授权");
  143. }
  144. }
  145. private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset,
  146. RelationalConnectorRuntime runtime, ConnectorBinding binding, CancellationToken token)
  147. {
  148. var (address, key) = await LoadRelationalReceiver(db, profile, dataset, token);
  149. var version = binding.SourceSchemaVersion;
  150. string? position = null;
  151. var receipts = new List<MdpIngestReceipt>();
  152. var complete = false;
  153. for (var page = 0; page < RelationalTrialPages; page++)
  154. {
  155. var read = await runtime.ReadAsync(new(position, 2), token);
  156. if (read is null) { complete = true; break; }
  157. var pending = read.Batch.Pending;
  158. var digest = SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new[]
  159. { profile.Id, version, pending.SourcePosition, pending.Id.PayloadSha256 }));
  160. var trialKey = "relational-trial-" + Convert.ToHexString(digest).ToLowerInvariant();
  161. var batch = ConnectorFrozenBatch.Capture(binding, new(trialKey, trialKey, read.Batch.Payload,
  162. pending.SourcePosition, pending.NextCheckpoint, read.HasMore));
  163. var receipt = await SubmitRelationalTrial(address, dataset.DatasetKey, batch, key, token);
  164. if (receipt.BatchId == Guid.Empty || receipt.SchemaVersion != version || receipt.ReceiveStatus != "accepted"
  165. || receipt.AcceptedRecordCount <= 0)
  166. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  167. var decision = ConnectorResume.Decide(binding, batch.Pending,
  168. new(batch.Pending.Id, ConnectorConfirmation.CloudDurable, receipt.BatchId), batch);
  169. if (decision.Action != ConnectorResumeAction.Advance)
  170. throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  171. position = decision.NextCheckpoint;
  172. receipts.Add(receipt);
  173. if (!read.HasMore) { complete = true; break; }
  174. }
  175. return new { profile.Driver, position, complete, receipts };
  176. }
  177. }