using System.Security.Cryptography; using System.Text; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed partial class MdpIngestDatasetController { [HttpGet("{id:long}/api-contract")] [DisplayName("下载数据集 API 推送契约")] public Task ReadApiContract(long id, [FromQuery] long? factoryId, [FromServices] MdpIngestContractBinder binder, [FromQuery] bool kit = false) => WithScope(factoryId, async scope => { var dataset = await Datasets(scope).FirstAsync(row => row.Id == id); if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version) return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" }); var binding = new MdpIngestActiveBinding { DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId, FactoryId = dataset.FactoryId, SourceSchemaVersion = version }; IngestContract contract; try { (_, contract) = await binder.ReadContractAsync(binding); } catch (IngestContractException) { return NotFound(new { message = "未找到该版本的受控契约" }); } var names = contract.FieldMapJson is null ? new Dictionary() : JsonSerializer.Deserialize>(contract.FieldMapJson)!; string Map(string name) => names.GetValueOrDefault(name, name); var rowSchema = new Dictionary { ["$schema"] = "https://json-schema.org/draft/2020-12/schema", ["type"] = "object", ["required"] = new[] { Map("PoNo"), Map("PoLine"), Map("ItemCode"), Map("OrderQty"), Map("sourceUpdatedAt") }, ["properties"] = new Dictionary { [Map("PoNo")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "^[^#]*[^#\\s][^#]*$" }, [Map("PoLine")] = new { type = "string", minLength = 1, maxLength = 50, pattern = "^[^#]*[^#\\s][^#]*$" }, [Map("ItemCode")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "\\S" }, [Map("OrderQty")] = new { type = "number", exclusiveMinimum = 0, exclusiveMaximum = 1_000_000_000_000m, multipleOf = 0.000001m }, [Map("sourceUpdatedAt")] = new { type = "string", format = "date-time" }, [Map("SupplierCode")] = OptionalText(100), [Map("Status")] = OptionalText(50), [Map("OrderDate")] = OptionalDate(), [Map("DueDate")] = OptionalDate() } }; var sample = new Dictionary { [Map("PoNo")] = kit ? $"SANDBOX-{Guid.NewGuid():N}" : "SANDBOX-PO-001", [Map("PoLine")] = "01", [Map("ItemCode")] = "SANDBOX-SKU", [Map("OrderQty")] = 15.5m, [Map("sourceUpdatedAt")] = kit ? DateTimeOffset.UtcNow.ToString("O") : "2026-01-01T00:00:00Z" }; var endpoint = $"/api/v1/ingest/{dataset.DatasetKey}"; Response.Headers.CacheControl = "no-store"; var document = new { dataset.DatasetKey, schemaVersion = version, schemaSha256 = contract.SourceSchema.Stamp.Sha256, schemaJson = contract.SourceSchema.Json, rowSchema, endpoint, samples = new { json = JsonSerializer.Serialize(new { factoryId = scope.FactoryId.ToString(), data = new { list = new[] { sample } } }), ndjson = JsonSerializer.Serialize(sample) + "\n", ndjsonFactoryHeader = scope.FactoryId.ToString() }, batchStatusEndpoint = endpoint + "/batches/{batchId}", formats = new[] { "application/json", "application/x-ndjson" }, limits = MdpIngestProtocol.Limits, retry = new { idempotencyDays = 7, nonceMinutes = 15, clockSkewSeconds = 300 }, signatureVector = SignatureVector(endpoint, version), errorCodes = new[] { "INVALID_AUTHENTICATION", "NONCE_REPLAYED", "DATASET_UNAVAILABLE", "INVALID_BATCH_SCOPE", "CONTENT_DIGEST_MISMATCH", "INVALID_JSON", "INVALID_ENVELOPE", "UNKNOWN_SCHEMA", "BODY_TOO_LARGE", "TOO_MANY_RECORDS", "JSON_TOO_DEEP", "UNSUPPORTED_MEDIA_TYPE", "SOURCE_RATE_LIMITED", "TENANT_RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_EXPIRED", "BATCH_NOT_FOUND" } }; if (!kit) return Ok(document); var config = HttpContext.RequestServices.GetRequiredService(); var origin = config[$"MdpUnifiedIngress:PushKits:{dataset.TenantId}:{dataset.FactoryId}:{dataset.Id}:SandboxBaseUrl"]; var bytes = MdpPushKit.Build(JsonSerializer.SerializeToElement(document, MdpPushKit.JsonOptions), scope.FactoryId.ToString(System.Globalization.CultureInfo.InvariantCulture), origin); return File(bytes, "application/zip", MdpPushKit.FileName(dataset.DatasetKey, version)); }); [HttpPost("{id:long}/api-contract/validate")] [RequestSizeLimit(8 * 1024 * 1024)] [DisplayName("校验数据集 API 推送样本")] public Task ValidatePushSample(long id, [FromQuery] long? factoryId, [FromBody] MdpValidatePushSample input, [FromServices] MdpIngestContractBinder binder) => WithScope(factoryId, async scope => { var dataset = await Datasets(scope).FirstAsync(row => row.Id == id); if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version) return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" }); var format = input.MediaType switch { "application/json" => IngestPayloadFormat.Json, "application/x-ndjson" => IngestPayloadFormat.Ndjson, _ => (IngestPayloadFormat?)null }; if (format is null) return StatusCode(StatusCodes.Status415UnsupportedMediaType, new { code = "UNSUPPORTED_MEDIA_TYPE" }); if (input.Sample is null || Encoding.UTF8.GetByteCount(input.Sample) > MdpIngestProtocol.Limits.MaxBodyBytes) return BadRequest(new { code = "SAMPLE_REQUIRED_OR_TOO_LARGE" }); var binding = new MdpIngestActiveBinding { DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId, FactoryId = dataset.FactoryId, SourceSchemaVersion = version }; var identity = new IngestDatasetIdentity(dataset.TenantId, dataset.FactoryId, 0, dataset.Id, "", dataset.DatasetKey); var bytes = Encoding.UTF8.GetBytes(input.Sample); try { var (registry, _) = await binder.ReadContractAsync(binding); var batch = new IngestBatchPreparer(registry).Prepare(identity, version, bytes, MdpIngestProtocol.Limits, format: format.Value); if (format == IngestPayloadFormat.Json && !MdpBatchFactory.TryRead(bytes, dataset.TenantId, dataset.FactoryId, false, out _) || !MdpBatchFactory.RowsMatch(batch)) return UnprocessableEntity(new { code = "INVALID_BATCH_SCOPE" }); var processed = PurchaseBatchProcessor.Process(batch, ""); var positions = batch.Events.ToDictionary(row => row.RawEventId, row => row.SourcePosition); Response.Headers.CacheControl = "no-store"; return Ok(new { schemaVersion = version, received = batch.Batch.AcceptedRowCount, valid = processed.Package.Items.Count, isolated = processed.Quarantines.Select(row => row.RawEventId).Distinct().Count(), issues = processed.Quarantines.Select(row => new { position = positions[row.RawEventId], row.Field, row.Reason }), traceId = HttpContext.TraceIdentifier }); } catch (IngestContractException error) { return UnprocessableEntity(new { code = error.Code.ToString(), traceId = HttpContext.TraceIdentifier }); } }); private static object OptionalText(int maxLength) => new { type = new[] { "string", "null" }, maxLength }; private static object OptionalDate() => new { type = new[] { "string", "null" }, pattern = @"^[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$" }; private static object SignatureVector(string endpoint, string version) { const string accessKey = "documentation-example"; const string timestamp = "1700000000"; const string nonce = "example-nonce"; const string idempotencyKey = "example-idempotency"; const string mediaType = "application/x-ndjson"; const string payload = "{}\n"; var key = Enumerable.Range(0, 32).Select(value => (byte)value).ToArray(); var digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant(); var canonical = MdpIngestProtocol.CanonicalSignature("POST", endpoint, accessKey, timestamp, nonce, digest, idempotencyKey, true, mediaType, null, version); var signature = Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(canonical))); return new { method = "POST", path = endpoint, accessKey, timestamp, nonce, idempotencyKey, mediaType, schemaVersion = version, payload, payloadSha256 = digest, exampleKeyBase64 = Convert.ToBase64String(key), canonical, signatureBase64 = signature }; } } public sealed record MdpValidatePushSample(string? MediaType, string? Sample);