|
|
@@ -1,3 +1,4 @@
|
|
|
+using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
|
|
|
using System.Globalization;
|
|
|
using System.Net;
|
|
|
using System.Net.Http.Json;
|
|
|
@@ -13,23 +14,11 @@ namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
|
|
|
|
|
|
public sealed partial class MdpIngestDatasetController
|
|
|
{
|
|
|
- private sealed record RelationalTrialProfile(string Id, string Name, long TenantId, long FactoryId, long DatasetId,
|
|
|
- long SourceId, string Driver, string ConnectionString, string Database, string Schema, string Table,
|
|
|
- string PositionColumn, string[] Columns, string CredentialFile, string ReceiverBase);
|
|
|
- private sealed record RelationalTrialKey(string AccessKey, string Secret);
|
|
|
- private static readonly JsonSerializerOptions RelationalTrialJson = new(JsonSerializerDefaults.Web);
|
|
|
- private static readonly HttpClient RelationalTrialHttp = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false });
|
|
|
private const int RelationalTrialPages = 5;
|
|
|
|
|
|
- private async Task<RelationalTrialProfile[]> TrialProfiles(DatasetScope scope, long id, CancellationToken token)
|
|
|
- {
|
|
|
- var path = Settings["MDP_RELATIONAL_TRIALS_FILE"];
|
|
|
- if (string.IsNullOrWhiteSpace(path)) return [];
|
|
|
- using var file = System.IO.File.OpenRead(path);
|
|
|
- var profiles = await JsonSerializer.DeserializeAsync<RelationalTrialProfile[]>(file, RelationalTrialJson, token) ?? [];
|
|
|
- return profiles.Where(profile => profile.TenantId == scope.TenantId && profile.FactoryId == scope.FactoryId
|
|
|
- && profile.DatasetId == id).ToArray();
|
|
|
- }
|
|
|
+ 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) =>
|
|
|
@@ -47,8 +36,48 @@ public sealed partial class MdpIngestDatasetController
|
|
|
}
|
|
|
});
|
|
|
|
|
|
+ [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();
|
|
|
@@ -63,10 +92,30 @@ public sealed partial class MdpIngestDatasetController
|
|
|
return Conflict(new { message = "请先启用已绑定来源的采购接收版本" });
|
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(25));
|
|
|
- return Ok(await ReadRelationalTrial(profile, dataset, source, deadline.Token));
|
|
|
+ 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)
|
|
|
@@ -83,45 +132,36 @@ public sealed partial class MdpIngestDatasetController
|
|
|
}
|
|
|
});
|
|
|
|
|
|
- private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset, MdpSource source, CancellationToken token)
|
|
|
+ private async Task CheckConfiguredSourcePreflight(MdpIngestDataset dataset, MdpSource source, Release candidate, CancellationToken token)
|
|
|
{
|
|
|
- if (!Uri.TryCreate(profile.ReceiverBase, UriKind.Absolute, out var address)
|
|
|
- || !IPAddress.TryParse(address.Host, out var ip) || !IPAddress.IsLoopback(ip)
|
|
|
- || address.Scheme is not ("http" or "https") || !string.IsNullOrEmpty(address.UserInfo)
|
|
|
- || address.AbsolutePath != "/" || !string.IsNullOrEmpty(address.Query) || !string.IsNullOrEmpty(address.Fragment))
|
|
|
- throw new ArgumentException("Receipt host must be a loopback origin.");
|
|
|
- var version = dataset.ActiveSchemaVersion!;
|
|
|
- var registry = new MdpIngestDatasetRegistry(db);
|
|
|
- var active = await registry.ResolveActiveBindingAsync(profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey);
|
|
|
- if (active is null || active.DatasetId != dataset.Id || active.SourceSchemaVersion != version)
|
|
|
- throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
|
|
|
- var mapping = await registry.ReadPublishedMapping(active) ?? throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
|
|
|
- var schemas = new PurchaseVersionConfiguration(dataset.DatasetKey, version, mapping);
|
|
|
- var contract = schemas.Find(dataset.DatasetKey, version)!;
|
|
|
- var binding = new ConnectorBinding(new(profile.TenantId, profile.FactoryId, source.Id, dataset.Id,
|
|
|
- source.SourceCode, dataset.DatasetKey), version, contract.ConfigVersion);
|
|
|
- var execution = new ConnectorExecution(binding, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database);
|
|
|
- var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, profile.Driver, NativeRelationalDriver.Version,
|
|
|
- ConnectorManifest.SdkVersion, dataset.DatasetKey, version, [ConnectorManifest.CloudDirect], new(profile.Id),
|
|
|
- new Dictionary<string, ConnectorCapability> { [ConnectorManifest.Database] = new("primary-key", Full: true) },
|
|
|
- new("configured-trial", "trial", []));
|
|
|
- var sourceMapping = new RelationalSourceMapping(execution, profile.Id, profile.Database, profile.Schema, profile.Table,
|
|
|
- profile.PositionColumn, profile.Columns) { IncludeFactoryInEnvelope = true };
|
|
|
- var driver = new NativeRelationalDriver(sourceMapping, (_, _, _) => Task.FromResult(profile.ConnectionString));
|
|
|
- var runtime = new RelationalConnectorRuntime([driver], manifest, execution, schemas);
|
|
|
- var probe = await runtime.ProbeAsync(token);
|
|
|
- if (!probe.Supported) throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
|
|
|
+ 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, "数据库来源预检未通过,请核对连通性、驱动与只读授权");
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- using var credFile = System.IO.File.OpenRead(profile.CredentialFile);
|
|
|
- var key = await JsonSerializer.DeserializeAsync<RelationalTrialKey>(credFile, RelationalTrialJson, token)
|
|
|
- ?? throw new ArgumentException("Missing receipt credentials.");
|
|
|
- var hash = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(key.AccessKey))).ToLowerInvariant();
|
|
|
- var authorized = await db.Ado.GetIntAsync("""
|
|
|
- SELECT COUNT(*) FROM mdp_ingest_access_grant
|
|
|
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
|
|
|
- AND dataset_key=@DatasetKey AND access_key_hash=@hash AND use_batch_factory=1 AND enabled=1
|
|
|
- """, new { profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey, hash });
|
|
|
- if (authorized != 1) throw new MdpIngestHttpException(409, "TRIAL_GRANT_MISMATCH");
|
|
|
+ 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;
|
|
|
@@ -150,30 +190,4 @@ public sealed partial class MdpIngestDatasetController
|
|
|
return new { profile.Driver, position, complete, receipts };
|
|
|
}
|
|
|
|
|
|
- private static async Task<MdpIngestReceipt> SubmitRelationalTrial(Uri address, string datasetKey,
|
|
|
- ConnectorFrozenBatch batch, RelationalTrialKey key, CancellationToken token)
|
|
|
- {
|
|
|
- var endpoint = new Uri(address, "/api/v1/ingest/" + Uri.EscapeDataString(datasetKey));
|
|
|
- var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
|
|
|
- var nonce = Guid.NewGuid().ToString("N");
|
|
|
- var id = batch.Pending.Id;
|
|
|
- var canonical = string.Join('&', "POST", endpoint.AbsolutePath, key.AccessKey, timestamp, nonce, id.PayloadSha256, id.IdempotencyKey);
|
|
|
- var bytes = Convert.FromBase64String(key.Secret);
|
|
|
- string signature;
|
|
|
- try { signature = Convert.ToBase64String(HMACSHA256.HashData(bytes, Encoding.UTF8.GetBytes(canonical))); }
|
|
|
- finally { CryptographicOperations.ZeroMemory(bytes); }
|
|
|
- using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(batch.Payload.ToArray()) };
|
|
|
- request.Content.Headers.ContentType = new("application/json");
|
|
|
- request.Headers.Add("X-Access-Key", key.AccessKey);
|
|
|
- request.Headers.Add("X-Timestamp", timestamp);
|
|
|
- request.Headers.Add("X-Nonce", nonce);
|
|
|
- request.Headers.Add("X-Signature", signature);
|
|
|
- request.Headers.Add("X-Content-SHA256", id.PayloadSha256);
|
|
|
- request.Headers.Add("Idempotency-Key", id.IdempotencyKey);
|
|
|
- using var response = await RelationalTrialHttp.SendAsync(request, token);
|
|
|
- if (response.StatusCode != HttpStatusCode.Accepted)
|
|
|
- throw new MdpIngestHttpException(response.IsSuccessStatusCode ? 502 : (int)response.StatusCode, "INGEST_NOT_CONFIRMED");
|
|
|
- return await response.Content.ReadFromJsonAsync<MdpIngestReceipt>(RelationalTrialJson, token)
|
|
|
- ?? throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
|
|
|
- }
|
|
|
}
|