| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
- using System.Globalization;
- using System.Net;
- using System.Net.Http.Json;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
- using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed partial class MdpIngestDatasetController
- {
- private const int RelationalTrialPages = 5;
- private async Task<RelationalTrialProfile[]> TrialProfiles(DatasetScope scope, long id, CancellationToken token) =>
- (await ReadProfiles(Settings["MDP_RELATIONAL_TRIALS_FILE"], token)).Where(profile =>
- profile.TenantId == scope.TenantId && profile.FactoryId == scope.FactoryId && profile.DatasetId == id).ToArray();
- [HttpGet("{id:long}/relational-trials")]
- public Task<IActionResult> ListRelationalTrials(long id, long? factoryId, CancellationToken token) =>
- WithScope(factoryId, async scope =>
- {
- if (!await Datasets(scope).AnyAsync(d => d.Id == id)) return NotFound();
- if (!await Can(TrialPermission)) return Ok(Array.Empty<object>());
- try
- {
- return Ok((await TrialProfiles(scope, id, token)).Select(p => new { p.Id, p.Name, p.Driver }));
- }
- catch (Exception error) when (error is IOException or JsonException or UnauthorizedAccessException)
- {
- return StatusCode(503, new { message = "数据库连接器试跑配置无法读取" });
- }
- });
- [HttpGet("{id:long}/relational-trials/{profileId}/probe")]
- public Task<IActionResult> ProbeRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
- ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: true, token);
- [HttpGet("{id:long}/relational-trials/{profileId}/catalog")]
- public Task<IActionResult> InspectRelationalTrial(long id, string profileId, long? factoryId, string? objectName, CancellationToken token) =>
- WithScope(factoryId, async scope =>
- {
- if (!await Can(TrialPermission)) return Forbid();
- var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
- if (dataset is null) return NotFound();
- try
- {
- var profile = (await TrialProfiles(scope, id, token)).SingleOrDefault(p => p.Id == profileId);
- if (profile is null) return NotFound();
- var source = await BoundSource(dataset, profile.SourceId);
- if (source is null) return NotFound();
- var binding = new ConnectorBinding(new(scope.TenantId, scope.FactoryId, source.Id, id,
- source.SourceCode, dataset.DatasetKey), dataset.ActiveSchemaVersion ?? "draft",
- dataset.Revision.ToString(CultureInfo.InvariantCulture));
- using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
- deadline.CancelAfter(TimeSpan.FromSeconds(20));
- var report = await InspectProfile(profile, binding, deadline.Token, objectName);
- return Ok(new { dataset.Revision, report, canMeasureCapacity = string.IsNullOrWhiteSpace(objectName) || string.Equals(objectName, profile.Table, StringComparison.Ordinal) });
- }
- catch (OperationCanceledException) when (!token.IsCancellationRequested)
- {
- return StatusCode(504, new { message = "来源预检超时" });
- }
- catch (Exception error) when (error is ConnectorContractException or System.Data.Common.DbException or
- IOException or JsonException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
- {
- return StatusCode(503, new { message = "请核对来源配置、连通性或只读授权" });
- }
- });
- [HttpPost("{id:long}/relational-trials/{profileId}")]
- public Task<IActionResult> RunRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
- ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: false, token);
- private Task<IActionResult> ExecuteRelationalTrial(long id, string profileId, long? factoryId, bool probeOnly,
- CancellationToken token) =>
- WithScope(factoryId, async scope =>
- {
- if (!await Can(TrialPermission)) return Forbid();
- var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
- if (dataset is null) return NotFound();
- try
- {
- var profile = (await TrialProfiles(scope, id, token)).SingleOrDefault(p => p.Id == profileId);
- if (profile is null) return NotFound();
- var source = await BoundSource(dataset, profile.SourceId);
- if (source is null || !dataset.Enabled || dataset.ActiveSchemaVersion is null || await Lifecycle(id) != "ACTIVE")
- return Conflict(new { message = "请先启用已绑定来源的采购接收版本" });
- using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
- deadline.CancelAfter(TimeSpan.FromSeconds(25));
- var (runtime, binding, _) = await CreateRelationalTrial(db, profile, dataset, source);
- var probe = await runtime.ProbeAsync(deadline.Token);
- if (probeOnly) return Ok(probe);
- if (!probe.Supported)
- return Conflict(new { message = "数据库读取能力未通过检查", code = "UnsupportedCapability", probe.Reason });
- if (profile.Preflight is not null || profile.SyncEnabled)
- {
- var report = await InspectProfile(profile, binding, deadline.Token);
- var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
- if (blocked is not null)
- return Conflict(new { message = blocked.Message, code = blocked.Code });
- }
- return Ok(await ReadRelationalTrial(profile, dataset, runtime, binding, deadline.Token));
- }
- catch (ConnectorContractException error)
- {
- if (probeOnly && error.Code is ConnectorError.SourceUnavailable or ConnectorError.ScopeMismatch
- or ConnectorError.InvalidManifest or ConnectorError.UnsupportedCapability or ConnectorError.UnsupportedVersion)
- return Ok(new ConnectorProbeResult(false, error.Code switch
- {
- ConnectorError.SourceUnavailable => "source-unavailable",
- ConnectorError.ScopeMismatch => "database-scope-mismatch",
- _ => "driver-configuration-invalid",
- }));
- return Conflict(new { message = "数据库连接器校验失败", code = error.Code.ToString() });
- }
- catch (MdpIngestHttpException error)
- {
- return StatusCode(error.StatusCode, new { message = "统一接收未返回可推进的回执", code = error.Code });
- }
- catch (OperationCanceledException) when (!token.IsCancellationRequested)
- {
- return StatusCode(504, new { message = "数据库连接器试跑超时,请核对已有批次" });
- }
- catch (Exception error) when (error is IOException or JsonException or HttpRequestException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
- {
- return StatusCode(503, new { message = "请核对试跑配置、只读连接和接收凭据" });
- }
- });
- private async Task CheckConfiguredSourcePreflight(MdpIngestDataset dataset, MdpSource source, Release candidate, CancellationToken token)
- {
- var scope = new DatasetScope(dataset.TenantId, dataset.FactoryId, "");
- var profiles = (await TrialProfiles(scope, dataset.Id, token))
- .Where(p => p.SourceId == source.Id && (p.SyncEnabled || p.Preflight is not null)).ToArray();
- if (profiles.Length == 0) return;
- using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
- deadline.CancelAfter(TimeSpan.FromSeconds(20));
- var binding = new ConnectorBinding(new(dataset.TenantId, dataset.FactoryId, source.Id, dataset.Id,
- source.SourceCode, dataset.DatasetKey), candidate.Version, dataset.Revision.ToString(CultureInfo.InvariantCulture));
- try
- {
- foreach (var profile in profiles)
- {
- var report = await InspectProfile(profile, binding, deadline.Token);
- var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
- Require(blocked is null, blocked?.Message ?? "来源预检通过");
- }
- }
- catch (Exception error) when (!token.IsCancellationRequested && error is System.Data.Common.DbException or ConnectorContractException or OperationCanceledException)
- {
- Require(false, "数据库来源预检未通过,请核对连通性、驱动与只读授权");
- }
- }
- private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset,
- RelationalConnectorRuntime runtime, ConnectorBinding binding, CancellationToken token)
- {
- var (address, key) = await LoadRelationalReceiver(db, profile, dataset, token);
- var version = binding.SourceSchemaVersion;
- string? position = null;
- var receipts = new List<MdpIngestReceipt>();
- var complete = false;
- for (var page = 0; page < RelationalTrialPages; page++)
- {
- var read = await runtime.ReadAsync(new(position, 2), token);
- if (read is null) { complete = true; break; }
- var pending = read.Batch.Pending;
- var digest = SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new[]
- { profile.Id, version, pending.SourcePosition, pending.Id.PayloadSha256 }));
- var trialKey = "relational-trial-" + Convert.ToHexString(digest).ToLowerInvariant();
- var batch = ConnectorFrozenBatch.Capture(binding, new(trialKey, trialKey, read.Batch.Payload,
- pending.SourcePosition, pending.NextCheckpoint, read.HasMore));
- var receipt = await SubmitRelationalTrial(address, dataset.DatasetKey, batch, key, token);
- if (receipt.BatchId == Guid.Empty || receipt.SchemaVersion != version || receipt.ReceiveStatus != "accepted"
- || receipt.AcceptedRecordCount <= 0)
- throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
- var decision = ConnectorResume.Decide(binding, batch.Pending,
- new(batch.Pending.Id, ConnectorConfirmation.CloudDurable, receipt.BatchId), batch);
- if (decision.Action != ConnectorResumeAction.Advance)
- throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
- position = decision.NextCheckpoint;
- receipts.Add(receipt);
- if (!read.HasMore) { complete = true; break; }
- }
- return new { profile.Driver, position, complete, receipts };
- }
- }
|