| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Microsoft.Extensions.Configuration;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed partial class MdpApiPullService(ISqlSugarClient host, MdpApiPullClient client, MdpApiPullEgress egress, IConfiguration configuration)
- {
- private static readonly JsonSerializerOptions Wire = new(JsonSerializerDefaults.Web);
- private const string Profiles = """
- SELECT id AS Id, tenant_id AS TenantId, factory_id AS FactoryId, source_id AS SourceId, dataset_id AS DatasetId,
- schema_version AS SchemaVersion, release_id AS ReleaseId, plan_json AS PlanJson, state AS State,
- created_by AS CreatedBy, preview_json AS PreviewJson
- FROM mdp_connector_api_pull_profile
- """;
- public async Task<IReadOnlyList<MdpApiPullProfileInfo>> ListProfilesAsync(long tenant, long factory, long dataset)
- {
- using var db = MdpIngestDatabase.Open(host);
- return (await db.Ado.SqlQueryAsync<Profile>(Profiles + " " + """
- WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset ORDER BY id DESC LIMIT 50
- """, new { tenant, factory, dataset })).Select(ProfileInfo).ToArray();
- }
- public async Task<string> CreateAsync(long tenant, long factory, long dataset, long source, long actor, MdpApiPullPlan input,
- CancellationToken cancellationToken)
- {
- input.Validate();
- egress.Target(tenant, source, input.Endpoint);
- if (input.Auth == "oauth2") egress.Target(tenant, source, new Uri(input.TokenUrl!));
- using var db = MdpIngestDatabase.Open(host);
- var id = await Tx(db, async () =>
- {
- var bound = await BoundAsync(db, tenant, factory, dataset, source);
- await db.Ado.ExecuteCommandAsync("""
- INSERT INTO mdp_connector_api_pull_profile
- (tenant_id,factory_id,dataset_id,source_id,schema_version,release_id,plan_json,created_by,poll_seconds)
- VALUES (@tenant,@factory,@dataset,@source,@Version,@ReleaseId,@Json,@actor,@PollSeconds)
- """, new { tenant, factory, dataset, source, bound.Version, bound.ReleaseId, Json = JsonSerializer.Serialize(input, Wire), actor, input.PollSeconds });
- cancellationToken.ThrowIfCancellationRequested();
- return await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
- });
- return id.ToString(CultureInfo.InvariantCulture);
- }
- public async Task<MdpApiPullPreview> PreflightAsync(long tenant, long factory, long dataset, long id, long actor, CancellationToken cancellationToken)
- {
- using var db = MdpIngestDatabase.Open(host);
- var profile = await ReadProfile(db, tenant, factory, dataset, id);
- Require(profile.State is "DRAFT" or "PREFLIGHT", "PULL_PROFILE_STATE");
- var bound = await BoundAsync(db, tenant, factory, dataset, profile.SourceId, profile, lockDataset: false);
- var plan = Plan(profile);
- var initial = plan.Begin(DateTimeOffset.UtcNow, null);
- var response = await FetchAsync(tenant, profile.SourceId, plan, initial, cancellationToken);
- if (response.LinkDiagnostic is { } diagnostic) throw new MdpApiPullException(diagnostic);
- var prepared = await PrepareAsync(db, profile, bound, plan, response.Body);
- using var json = JsonDocument.Parse(response.Body);
- var next = plan.Next(initial, json.RootElement, prepared.Events.Count, response.Effective, response.NextLink);
- var processed = prepared.Events.Count == 0 ? null : PurchaseBatchProcessor.Process(prepared, "");
- var preview = new MdpApiPullPreview(profile.SchemaVersion, prepared.Events.Count, processed?.Package.Items.Count ?? 0,
- processed?.Quarantines.Select(row => row.RawEventId).Distinct().Count() ?? 0,
- processed?.Package.Items.Sum(line => line.OrderQty) ?? 0, next is not null, prepared.Batch.PayloadSha256);
- var changed = await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_profile SET state='PREFLIGHT',checked_by=@actor,preview_json=@Preview,
- changed_at=UTC_TIMESTAMP(6)
- WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND state IN ('DRAFT','PREFLIGHT')
- """, new { id, tenant, factory, dataset, actor, Preview = JsonSerializer.Serialize(preview, Wire) });
- Require(changed == 1, "PULL_PROFILE_STATE");
- return preview;
- }
- public async Task ActivateAsync(long tenant, long factory, long dataset, long id, long actor, CancellationToken token)
- {
- using var db = MdpIngestDatabase.Open(host);
- await Tx(db, async () =>
- {
- var profile = await ReadProfile(db, tenant, factory, dataset, id);
- var bound = await BoundAsync(db, tenant, factory, dataset, profile.SourceId, profile);
- profile = await ReadProfile(db, tenant, factory, dataset, id, true);
- Require((profile.State is "PREFLIGHT" or "PAUSED") && profile.CreatedBy != actor
- && profile.PreviewJson is not null
- && JsonSerializer.Deserialize<MdpApiPullPreview>(profile.PreviewJson, Wire) is { Valid: > 0 },
- "PULL_INDEPENDENT_APPROVAL_REQUIRED");
- await RequireWriterAsync(db, profile, bound);
- var busy = await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_connector_api_pull_run WHERE tenant_id=@tenant AND factory_id=@factory
- AND dataset_id=@dataset AND source_id=@SourceId AND active_slot=1
- """, new { tenant, factory, dataset, profile.SourceId });
- Require(busy == 0, "PULL_ACTIVE_RUN");
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_profile SET state='PAUSED',active_slot=NULL,next_run_at=NULL,changed_at=UTC_TIMESTAMP(6)
- WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@SourceId AND active_slot=1
- """, new { tenant, factory, dataset, profile.SourceId });
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_profile SET state='ACTIVE',active_slot=1,approved_by=@actor,
- next_run_at=IF(poll_seconds=0,NULL,TIMESTAMPADD(SECOND,poll_seconds,UTC_TIMESTAMP(6))),changed_at=UTC_TIMESTAMP(6)
- WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
- """, new { id, tenant, factory, dataset, actor });
- token.ThrowIfCancellationRequested();
- return true;
- });
- }
- public async Task PauseAsync(long tenant, long factory, long dataset, long id)
- {
- using var db = MdpIngestDatabase.Open(host);
- await Tx(db, async () =>
- {
- var profile = await ReadProfile(db, tenant, factory, dataset, id, true);
- Require(profile.State == "ACTIVE", "PULL_PROFILE_STATE");
- var pending = await db.Ado.GetIntAsync("""
- SELECT COUNT(*) FROM mdp_connector_api_pull_run WHERE profile_id=@id AND tenant_id=@tenant
- AND factory_id=@factory AND dataset_id=@dataset AND active_slot=1
- """, new { id, tenant, factory, dataset });
- Require(pending == 0, "PULL_ACTIVE_RUN");
- await db.Ado.ExecuteCommandAsync("""
- UPDATE mdp_connector_api_pull_profile SET state='PAUSED',active_slot=NULL,next_run_at=NULL,changed_at=UTC_TIMESTAMP(6)
- WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset
- """, new { id, tenant, factory, dataset });
- return true;
- });
- }
- internal static async Task<Profile> ReadProfile(ISqlSugarClient db, long tenant, long factory, long dataset, long id, bool locked = false) =>
- await db.Ado.SqlQuerySingleAsync<Profile>(Profiles + " " + """
- WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND id=@id
- """ + (locked ? " FOR UPDATE" : ""), new { tenant, factory, dataset, id })
- ?? throw new MdpApiPullException("PULL_PROFILE_NOT_FOUND");
- private static async Task<Published> BoundAsync(ISqlSugarClient db, long tenant, long factory, long dataset, long source,
- Profile? profile = null, bool lockDataset = true)
- {
- if (lockDataset)
- {
- var found = await db.Ado.GetLongAsync("""
- SELECT id FROM mdp_ingest_dataset WHERE id=@dataset AND tenant_id=@tenant AND factory_id=@factory FOR UPDATE
- """, new { tenant, factory, dataset });
- Require(found == dataset, "PULL_DATASET_UNAVAILABLE");
- }
- var current = await db.Ado.SqlQuerySingleAsync<Published>("""
- SELECT d.dataset_key AS DatasetKey,p.schema_version AS Version,p.release_id AS ReleaseId,s.source_code AS SourceCode
- FROM mdp_ingest_dataset d
- JOIN mdp_ingest_dataset_source b ON b.dataset_id=d.id AND b.tenant_id=d.tenant_id
- AND b.factory_id=d.factory_id AND b.source_id=@source AND b.enabled=1
- 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'
- JOIN mdp_ingest_lifecycle l ON l.dataset_id=d.id AND l.state='ACTIVE'
- JOIN mdp_ingest_published_source p ON p.tenant_id=d.tenant_id AND p.factory_id=d.factory_id
- AND p.dataset_id=d.id AND p.source_id=s.id AND p.schema_version=d.active_schema_version
- WHERE d.id=@dataset AND d.tenant_id=@tenant AND d.factory_id=@factory AND d.enabled=1
- AND EXISTS (SELECT 1 FROM mdp_purchase_active_factory f WHERE f.tenant_id=d.tenant_id AND f.factory_id=d.factory_id)
- """, new { tenant, factory, dataset, source })
- ?? throw new MdpApiPullException("PULL_DATASET_UNAVAILABLE");
- Require(profile is null || profile.ReleaseId == current.ReleaseId && profile.SchemaVersion == current.Version, "PULL_RELEASE_CHANGED");
- return current;
- }
- private async Task RequireWriterAsync(ISqlSugarClient db, Profile profile, Published bound)
- {
- await MdpEdgeRoute.RequireDirectAsync(db, configuration, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
- var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId);
- MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
- if (migration is null)
- {
- var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(profile.TenantId, "PURCHASE");
- Require(string.Equals(authority?.SourceSystem, bound.SourceCode, StringComparison.OrdinalIgnoreCase), "PULL_SOURCE_NOT_AUTHORIZED");
- }
- else Require(migration.NewSourceCode == bound.SourceCode, "PULL_SOURCE_NOT_AUTHORIZED");
- }
- private static async Task<PreparedIngestBatch> PrepareAsync(ISqlSugarClient db, Profile profile, Published bound,
- MdpApiPullPlan plan, byte[] body)
- {
- var preparer = await PagePreparerAsync(db, profile, bound);
- var prepared = preparer.PrepareApiPage(PageIdentity(profile, bound), bound.Version, body, MdpIngestProtocol.Limits,
- MdpApiPullPlan.Path(plan.ResponsePath), PurchaseApiWindow);
- Require(MdpBatchFactory.RowsMatch(prepared), "PULL_BATCH_SCOPE_INVALID");
- return prepared;
- }
- private static readonly IngestSourceWindow PurchaseApiWindow = new(null, null, IngestSourceWindow.PurchaseApiTime);
- private static IngestDatasetIdentity PageIdentity(Profile profile, Published bound) =>
- new(profile.TenantId, profile.FactoryId, profile.SourceId, profile.DatasetId, bound.SourceCode, bound.DatasetKey);
- private static async Task<IngestBatchPreparer> PagePreparerAsync(ISqlSugarClient db, Profile profile, Published bound)
- {
- var binder = new MdpIngestContractBinder(new MdpIngestDatasetRegistry(db));
- var (registry, _) = await binder.ReadContractAsync(new MdpIngestActiveBinding
- {
- TenantId = profile.TenantId, FactoryId = profile.FactoryId, DatasetId = profile.DatasetId, SourceId = profile.SourceId,
- SourceCode = bound.SourceCode, DatasetKey = bound.DatasetKey, SourceSchemaVersion = bound.Version
- });
- return new IngestBatchPreparer(registry);
- }
- private static MdpApiPullPlan Plan(Profile profile) => JsonSerializer.Deserialize<MdpApiPullPlan>(profile.PlanJson, Wire)
- ?? throw new MdpApiPullException("PULL_CONFIG_INVALID");
- private static MdpApiPullProfileInfo ProfileInfo(Profile row) => new(row.Id.ToString(CultureInfo.InvariantCulture),
- row.SourceId.ToString(CultureInfo.InvariantCulture), row.SchemaVersion, row.State,
- row.PreviewJson is null ? null : JsonSerializer.Deserialize<MdpApiPullPreview>(row.PreviewJson, Wire));
- private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
- private static async Task<T> Tx<T>(ISqlSugarClient db, Func<Task<T>> body)
- {
- var result = await db.Ado.UseTranAsync(body);
- if (result.IsSuccess) return result.Data;
- if (result.ErrorException is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure);
- throw new MdpApiPullException("PULL_STORE_UNAVAILABLE");
- }
- private static void Require(bool condition, string code)
- {
- if (!condition) throw new MdpApiPullException(code);
- }
- internal sealed class Profile
- {
- public long Id { get; set; }
- public long TenantId { get; set; }
- public long FactoryId { get; set; }
- public long DatasetId { get; set; }
- public long SourceId { get; set; }
- public long ReleaseId { get; set; }
- public long CreatedBy { get; set; }
- public string PlanJson { get; set; } = "";
- public string State { get; set; } = "";
- public string SchemaVersion { get; set; } = "";
- public string? PreviewJson { get; set; }
- }
- private sealed class Published
- {
- public string DatasetKey { get; set; } = "";
- public string Version { get; set; } = "";
- public string SourceCode { get; set; } = "";
- public long ReleaseId { get; set; }
- }
- }
- public sealed record MdpApiPullProfileInfo(string Id, string SourceId, string SchemaVersion, string State, MdpApiPullPreview? Preview);
- public sealed record MdpApiPullPreview(string SchemaVersion, int Received, int Valid, int Isolated, decimal Quantity, bool HasNext, string Digest);
|