MdpRelationalSource.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. using System.Globalization;
  2. using System.Net;
  3. using System.Net.Http.Json;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Text.Json;
  7. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  8. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  9. using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
  10. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  11. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  12. internal sealed record RelationalTrialProfile(string Id, string Name, long TenantId, long FactoryId, long DatasetId,
  13. long SourceId, string Driver, string ConnectionString, string Database, string Schema, string Table,
  14. string PositionColumn, string[] Columns, string CredentialFile, string ReceiverBase, string? OdbcFamily,
  15. RelationalPreflightOptions? Preflight, bool SyncEnabled = false, int SyncPageSize = 100);
  16. internal sealed record RelationalTrialKey(string AccessKey, string Secret);
  17. internal static class MdpRelationalSource
  18. {
  19. internal static readonly JsonSerializerOptions RelationalTrialJson = new(JsonSerializerDefaults.Web);
  20. internal static readonly HttpClient RelationalTrialHttp = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false });
  21. internal static async Task<RelationalTrialProfile[]> ReadProfiles(string? path, CancellationToken token)
  22. {
  23. if (string.IsNullOrWhiteSpace(path)) return [];
  24. using var file = File.OpenRead(path);
  25. return await JsonSerializer.DeserializeAsync<RelationalTrialProfile[]>(file, RelationalTrialJson, token) ?? [];
  26. }
  27. internal static async Task<(RelationalConnectorRuntime Runtime, ConnectorBinding Binding, PurchaseVersionConfiguration Configuration)> CreateRelationalTrial(
  28. ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, MdpSource source)
  29. {
  30. var version = dataset.ActiveSchemaVersion!;
  31. var registry = new MdpIngestDatasetRegistry(db);
  32. var active = await registry.ResolveActiveBindingAsync(profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey);
  33. if (active is null || active.DatasetId != dataset.Id || active.SourceSchemaVersion != version)
  34. throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
  35. var mapping = await registry.ReadPublishedMapping(active) ?? throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
  36. var schemas = new PurchaseVersionConfiguration(dataset.DatasetKey, version, mapping);
  37. var contract = schemas.Find(dataset.DatasetKey, version)!;
  38. var binding = new ConnectorBinding(new(profile.TenantId, profile.FactoryId, source.Id, dataset.Id,
  39. source.SourceCode, dataset.DatasetKey), version, contract.ConfigVersion);
  40. var execution = TrialExecution(profile, binding);
  41. var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, profile.Driver, NativeRelationalDriver.Version,
  42. ConnectorManifest.SdkVersion, dataset.DatasetKey, version, [ConnectorManifest.CloudDirect], new(profile.Id),
  43. new Dictionary<string, ConnectorCapability> { [ConnectorManifest.Database] = new("primary-key", Full: true) },
  44. new("configured-trial", "trial", []));
  45. return (new RelationalConnectorRuntime([TrialDriver(profile, execution)], manifest, execution, schemas), binding, schemas);
  46. }
  47. internal static ConnectorExecution TrialExecution(RelationalTrialProfile profile, ConnectorBinding binding) =>
  48. new(binding, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database);
  49. internal static IRelationalSourceDriver TrialDriver(RelationalTrialProfile profile, ConnectorExecution execution)
  50. {
  51. var sourceMapping = new RelationalSourceMapping(execution, profile.Id, profile.Database, profile.Schema, profile.Table,
  52. profile.PositionColumn, profile.Columns)
  53. { IncludeFactoryInEnvelope = true };
  54. Task<string> Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(profile.ConnectionString);
  55. return profile.Driver == OdbcRelationalDriver.Id
  56. ? new OdbcRelationalDriver(sourceMapping, profile.OdbcFamily ?? "", Resolve)
  57. : new NativeRelationalDriver(sourceMapping, Resolve);
  58. }
  59. internal static async Task<RelationalInspection> InspectProfile(RelationalTrialProfile profile, ConnectorBinding binding, CancellationToken token, string? objectName = null)
  60. {
  61. var execution = TrialExecution(profile, binding);
  62. var driver = TrialDriver(profile, execution);
  63. await using var session = await driver.OpenReadOnlyAsync(execution, profile.Id, token);
  64. if (session is not IRelationalSourceInspection inspection)
  65. throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
  66. return await inspection.InspectAsync(profile.Preflight ?? new(null, null, "unsupported", null, "full", null), token, objectName);
  67. }
  68. internal static async Task<(Uri Address, RelationalTrialKey Key)> LoadRelationalReceiver(
  69. ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, CancellationToken token)
  70. {
  71. if (!Uri.TryCreate(profile.ReceiverBase, UriKind.Absolute, out var address)
  72. || !IPAddress.TryParse(address.Host, out var ip) || !IPAddress.IsLoopback(ip)
  73. || address.Scheme is not ("http" or "https") || !string.IsNullOrEmpty(address.UserInfo)
  74. || address.AbsolutePath != "/" || !string.IsNullOrEmpty(address.Query) || !string.IsNullOrEmpty(address.Fragment))
  75. throw new ArgumentException("Receipt host must be a loopback origin.");
  76. using var credFile = System.IO.File.OpenRead(profile.CredentialFile);
  77. var key = await JsonSerializer.DeserializeAsync<RelationalTrialKey>(credFile, RelationalTrialJson, token)
  78. ?? throw new ArgumentException("Missing receipt credentials.");
  79. var hash = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(key.AccessKey))).ToLowerInvariant();
  80. var authorized = await db.Ado.GetIntAsync("""
  81. SELECT COUNT(*) FROM mdp_ingest_access_grant
  82. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
  83. AND dataset_key=@DatasetKey AND access_key_hash=@hash AND use_batch_factory=1 AND enabled=1
  84. """, new { profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey, hash });
  85. if (authorized != 1) throw new MdpIngestHttpException(409, "TRIAL_GRANT_MISMATCH");
  86. return (address, key);
  87. }
  88. internal static async Task<MdpIngestReceipt> SubmitRelationalTrial(Uri address, string datasetKey,
  89. ConnectorFrozenBatch batch, RelationalTrialKey key, CancellationToken token)
  90. {
  91. var endpoint = new Uri(address, "/api/v1/ingest/" + Uri.EscapeDataString(datasetKey));
  92. var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
  93. var nonce = Guid.NewGuid().ToString("N");
  94. var id = batch.Pending.Id;
  95. var canonical = string.Join('&', "POST", endpoint.AbsolutePath, key.AccessKey, timestamp, nonce, id.PayloadSha256, id.IdempotencyKey);
  96. var bytes = Convert.FromBase64String(key.Secret);
  97. string signature;
  98. try { signature = Convert.ToBase64String(HMACSHA256.HashData(bytes, Encoding.UTF8.GetBytes(canonical))); }
  99. finally { CryptographicOperations.ZeroMemory(bytes); }
  100. using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(batch.Payload.ToArray()) };
  101. request.Content.Headers.ContentType = new("application/json");
  102. request.Headers.Add("X-Access-Key", key.AccessKey);
  103. request.Headers.Add("X-Timestamp", timestamp);
  104. request.Headers.Add("X-Nonce", nonce);
  105. request.Headers.Add("X-Signature", signature);
  106. request.Headers.Add("X-Content-SHA256", id.PayloadSha256);
  107. request.Headers.Add("Idempotency-Key", id.IdempotencyKey);
  108. using var response = await RelationalTrialHttp.SendAsync(request, token);
  109. if (response.StatusCode != HttpStatusCode.Accepted)
  110. throw new MdpIngestHttpException(response.IsSuccessStatusCode ? 502 : (int)response.StatusCode, "INGEST_NOT_CONFIRMED");
  111. return await response.Content.ReadFromJsonAsync<MdpIngestReceipt>(RelationalTrialJson, token)
  112. ?? throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
  113. }
  114. }