using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
using Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
using Admin.NET.Plugin.AiDOP.DataPlatform;
using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
using Microsoft.Extensions.Logging;
namespace Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
/// 入站接收主流水线。步骤顺序按任务书 §6.3 定死,勿换序。
public sealed class MdpInboundReceiveService : ITransient
{
private const string PurchaseOrderEntity = "S3_PURCHASE_ORDER";
private static readonly Regex TableNameRe = new(@"^[A-Za-z0-9_]+$", RegexOptions.Compiled);
private static readonly Regex IsoOffsetRe = new(@"[Zz]|[+\-]\d{2}:\d{2}", RegexOptions.Compiled);
private const int MaxRowBytes = 64 * 1024;
private static readonly TimeSpan InProgressWindow = TimeSpan.FromMinutes(10);
private readonly ISqlSugarClient _db;
private readonly MdpInboundAuthService _auth;
private readonly MdpInboundFieldMapper _mapper;
private readonly MdpStagingWriter _writer;
private readonly MdpInboundModuleTrigger _trigger;
private readonly MdpInboundSnapshotService _snapshots;
private readonly MdmMirrorUpsertService _mirror;
private readonly InboundNeutralProjectionService _neutral;
private readonly ILogger _logger;
public MdpInboundReceiveService(
ISqlSugarClient db,
MdpInboundAuthService auth,
MdpInboundFieldMapper mapper,
MdpStagingWriter writer,
MdpInboundModuleTrigger trigger,
MdpInboundSnapshotService snapshots,
MdmMirrorUpsertService mirror,
InboundNeutralProjectionService neutral,
ILogger logger)
{
_db = db;
_auth = auth;
_mapper = mapper;
_writer = writer;
_trigger = trigger;
_snapshots = snapshots;
_mirror = mirror;
_neutral = neutral;
_logger = logger;
}
public async Task ReceiveAsync(MdpInboundReceiveArgs args, CancellationToken ct)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var entityCode = (args.EntityCode ?? string.Empty).Trim().ToUpperInvariant();
var purchaseOrder = entityCode == PurchaseOrderEntity;
var hash = ToSha256Hex(args.RawBody);
var contractVersion = ContractVersion(args);
MdpEntity entity;
MdpInboundGrant grant;
try
{
entity = await LoadInboundEntityAsync(entityCode, ct)
?? throw new MdpInboundBatchException(403, "entity not authorized");
var denied = await _auth.CheckAsync(args.AccessKey, args.TenantId, entityCode, args.ClientIp, ct);
if (denied != null)
return Fail(denied.Value.Status, denied.Value.Message);
grant = await _auth.GetGrantAsync(args.AccessKey, entityCode, ct)
?? throw new MdpInboundBatchException(403, "entity not authorized");
if (contractVersion == "v1")
_logger.LogInformation(
"inbound receive v1 entity={Entity} accessKey={AccessKey}",
entity.EntityCode, args.AccessKey);
var minimum = await MinContractVersionAsync(grant.Id, ct);
if (string.Equals(minimum, "v2", StringComparison.OrdinalIgnoreCase) && contractVersion != "v2")
return Fail(400, "contract version v2 required");
}
catch (MdpInboundBatchException ex)
{
return Fail(ex.HttpStatus, ex.Message);
}
MdpInboundParsedBatch batch;
try
{
batch = ParseBatch(args.RawBody, grant, entity);
}
catch (MdpInboundBatchException ex)
{
return Fail(ex.HttpStatus, ex.Message);
}
catch (JsonException)
{
return Fail(400, "invalid json");
}
var source = await _db.Queryable()
.Where(s => s.SourceCode == grant.SourceCode && s.Status == 1)
.WhereIF(purchaseOrder, s => s.TenantId == args.TenantId || s.TenantId == 0)
.FirstAsync(ct);
if (source == null)
return Fail(500, "inbound source not configured");
var neutralSource = MdpSourceIdentity.NeutralCode(source.SystemCode, source.SourceCode);
var sourceTable = string.IsNullOrWhiteSpace(entity.SourceTableName)
? entity.EntityCode
: entity.SourceTableName!;
try
{
await _snapshots.EnsureAcceptAsync(
batch.SnapshotId, args.AccessKey, args.TenantId, entity.EntityCode, batch.Seq, ct);
}
catch (MdpInboundBatchException ex)
{
return Fail(ex.HttpStatus, ex.Message);
}
MdpInboundRequest? request;
try
{
request = purchaseOrder
? await FindCommittedPurchaseRequestAsync(args, entity.EntityCode, hash, ct)
: await BeginRequestAsync(args, entity, hash, batch.SnapshotId, ct);
}
catch (MdpInboundBatchException ex)
{
return Fail(ex.HttpStatus, ex.Message);
}
if (request?.Status == "COMMITTED" &&
string.Equals(request.RequestHash, hash, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(request.ReceiptJson))
{
return Receipt(request.ReceiptJson, replay: true);
}
if (!purchaseOrder)
await TryArchiveEnvelopeAsync(args, request!, hash, ct);
try
{
var maps = await _mapper.LoadAsync(args.TenantId, entity.EntityCode, args.AccessKey, ct);
var accepted = new List();
var positions = new Dictionary();
var rejected = new List();
var staleRejected = 0;
var equalTsOverride = 0;
for (var ordinal = 0; ordinal < batch.Rows.Count; ordinal++)
{
var prepared = PrepareRow(
batch.Rows[ordinal], entity, maps, contractVersion, grant, args.TenantId, rejected, out var batchDeny);
if (batchDeny != null)
{
if (request is not null)
await MarkFailedAsync(request.Id, batchDeny.Message, sw.ElapsedMilliseconds, ct);
return Fail(batchDeny.HttpStatus, batchDeny.Message);
}
if (prepared == null)
continue;
if (!purchaseOrder && entity.StaleGuardEnabled == 1)
{
var decision = await GuardStaleAsync(
entity, args.TenantId, sourceTable, prepared, neutralSource, ct);
if (decision.RejectStale)
{
staleRejected++;
rejected.Add(new MdpInboundRejectedRow { BizKey = prepared.BizKey, Reason = "stale" });
continue;
}
if (decision.EqualTsOverride)
equalTsOverride++;
prepared = decision.Row ?? prepared;
}
accepted.Add(prepared);
if (purchaseOrder)
positions.Add(prepared, ordinal);
}
var written = new List();
PurchaseMigrationScope? migration = null;
var replay = false;
var tran = await _db.Ado.UseTranAsync(async () =>
{
if (purchaseOrder)
{
migration = await MdpPurchaseMigrationStore.LockLegacyAsync(_db, args.TenantId,
grant.FactoryId.GetValueOrDefault(), grant.SourceCode);
if (migration is not null)
{
// 可能在等待作用域锁期间,原请求才完成提交;关闭写入不影响旧回执。
var prior = await FindCommittedPurchaseRequestAsync(args, entity.EntityCode, hash, ct, lockRow: true);
if (prior is not null)
{
request = prior;
replay = true;
return;
}
MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Legacy);
if (!string.IsNullOrWhiteSpace(batch.SnapshotId))
throw new MdpIngestHttpException(409, "PURCHASE_SNAPSHOT_UNAVAILABLE");
}
await RequireCurrentPurchaseGrantAsync(grant, source);
ct.ThrowIfCancellationRequested();
request = await BeginRequestAsync(args, entity, hash, batch.SnapshotId, ct);
if (request.Status == "COMMITTED")
{
if (string.IsNullOrWhiteSpace(request.ReceiptJson))
throw new MdpIngestHttpException(409, "PURCHASE_LEGACY_RECEIPT_UNAVAILABLE");
replay = true;
return;
}
await TryArchiveEnvelopeAsync(args, request, hash, ct, required: migration is not null);
}
var current = request ?? throw new InvalidOperationException("Inbound request was not reserved.");
var ctx = new MdpPullContext { TenantId = args.TenantId, BatchId = current.SyncBatchId };
var rowsToWrite = migration is null ? accepted
: accepted.OrderBy(row => TryGetString(row.Dict, "PoNo"), StringComparer.Ordinal)
.ThenBy(row => TryGetString(row.Dict, "PoLine"), StringComparer.Ordinal).ToList();
var useFactoryKey = purchaseOrder && migration is null && grant.FactoryId is > 0
&& await MdpPurchaseMigrationStore.HasFactoryOrderKeyAsync(_db);
foreach (var prepared in rowsToWrite)
{
var row = prepared;
string? storageKey = null;
if (migration is not null)
{
if (!TryMigrationLine(row, out var line))
{
rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "INVALID_PURCHASE_LINE" });
continue;
}
var traceId = FormattableString.Invariant($"{current.Id}:{positions[row]}");
var result = await MdpPurchaseMigrationWriter.WriteAsync(_db, migration, MdpPurchaseMigrationStore.Legacy,
line!, current.SyncBatchId, traceId);
if (result.Status is "WRITTEN" or "REUSED")
written.Add(row);
else if (result.Status == "CONFLICT")
rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "PURCHASE_ORDER_CONFLICT" });
else
throw new InvalidOperationException("Unexpected purchase migration write result.");
continue;
}
if (purchaseOrder)
{
// 旧贴源唯一键没有租户/工厂,先检查精确键,禁止旧通用逻辑转移别的来源。
var ownership = await LockLegacyPurchaseStageAsync(args.TenantId, row, sourceTable, neutralSource, useFactoryKey);
storageKey = ownership.Key;
if (ownership.Conflict)
{
rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "PURCHASE_ORDER_CONFLICT" });
continue;
}
if (entity.StaleGuardEnabled == 1 && ownership.Row is not null)
{
var decision = CheckStale(row, ownership.Row);
if (decision.RejectStale)
{
staleRejected++;
rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "stale" });
continue;
}
if (decision.EqualTsOverride)
equalTsOverride++;
}
}
else
{
await TransferIfNeededAsync(entity, args.TenantId, sourceTable, row.BizKey, neutralSource, ct);
}
var n = await _writer.UpsertAsync(
source, entity, sourceTable, row.Dict, row.RawJson, row.BizKey, ctx, storageKey);
if (n == 0)
{
rejected.Add(new MdpInboundRejectedRow
{
BizKey = row.BizKey,
Reason = "tenant_unresolved"
});
}
else
{
written.Add(row);
}
}
var data = new MdpInboundReceiptData
{
EntityCode = entity.EntityCode,
Accepted = written.Count,
Rejected = rejected.Count,
RejectedRows = rejected,
IdempotentReplay = false,
SyncBatchId = current.SyncBatchId,
RequestId = current.Id,
TransformEnqueued = false,
StaleRejected = staleRejected,
EqualTsOverride = equalTsOverride
};
var resultCode = rejected.Count > 0 ? 2 : 0;
var body = Envelope(resultCode, resultCode == 2 ? "partial" : "ok", data);
var receiptJson = JsonSerializer.Serialize(body, MdpInboundJson.Options);
var now = DateTime.Now;
await _db.Updateable()
.SetColumns(r => new MdpInboundRequest
{
Status = "COMMITTED",
HttpStatus = 202,
ResultCode = resultCode,
Accepted = written.Count,
Rejected = rejected.Count,
StaleRejected = staleRejected,
EqualTsOverride = equalTsOverride,
ReceiptJson = receiptJson,
ErrorMsg = null,
ElapsedMs = (int)sw.ElapsedMilliseconds,
UpdateTime = now
})
.Where(r => r.Id == current.Id)
.ExecuteCommandAsync(ct);
if (!string.IsNullOrWhiteSpace(batch.SnapshotId) && batch.Seq is > 0)
await _snapshots.AdvanceAsync(batch.SnapshotId, batch.Seq.Value, written.Count, ct);
});
if (!tran.IsSuccess)
{
if (tran.ErrorException is MdpIngestHttpException admission)
{
if (request is not null)
await MarkFailedAsync(request.Id, admission.Code, sw.ElapsedMilliseconds, CancellationToken.None, admission.StatusCode);
return Fail(admission.StatusCode, admission.Code);
}
if (tran.ErrorException is MdpInboundBatchException batchError)
return Fail(batchError.HttpStatus, batchError.Message);
var err = tran.ErrorException?.Message ?? "transaction failed";
if (request is not null)
await MarkFailedAsync(request.Id, Truncate(err, 1000), sw.ElapsedMilliseconds,
purchaseOrder ? CancellationToken.None : ct);
_logger.LogError(tran.ErrorException, "inbound write transaction failed requestId={Id}", request?.Id);
return Fail(500, "inbound write failed");
}
var finished = request ?? throw new InvalidOperationException("Inbound request was not reserved.");
if (replay)
return Receipt(finished.ReceiptJson, replay: true);
var committed = await _db.Queryable()
.Where(r => r.Id == finished.Id)
.FirstAsync(ct);
var receiptJson = committed?.ReceiptJson;
if (migration is not null)
return Receipt(receiptJson, replay: false);
try
{
await _mirror.MirrorCommittedAsync(
entity.EntityCode, args.TenantId, grant.FactoryId, grant.SourceCode, written, ct);
if (purchaseOrder && written.Count > 0)
await _neutral.ProjectPurchaseBatchAsync(args.TenantId, grant.FactoryId, grant.SourceCode, neutralSource,
sourceTable, finished.SyncBatchId, ct);
else if (!purchaseOrder)
await _neutral.ProjectAsync(entity.EntityCode, args.TenantId, grant.SourceCode, ct);
}
catch (Exception ex)
{
_logger.LogError(ex, "inbound mirror after commit failed requestId={Id}", finished.Id);
}
var enqueued = false;
try
{
enqueued = await _trigger.EnqueueForEntityAsync(
entity.EntityCode, args.TenantId, grant.FactoryId, ct);
}
catch (Exception ex)
{
_logger.LogError(ex, "inbound trigger after commit failed requestId={Id}", finished.Id);
}
if (enqueued)
receiptJson = await PatchTransformEnqueuedAsync(finished.Id, receiptJson, ct);
return Receipt(receiptJson, replay: false);
}
catch (Exception ex)
{
if (request is not null)
await MarkFailedAsync(request.Id, Truncate(ex.Message, 1000), sw.ElapsedMilliseconds,
purchaseOrder ? CancellationToken.None : ct);
_logger.LogError(ex, "inbound receive failed requestId={Id}", request?.Id);
return Fail(500, "inbound receive failed");
}
}
private static string ContractVersion(MdpInboundReceiveArgs args)
{
if (args.Headers != null
&& args.Headers.TryGetValue(MdpInboundFieldMapper.ContractVersionHeader, out var raw))
return MdpInboundFieldMapper.NormalizeVersion(raw);
return "v1";
}
/// 授权上的最低契约版本。列尚未迁移时按 v1,不打断推数。
private async Task MinContractVersionAsync(long grantId, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
try
{
var value = await _db.Ado.GetStringAsync(
"SELECT min_contract_version FROM mdp_inbound_grant WHERE id=@id",
new SugarParameter("@id", grantId));
return string.IsNullOrWhiteSpace(value) ? "v1" : value.Trim();
}
catch (Exception ex)
{
_logger.LogDebug(ex, "入站最低契约版本列未就绪,按 v1 继续");
return "v1";
}
}
public async Task SchemaAsync(
string entityCode, string accessKey, long tenantId, string clientIp, CancellationToken ct,
string? contractVersion = null)
{
var code = (entityCode ?? string.Empty).Trim().ToUpperInvariant();
var denied = await _auth.CheckAsync(accessKey, tenantId, code, clientIp, ct);
if (denied != null)
return Fail(denied.Value.Status, denied.Value.Message);
var entity = await LoadInboundEntityAsync(code, ct);
if (entity == null)
return Fail(403, "entity not authorized");
var maps = await _mapper.LoadAsync(tenantId, entity.EntityCode, accessKey, ct);
var version = MdpInboundFieldMapper.NormalizeVersion(contractVersion);
if (version == "v1")
_logger.LogInformation("inbound schema v1 entity={Entity} accessKey={AccessKey}", entity.EntityCode, accessKey);
return Ok(_mapper.BuildSchema(entity, maps, version));
}
public async Task ReceiptAsync(
string syncBatchId, string accessKey, CancellationToken ct)
{
var row = await _db.Queryable()
.Where(r => r.SyncBatchId == syncBatchId && r.AccessKey == accessKey)
.FirstAsync(ct);
if (row == null)
return Fail(404, "receipt not found");
object receipt = null;
if (!string.IsNullOrWhiteSpace(row.ReceiptJson))
{
try
{
receipt = JsonSerializer.Deserialize