MdpApiPullService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using System.Globalization;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using System.Text.Json;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  6. using Microsoft.Extensions.Configuration;
  7. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  8. public sealed partial class MdpApiPullService(ISqlSugarClient host, MdpApiPullClient client, MdpApiPullEgress egress, IConfiguration configuration)
  9. {
  10. private static readonly JsonSerializerOptions Wire = new(JsonSerializerDefaults.Web);
  11. private const string Profiles = """
  12. SELECT id AS Id, tenant_id AS TenantId, factory_id AS FactoryId, source_id AS SourceId, dataset_id AS DatasetId,
  13. schema_version AS SchemaVersion, release_id AS ReleaseId, plan_json AS PlanJson, state AS State,
  14. created_by AS CreatedBy, preview_json AS PreviewJson
  15. FROM mdp_connector_api_pull_profile
  16. """;
  17. public async Task<IReadOnlyList<MdpApiPullProfileInfo>> ListProfilesAsync(long tenant, long factory, long dataset)
  18. {
  19. using var db = MdpIngestDatabase.Open(host);
  20. return (await db.Ado.SqlQueryAsync<Profile>(Profiles + " " + """
  21. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset ORDER BY id DESC LIMIT 50
  22. """, new { tenant, factory, dataset })).Select(ProfileInfo).ToArray();
  23. }
  24. public async Task<string> CreateAsync(long tenant, long factory, long dataset, long source, long actor, MdpApiPullPlan input,
  25. CancellationToken cancellationToken)
  26. {
  27. input.Validate();
  28. egress.Target(tenant, source, input.Endpoint);
  29. if (input.Auth == "oauth2") egress.Target(tenant, source, new Uri(input.TokenUrl!));
  30. using var db = MdpIngestDatabase.Open(host);
  31. var id = await Tx(db, async () =>
  32. {
  33. var bound = await BoundAsync(db, tenant, factory, dataset, source);
  34. await db.Ado.ExecuteCommandAsync("""
  35. INSERT INTO mdp_connector_api_pull_profile
  36. (tenant_id,factory_id,dataset_id,source_id,schema_version,release_id,plan_json,created_by,poll_seconds)
  37. VALUES (@tenant,@factory,@dataset,@source,@Version,@ReleaseId,@Json,@actor,@PollSeconds)
  38. """, new { tenant, factory, dataset, source, bound.Version, bound.ReleaseId, Json = JsonSerializer.Serialize(input, Wire), actor, input.PollSeconds });
  39. cancellationToken.ThrowIfCancellationRequested();
  40. return await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
  41. });
  42. return id.ToString(CultureInfo.InvariantCulture);
  43. }
  44. public async Task<MdpApiPullPreview> PreflightAsync(long tenant, long factory, long dataset, long id, long actor, CancellationToken cancellationToken)
  45. {
  46. using var db = MdpIngestDatabase.Open(host);
  47. var profile = await ReadProfile(db, tenant, factory, dataset, id);
  48. Require(profile.State is "DRAFT" or "PREFLIGHT", "PULL_PROFILE_STATE");
  49. var bound = await BoundAsync(db, tenant, factory, dataset, profile.SourceId, profile, lockDataset: false);
  50. var plan = Plan(profile);
  51. var initial = plan.Begin(DateTimeOffset.UtcNow, null);
  52. var response = await FetchAsync(tenant, profile.SourceId, plan, initial, cancellationToken);
  53. if (response.LinkDiagnostic is { } diagnostic) throw new MdpApiPullException(diagnostic);
  54. var prepared = await PrepareAsync(db, profile, bound, plan, response.Body);
  55. using var json = JsonDocument.Parse(response.Body);
  56. var next = plan.Next(initial, json.RootElement, prepared.Events.Count, response.Effective, response.NextLink);
  57. var processed = prepared.Events.Count == 0 ? null : PurchaseBatchProcessor.Process(prepared, "");
  58. var preview = new MdpApiPullPreview(profile.SchemaVersion, prepared.Events.Count, processed?.Package.Items.Count ?? 0,
  59. processed?.Quarantines.Select(row => row.RawEventId).Distinct().Count() ?? 0,
  60. processed?.Package.Items.Sum(line => line.OrderQty) ?? 0, next is not null, prepared.Batch.PayloadSha256);
  61. var changed = await db.Ado.ExecuteCommandAsync("""
  62. UPDATE mdp_connector_api_pull_profile SET state='PREFLIGHT',checked_by=@actor,preview_json=@Preview,
  63. changed_at=UTC_TIMESTAMP(6)
  64. WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND state IN ('DRAFT','PREFLIGHT')
  65. """, new { id, tenant, factory, dataset, actor, Preview = JsonSerializer.Serialize(preview, Wire) });
  66. Require(changed == 1, "PULL_PROFILE_STATE");
  67. return preview;
  68. }
  69. public async Task ActivateAsync(long tenant, long factory, long dataset, long id, long actor, CancellationToken token)
  70. {
  71. using var db = MdpIngestDatabase.Open(host);
  72. await Tx(db, async () =>
  73. {
  74. var profile = await ReadProfile(db, tenant, factory, dataset, id);
  75. var bound = await BoundAsync(db, tenant, factory, dataset, profile.SourceId, profile);
  76. profile = await ReadProfile(db, tenant, factory, dataset, id, true);
  77. Require((profile.State is "PREFLIGHT" or "PAUSED") && profile.CreatedBy != actor
  78. && profile.PreviewJson is not null
  79. && JsonSerializer.Deserialize<MdpApiPullPreview>(profile.PreviewJson, Wire) is { Valid: > 0 },
  80. "PULL_INDEPENDENT_APPROVAL_REQUIRED");
  81. await RequireWriterAsync(db, profile, bound);
  82. var busy = await db.Ado.GetIntAsync("""
  83. SELECT COUNT(*) FROM mdp_connector_api_pull_run WHERE tenant_id=@tenant AND factory_id=@factory
  84. AND dataset_id=@dataset AND source_id=@SourceId AND active_slot=1
  85. """, new { tenant, factory, dataset, profile.SourceId });
  86. Require(busy == 0, "PULL_ACTIVE_RUN");
  87. await db.Ado.ExecuteCommandAsync("""
  88. UPDATE mdp_connector_api_pull_profile SET state='PAUSED',active_slot=NULL,next_run_at=NULL,changed_at=UTC_TIMESTAMP(6)
  89. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@SourceId AND active_slot=1
  90. """, new { tenant, factory, dataset, profile.SourceId });
  91. await db.Ado.ExecuteCommandAsync("""
  92. UPDATE mdp_connector_api_pull_profile SET state='ACTIVE',active_slot=1,approved_by=@actor,
  93. next_run_at=IF(poll_seconds=0,NULL,TIMESTAMPADD(SECOND,poll_seconds,UTC_TIMESTAMP(6))),changed_at=UTC_TIMESTAMP(6)
  94. WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  95. """, new { id, tenant, factory, dataset, actor });
  96. token.ThrowIfCancellationRequested();
  97. return true;
  98. });
  99. }
  100. public async Task PauseAsync(long tenant, long factory, long dataset, long id)
  101. {
  102. using var db = MdpIngestDatabase.Open(host);
  103. await Tx(db, async () =>
  104. {
  105. var profile = await ReadProfile(db, tenant, factory, dataset, id, true);
  106. Require(profile.State == "ACTIVE", "PULL_PROFILE_STATE");
  107. var pending = await db.Ado.GetIntAsync("""
  108. SELECT COUNT(*) FROM mdp_connector_api_pull_run WHERE profile_id=@id AND tenant_id=@tenant
  109. AND factory_id=@factory AND dataset_id=@dataset AND active_slot=1
  110. """, new { id, tenant, factory, dataset });
  111. Require(pending == 0, "PULL_ACTIVE_RUN");
  112. await db.Ado.ExecuteCommandAsync("""
  113. UPDATE mdp_connector_api_pull_profile SET state='PAUSED',active_slot=NULL,next_run_at=NULL,changed_at=UTC_TIMESTAMP(6)
  114. WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
  115. """, new { id, tenant, factory, dataset });
  116. return true;
  117. });
  118. }
  119. internal static async Task<Profile> ReadProfile(ISqlSugarClient db, long tenant, long factory, long dataset, long id, bool locked = false) =>
  120. await db.Ado.SqlQuerySingleAsync<Profile>(Profiles + " " + """
  121. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND id=@id
  122. """ + (locked ? " FOR UPDATE" : ""), new { tenant, factory, dataset, id })
  123. ?? throw new MdpApiPullException("PULL_PROFILE_NOT_FOUND");
  124. private static async Task<Published> BoundAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source,
  125. Profile? profile = null, bool lockDataset = true)
  126. {
  127. if (lockDataset)
  128. {
  129. var found = await db.Ado.GetLongAsync("""
  130. SELECT id FROM mdp_ingest_dataset WHERE id=@dataset AND tenant_id=@tenant AND factory_id=@factory FOR UPDATE
  131. """, new { tenant, factory, dataset });
  132. Require(found == dataset, "PULL_DATASET_UNAVAILABLE");
  133. }
  134. var current = await db.Ado.SqlQuerySingleAsync<Published>("""
  135. SELECT d.dataset_key AS DatasetKey,p.schema_version AS Version,p.release_id AS ReleaseId,s.source_code AS SourceCode
  136. FROM mdp_ingest_dataset d
  137. JOIN mdp_ingest_dataset_source b ON b.dataset_id=d.id AND b.tenant_id=d.tenant_id
  138. AND b.factory_id=d.factory_id AND b.source_id=@source AND b.enabled=1
  139. JOIN mdp_source s ON s.id=b.source_id AND s.tenant_id=d.tenant_id AND s.status=1 AND s.source_type='API'
  140. JOIN mdp_ingest_lifecycle l ON l.dataset_id=d.id AND l.state='ACTIVE'
  141. JOIN mdp_ingest_published_source p ON p.tenant_id=d.tenant_id AND p.factory_id=d.factory_id
  142. AND p.dataset_id=d.id AND p.source_id=s.id AND p.schema_version=d.active_schema_version
  143. WHERE d.id=@dataset AND d.tenant_id=@tenant AND d.factory_id=@factory AND d.enabled=1
  144. AND EXISTS (SELECT 1 FROM mdp_purchase_active_factory f WHERE f.tenant_id=d.tenant_id AND f.factory_id=d.factory_id)
  145. """, new { tenant, factory, dataset, source })
  146. ?? throw new MdpApiPullException("PULL_DATASET_UNAVAILABLE");
  147. Require(profile is null || profile.ReleaseId == current.ReleaseId && profile.SchemaVersion == current.Version, "PULL_RELEASE_CHANGED");
  148. return current;
  149. }
  150. private async Task RequireWriterAsync(ISqlSugarClient db, Profile profile, Published bound)
  151. {
  152. await MdpEdgeRoute.RequireDirectAsync(db, configuration, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
  153. var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
  154. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  155. if (migration is null)
  156. {
  157. var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(profile.TenantId, "PURCHASE");
  158. Require(string.Equals(authority?.SourceSystem, bound.SourceCode, StringComparison.OrdinalIgnoreCase), "PULL_SOURCE_NOT_AUTHORIZED");
  159. }
  160. else Require(migration.NewSourceCode == bound.SourceCode, "PULL_SOURCE_NOT_AUTHORIZED");
  161. }
  162. private static async Task<PreparedIngestBatch> PrepareAsync(ISqlSugarClient db, Profile profile, Published bound,
  163. MdpApiPullPlan plan, byte[] body)
  164. {
  165. var preparer = await PagePreparerAsync(db, profile, bound);
  166. var prepared = preparer.PrepareApiPage(PageIdentity(profile, bound), bound.Version, body, MdpIngestProtocol.Limits,
  167. MdpApiPullPlan.Path(plan.ResponsePath), PurchaseApiWindow);
  168. Require(MdpBatchFactory.RowsMatch(prepared), "PULL_BATCH_SCOPE_INVALID");
  169. return prepared;
  170. }
  171. private static readonly IngestSourceWindow PurchaseApiWindow = new(null, null, IngestSourceWindow.PurchaseApiTime);
  172. private static IngestDatasetIdentity PageIdentity(Profile profile, Published bound) =>
  173. new(profile.TenantId, profile.FactoryId, profile.SourceId, profile.DatasetId, bound.SourceCode, bound.DatasetKey);
  174. private static async Task<IngestBatchPreparer> PagePreparerAsync(ISqlSugarClient db, Profile profile, Published bound)
  175. {
  176. var binder = new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db));
  177. var (registry, _) = await binder.ReadContractAsync(new MdpIngestActiveBinding
  178. {
  179. TenantId = profile.TenantId, FactoryId = profile.FactoryId, DatasetId = profile.DatasetId, SourceId = profile.SourceId,
  180. SourceCode = bound.SourceCode, DatasetKey = bound.DatasetKey, SourceSchemaVersion = bound.Version
  181. });
  182. return new IngestBatchPreparer(registry);
  183. }
  184. private static MdpApiPullPlan Plan(Profile profile) => JsonSerializer.Deserialize<MdpApiPullPlan>(profile.PlanJson, Wire)
  185. ?? throw new MdpApiPullException("PULL_CONFIG_INVALID");
  186. private static MdpApiPullProfileInfo ProfileInfo(Profile row) => new(row.Id.ToString(CultureInfo.InvariantCulture),
  187. row.SourceId.ToString(CultureInfo.InvariantCulture), row.SchemaVersion, row.State,
  188. row.PreviewJson is null ? null : JsonSerializer.Deserialize<MdpApiPullPreview>(row.PreviewJson, Wire));
  189. private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
  190. private static async Task<T> Tx<T>(ISqlSugarClient db, Func<Task<T>> body)
  191. {
  192. var result = await db.Ado.UseTranAsync(body);
  193. if (result.IsSuccess) return result.Data;
  194. if (result.ErrorException is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure);
  195. throw new MdpApiPullException("PULL_STORE_UNAVAILABLE");
  196. }
  197. private static void Require(bool condition, string code)
  198. {
  199. if (!condition) throw new MdpApiPullException(code);
  200. }
  201. internal sealed class Profile
  202. {
  203. public long Id { get; set; }
  204. public long TenantId { get; set; }
  205. public long FactoryId { get; set; }
  206. public long DatasetId { get; set; }
  207. public long SourceId { get; set; }
  208. public long ReleaseId { get; set; }
  209. public long CreatedBy { get; set; }
  210. public string PlanJson { get; set; } = "";
  211. public string State { get; set; } = "";
  212. public string SchemaVersion { get; set; } = "";
  213. public string? PreviewJson { get; set; }
  214. }
  215. private sealed class Published
  216. {
  217. public string DatasetKey { get; set; } = "";
  218. public string Version { get; set; } = "";
  219. public string SourceCode { get; set; } = "";
  220. public long ReleaseId { get; set; }
  221. }
  222. }
  223. public sealed record MdpApiPullProfileInfo(string Id, string SourceId, string SchemaVersion, string State, MdpApiPullPreview? Preview);
  224. public sealed record MdpApiPullPreview(string SchemaVersion, int Received, int Valid, int Isolated, decimal Quantity, bool HasNext, string Digest);