MdpIngestDatasetController.ApiContract.cs 13 KB

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