MdpRelationalSource.cs 9.4 KB

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