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 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 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()); 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 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 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 RunRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) => ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: false, token); private Task 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 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(); 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 }; } }