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; internal 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, string? OdbcFamily, RelationalPreflightOptions? Preflight, bool SyncEnabled = false, int SyncPageSize = 100); internal sealed record RelationalTrialKey(string AccessKey, string Secret); internal static class MdpRelationalSource { internal static readonly JsonSerializerOptions RelationalTrialJson = new(JsonSerializerDefaults.Web); internal static readonly HttpClient RelationalTrialHttp = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }); internal static async Task ReadProfiles(string? path, CancellationToken token) { if (string.IsNullOrWhiteSpace(path)) return []; using var file = File.OpenRead(path); return await JsonSerializer.DeserializeAsync(file, RelationalTrialJson, token) ?? []; } internal static async Task<(RelationalConnectorRuntime Runtime, ConnectorBinding Binding, PurchaseVersionConfiguration Configuration)> CreateRelationalTrial( ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, MdpSource source) { 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 = TrialExecution(profile, binding); var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.SdkVersion, dataset.DatasetKey, version, [ConnectorManifest.CloudDirect], new(profile.Id), new Dictionary { [ConnectorManifest.Database] = new("primary-key", Full: true) }, new("configured-trial", "trial", [])); return (new RelationalConnectorRuntime([TrialDriver(profile, execution)], manifest, execution, schemas), binding, schemas); } internal static ConnectorExecution TrialExecution(RelationalTrialProfile profile, ConnectorBinding binding) => new(binding, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database); internal static IRelationalSourceDriver TrialDriver(RelationalTrialProfile profile, ConnectorExecution execution) { var sourceMapping = new RelationalSourceMapping(execution, profile.Id, profile.Database, profile.Schema, profile.Table, profile.PositionColumn, profile.Columns) { IncludeFactoryInEnvelope = true }; Task Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(profile.ConnectionString); return profile.Driver == OdbcRelationalDriver.Id ? new OdbcRelationalDriver(sourceMapping, profile.OdbcFamily ?? "", Resolve) : new NativeRelationalDriver(sourceMapping, Resolve); } internal static async Task InspectProfile(RelationalTrialProfile profile, ConnectorBinding binding, CancellationToken token, string? objectName = null) { var execution = TrialExecution(profile, binding); var driver = TrialDriver(profile, execution); await using var session = await driver.OpenReadOnlyAsync(execution, profile.Id, token); if (session is not IRelationalSourceInspection inspection) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); return await inspection.InspectAsync(profile.Preflight ?? new(null, null, "unsupported", null, "full", null), token, objectName); } internal static async Task<(Uri Address, RelationalTrialKey Key)> LoadRelationalReceiver( ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, 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."); using var credFile = System.IO.File.OpenRead(profile.CredentialFile); var key = await JsonSerializer.DeserializeAsync(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"); return (address, key); } internal static async Task 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(RelationalTrialJson, token) ?? throw new MdpIngestHttpException(502, "INVALID_RECEIPT"); } }