MdpIngestDatasetController.ApiContract.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  9. public sealed partial class MdpIngestDatasetController
  10. {
  11. [HttpGet("{id:long}/api-contract")]
  12. [DisplayName("下载数据集 API 推送契约")]
  13. public Task<IActionResult> ReadApiContract(long id, [FromQuery] long? factoryId, [FromServices] MdpIngestContractBinder binder,
  14. [FromQuery] bool kit = false) =>
  15. WithScope(factoryId, async scope =>
  16. {
  17. var dataset = await Datasets(scope).FirstAsync(row => row.Id == id);
  18. if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version)
  19. return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" });
  20. var binding = new MdpIngestActiveBinding
  21. {
  22. DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId,
  23. FactoryId = dataset.FactoryId, SourceSchemaVersion = version
  24. };
  25. IngestContract contract;
  26. try
  27. {
  28. (_, contract) = await binder.ReadContractAsync(binding);
  29. }
  30. catch (IngestContractException)
  31. {
  32. return NotFound(new { message = "未找到该版本的受控契约" });
  33. }
  34. var names = contract.FieldMapJson is null ? new Dictionary<string, string>()
  35. : JsonSerializer.Deserialize<Dictionary<string, string>>(contract.FieldMapJson)!;
  36. string Map(string name) => names.GetValueOrDefault(name, name);
  37. var rowSchema = new Dictionary<string, object>
  38. {
  39. ["$schema"] = "https://json-schema.org/draft/2020-12/schema",
  40. ["type"] = "object",
  41. ["required"] = new[] { Map("PoNo"), Map("PoLine"), Map("ItemCode"), Map("OrderQty"), Map("sourceUpdatedAt") },
  42. ["properties"] = new Dictionary<string, object>
  43. {
  44. [Map("PoNo")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "^[^#]*[^#\\s][^#]*$" },
  45. [Map("PoLine")] = new { type = "string", minLength = 1, maxLength = 50, pattern = "^[^#]*[^#\\s][^#]*$" },
  46. [Map("ItemCode")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "\\S" },
  47. [Map("OrderQty")] = new { type = "number", exclusiveMinimum = 0, exclusiveMaximum = 1_000_000_000_000m, multipleOf = 0.000001m },
  48. [Map("sourceUpdatedAt")] = new { type = "string", format = "date-time" },
  49. [Map("SupplierCode")] = OptionalText(100),
  50. [Map("Status")] = OptionalText(50),
  51. [Map("OrderDate")] = OptionalDate(),
  52. [Map("DueDate")] = OptionalDate()
  53. }
  54. };
  55. var sample = new Dictionary<string, object>
  56. {
  57. [Map("PoNo")] = kit ? $"SANDBOX-{Guid.NewGuid():N}" : "SANDBOX-PO-001",
  58. [Map("PoLine")] = "01", [Map("ItemCode")] = "SANDBOX-SKU",
  59. [Map("OrderQty")] = 15.5m,
  60. [Map("sourceUpdatedAt")] = kit ? DateTimeOffset.UtcNow.ToString("O") : "2026-01-01T00:00:00Z"
  61. };
  62. var endpoint = $"/api/v1/ingest/{dataset.DatasetKey}";
  63. Response.Headers.CacheControl = "no-store";
  64. var document = new
  65. {
  66. dataset.DatasetKey, schemaVersion = version, schemaSha256 = contract.SourceSchema.Stamp.Sha256,
  67. schemaJson = contract.SourceSchema.Json, rowSchema, endpoint,
  68. samples = new
  69. {
  70. json = JsonSerializer.Serialize(new { factoryId = scope.FactoryId.ToString(), data = new { list = new[] { sample } } }),
  71. ndjson = JsonSerializer.Serialize(sample) + "\n",
  72. ndjsonFactoryHeader = scope.FactoryId.ToString()
  73. },
  74. batchStatusEndpoint = endpoint + "/batches/{batchId}",
  75. formats = new[] { "application/json", "application/x-ndjson" },
  76. limits = MdpIngestProtocol.Limits,
  77. retry = new { idempotencyDays = 7, nonceMinutes = 15, clockSkewSeconds = 300 },
  78. signatureVector = SignatureVector(endpoint, version),
  79. errorCodes = new[] { "INVALID_AUTHENTICATION", "NONCE_REPLAYED", "DATASET_UNAVAILABLE", "INVALID_BATCH_SCOPE",
  80. "CONTENT_DIGEST_MISMATCH", "INVALID_JSON", "INVALID_ENVELOPE", "UNKNOWN_SCHEMA", "BODY_TOO_LARGE",
  81. "TOO_MANY_RECORDS", "JSON_TOO_DEEP", "UNSUPPORTED_MEDIA_TYPE", "SOURCE_RATE_LIMITED",
  82. "TENANT_RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_EXPIRED", "BATCH_NOT_FOUND" }
  83. };
  84. if (!kit)
  85. return Ok(document);
  86. var config = HttpContext.RequestServices.GetRequiredService<IConfiguration>();
  87. var origin = config[$"MdpUnifiedIngress:PushKits:{dataset.TenantId}:{dataset.FactoryId}:{dataset.Id}:SandboxBaseUrl"];
  88. var bytes = MdpPushKit.Build(JsonSerializer.SerializeToElement(document, MdpPushKit.JsonOptions),
  89. scope.FactoryId.ToString(System.Globalization.CultureInfo.InvariantCulture), origin);
  90. return File(bytes, "application/zip", MdpPushKit.FileName(dataset.DatasetKey, version));
  91. });
  92. [HttpPost("{id:long}/api-contract/validate")]
  93. [RequestSizeLimit(8 * 1024 * 1024)]
  94. [DisplayName("校验数据集 API 推送样本")]
  95. public Task<IActionResult> ValidatePushSample(long id, [FromQuery] long? factoryId, [FromBody] MdpValidatePushSample input,
  96. [FromServices] MdpIngestContractBinder binder) =>
  97. WithScope(factoryId, async scope =>
  98. {
  99. var dataset = await Datasets(scope).FirstAsync(row => row.Id == id);
  100. if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version)
  101. return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" });
  102. var format = input.MediaType switch
  103. {
  104. "application/json" => IngestPayloadFormat.Json,
  105. "application/x-ndjson" => IngestPayloadFormat.Ndjson,
  106. _ => (IngestPayloadFormat?)null
  107. };
  108. if (format is null)
  109. return StatusCode(StatusCodes.Status415UnsupportedMediaType, new { code = "UNSUPPORTED_MEDIA_TYPE" });
  110. if (input.Sample is null || Encoding.UTF8.GetByteCount(input.Sample) > MdpIngestProtocol.Limits.MaxBodyBytes)
  111. return BadRequest(new { code = "SAMPLE_REQUIRED_OR_TOO_LARGE" });
  112. var binding = new MdpIngestActiveBinding
  113. {
  114. DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId,
  115. FactoryId = dataset.FactoryId, SourceSchemaVersion = version
  116. };
  117. var identity = new IngestDatasetIdentity(dataset.TenantId, dataset.FactoryId, 0, dataset.Id, "", dataset.DatasetKey);
  118. var bytes = Encoding.UTF8.GetBytes(input.Sample);
  119. try
  120. {
  121. var (registry, _) = await binder.ReadContractAsync(binding);
  122. var batch = new IngestBatchPreparer(registry).Prepare(identity, version, bytes, MdpIngestProtocol.Limits, format: format.Value);
  123. if (format == IngestPayloadFormat.Json
  124. && !MdpBatchFactory.TryRead(bytes, dataset.TenantId, dataset.FactoryId, false, out _)
  125. || !MdpBatchFactory.RowsMatch(batch))
  126. return UnprocessableEntity(new { code = "INVALID_BATCH_SCOPE" });
  127. var processed = PurchaseBatchProcessor.Process(batch, "");
  128. var positions = batch.Events.ToDictionary(row => row.RawEventId, row => row.SourcePosition);
  129. Response.Headers.CacheControl = "no-store";
  130. return Ok(new
  131. {
  132. schemaVersion = version, received = batch.Batch.AcceptedRowCount, valid = processed.Package.Items.Count,
  133. isolated = processed.Quarantines.Select(row => row.RawEventId).Distinct().Count(),
  134. issues = processed.Quarantines.Select(row => new { position = positions[row.RawEventId], row.Field, row.Reason }),
  135. traceId = HttpContext.TraceIdentifier
  136. });
  137. }
  138. catch (IngestContractException error)
  139. {
  140. return UnprocessableEntity(new { code = error.Code.ToString(), traceId = HttpContext.TraceIdentifier });
  141. }
  142. });
  143. private static object OptionalText(int maxLength) => new { type = new[] { "string", "null" }, maxLength };
  144. private static object OptionalDate() =>
  145. 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}$" };
  146. private static object SignatureVector(string endpoint, string version)
  147. {
  148. const string accessKey = "documentation-example";
  149. const string timestamp = "1700000000";
  150. const string nonce = "example-nonce";
  151. const string idempotencyKey = "example-idempotency";
  152. const string mediaType = "application/x-ndjson";
  153. const string payload = "{}\n";
  154. var key = Enumerable.Range(0, 32).Select(value => (byte)value).ToArray();
  155. var digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant();
  156. var canonical = MdpIngestProtocol.CanonicalSignature("POST", endpoint, accessKey, timestamp, nonce,
  157. digest, idempotencyKey, true, mediaType, null, version);
  158. var signature = Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(canonical)));
  159. return new
  160. {
  161. method = "POST", path = endpoint, accessKey, timestamp, nonce, idempotencyKey, mediaType, schemaVersion = version,
  162. payload, payloadSha256 = digest, exampleKeyBase64 = Convert.ToBase64String(key), canonical, signatureBase64 = signature
  163. };
  164. }
  165. }
  166. public sealed record MdpValidatePushSample(string? MediaType, string? Sample);