MdpIngestDatasetController.ApiContract.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 package = (registry as PurchaseVersionConfiguration)?.Package;
  60. var standard = package != null && contract.StandardSchemaStamp is { } stamp
  61. ? package.StandardSchema(stamp.Version) : null;
  62. var sampleTime = DateTimeOffset.UtcNow;
  63. var sample = new Dictionary<string, object>
  64. {
  65. [Map("PoNo")] = kit ? $"SANDBOX-{Guid.NewGuid():N}" : "SANDBOX-PO-001",
  66. [Map("PoLine")] = "01", [Map("ItemCode")] = governedRow is { } row
  67. ? CompatibleSample(row, Map("ItemCode"), "SANDBOX-SKU") : "SANDBOX-SKU",
  68. [Map("OrderQty")] = governedRow is { } quantitySchema
  69. ? CompatibleSample(quantitySchema, Map("OrderQty"), "1", preferNumber: true) : 15.5m,
  70. [Map("sourceUpdatedAt")] = kit || package?.UsesMasterData == true ? sampleTime.ToString("O") : "2026-01-01T00:00:00Z"
  71. };
  72. if (package is { UsesMasterData: true })
  73. {
  74. var day = DateOnly.FromDateTime(sampleTime.UtcDateTime);
  75. foreach (var (field, kind) in new[] { ("ItemCode", "item"), ("SupplierCode", "supplier") })
  76. {
  77. if (!package.RequiresMaster(field, kind)) continue;
  78. var mapping = package.MasterMappings.FirstOrDefault(x => x.Kind == kind && x.From <= day
  79. && (x.To is null || day < x.To));
  80. if (mapping != null) sample[Map(field)] = mapping.ExternalCode;
  81. }
  82. }
  83. var endpoint = $"/api/v1/ingest/{dataset.DatasetKey}";
  84. Response.Headers.CacheControl = "no-store";
  85. var document = new
  86. {
  87. dataset.DatasetKey, schemaVersion = version, schemaSha256 = contract.SourceSchema.Stamp.Sha256,
  88. schemaJson = contract.SourceSchema.Json, rowSchema = (object?)governedRow ?? rowSchema, endpoint,
  89. schemas = new { source = contract.SourceSchema, raw = contract.RawSchema, handoff = contract.HandoffSchema, standard },
  90. samples = new
  91. {
  92. json = JsonSerializer.Serialize(new { factoryId = scope.FactoryId.ToString(), data = new { list = new[] { sample } } }),
  93. ndjson = JsonSerializer.Serialize(sample) + "\n",
  94. ndjsonFactoryHeader = scope.FactoryId.ToString()
  95. },
  96. batchStatusEndpoint = endpoint + "/batches/{batchId}",
  97. formats = new[] { "application/json", "application/x-ndjson" },
  98. limits = MdpIngestProtocol.Limits,
  99. retry = new { idempotencyDays = 7, nonceMinutes = 15, clockSkewSeconds = 300 },
  100. signatureVector = SignatureVector(endpoint, version),
  101. errorCodes = new[] { "INVALID_AUTHENTICATION", "NONCE_REPLAYED", "DATASET_UNAVAILABLE", "INVALID_BATCH_SCOPE",
  102. "CONTENT_DIGEST_MISMATCH", "INVALID_JSON", "INVALID_ENVELOPE", "UNKNOWN_SCHEMA", "BODY_TOO_LARGE",
  103. "TOO_MANY_RECORDS", "JSON_TOO_DEEP", "UNSUPPORTED_MEDIA_TYPE", "SOURCE_RATE_LIMITED",
  104. "TENANT_RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_EXPIRED", "BATCH_NOT_FOUND" }
  105. };
  106. if (!kit)
  107. return Ok(document);
  108. var config = HttpContext.RequestServices.GetRequiredService<IConfiguration>();
  109. var origin = config[$"MdpUnifiedIngress:PushKits:{dataset.TenantId}:{dataset.FactoryId}:{dataset.Id}:SandboxBaseUrl"];
  110. var bytes = MdpPushKit.Build(JsonSerializer.SerializeToElement(document, MdpPushKit.JsonOptions),
  111. scope.FactoryId.ToString(System.Globalization.CultureInfo.InvariantCulture), origin);
  112. return File(bytes, "application/zip", MdpPushKit.FileName(dataset.DatasetKey, version));
  113. });
  114. [HttpPost("{id:long}/api-contract/validate")]
  115. [RequestSizeLimit(8 * 1024 * 1024)]
  116. [DisplayName("校验数据集 API 推送样本")]
  117. public Task<IActionResult> ValidatePushSample(long id, [FromQuery] long? factoryId, [FromBody] MdpValidatePushSample input,
  118. [FromServices] MdpIngestContractBinder binder, [FromQuery] long? sourceId = null) =>
  119. WithScope(factoryId, async scope =>
  120. {
  121. var dataset = await Datasets(scope).FirstAsync(row => row.Id == id);
  122. var version = dataset == null ? null : await DownloadSourceVersion(dataset, sourceId);
  123. if (dataset == null || version == null)
  124. return NotFound(new { message = "当前工厂或来源没有可用的 Schema" });
  125. var format = input.MediaType switch
  126. {
  127. "application/json" => IngestPayloadFormat.Json,
  128. "application/x-ndjson" => IngestPayloadFormat.Ndjson,
  129. _ => (IngestPayloadFormat?)null
  130. };
  131. if (format is null)
  132. return StatusCode(StatusCodes.Status415UnsupportedMediaType, new { code = "UNSUPPORTED_MEDIA_TYPE" });
  133. if (input.Sample is null || Encoding.UTF8.GetByteCount(input.Sample) > MdpIngestProtocol.Limits.MaxBodyBytes)
  134. return BadRequest(new { code = "SAMPLE_REQUIRED_OR_TOO_LARGE" });
  135. var binding = new MdpIngestActiveBinding
  136. {
  137. DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId,
  138. FactoryId = dataset.FactoryId, SourceSchemaVersion = version
  139. };
  140. var identity = new IngestDatasetIdentity(dataset.TenantId, dataset.FactoryId, 0, dataset.Id, "", dataset.DatasetKey);
  141. var bytes = Encoding.UTF8.GetBytes(input.Sample);
  142. try
  143. {
  144. var (registry, _) = await binder.ReadContractAsync(binding);
  145. var batch = new IngestBatchPreparer(registry).Prepare(identity, version, bytes, MdpIngestProtocol.Limits, format: format.Value);
  146. if (format == IngestPayloadFormat.Json
  147. && !MdpBatchFactory.TryRead(bytes, dataset.TenantId, dataset.FactoryId, false, out _)
  148. || !MdpBatchFactory.RowsMatch(batch))
  149. return UnprocessableEntity(new { code = "INVALID_BATCH_SCOPE" });
  150. var processed = PurchaseBatchProcessor.Process(batch, "");
  151. var positions = batch.Events.ToDictionary(row => row.RawEventId, row => row.SourcePosition);
  152. Response.Headers.CacheControl = "no-store";
  153. return Ok(new
  154. {
  155. schemaVersion = version, received = batch.Batch.AcceptedRowCount, valid = processed.Package.Items.Count,
  156. isolated = processed.Quarantines.Select(row => row.RawEventId).Distinct().Count(),
  157. issues = processed.Quarantines.Select(row => new { position = positions[row.RawEventId], row.Field, row.Reason }),
  158. traceId = HttpContext.TraceIdentifier
  159. });
  160. }
  161. catch (IngestContractException error)
  162. {
  163. return UnprocessableEntity(new { code = error.Code.ToString(), traceId = HttpContext.TraceIdentifier });
  164. }
  165. });
  166. private async Task<string?> DownloadSourceVersion(MdpIngestDataset dataset, long? sourceId)
  167. {
  168. if (sourceId == null) return dataset.ActiveSchemaVersion;
  169. if (await BoundSource(dataset, sourceId.Value) == null) return null;
  170. return await db.Ado.SqlQuerySingleAsync<string>("""
  171. SELECT e.schema_version FROM mdp_ingest_effective_source e
  172. WHERE e.tenant_id=@TenantId AND e.factory_id=@FactoryId AND e.dataset_id=@Id AND e.source_id=@sourceId
  173. AND (NOT EXISTS (SELECT 1 FROM mdp_ingest_contract_archive a WHERE a.tenant_id=e.tenant_id
  174. AND a.factory_id=e.factory_id AND a.dataset_id=e.dataset_id AND a.schema_version=e.schema_version)
  175. OR EXISTS (SELECT 1 FROM mdp_ingest_published_source p WHERE p.tenant_id=e.tenant_id
  176. 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))
  177. """, new { dataset.TenantId, dataset.FactoryId, dataset.Id, sourceId });
  178. }
  179. private static JsonElement SourceRow(string schema)
  180. {
  181. using var document = JsonDocument.Parse(schema);
  182. return document.RootElement.GetProperty("properties").GetProperty("data")
  183. .GetProperty("properties").GetProperty("list").GetProperty("items").Clone();
  184. }
  185. private static object CompatibleSample(JsonElement row, string field, string text, bool preferNumber = false)
  186. {
  187. var type = row.GetProperty("properties").GetProperty(field).GetProperty("type");
  188. var types = type.ValueKind == JsonValueKind.Array
  189. ? type.EnumerateArray().Select(value => value.GetString()).ToArray()
  190. : [type.GetString()];
  191. if (!preferNumber && types.Contains("string")) return text;
  192. if (types.Contains("number") || types.Contains("integer")) return 1;
  193. if (types.Contains("boolean")) return true;
  194. return text;
  195. }
  196. private static object OptionalText(int maxLength) => new { type = new[] { "string", "null" }, maxLength };
  197. private static object OptionalDate() =>
  198. 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}$" };
  199. private static object SignatureVector(string endpoint, string version)
  200. {
  201. const string accessKey = "documentation-example";
  202. const string timestamp = "1700000000";
  203. const string nonce = "example-nonce";
  204. const string idempotencyKey = "example-idempotency";
  205. const string mediaType = "application/x-ndjson";
  206. const string payload = "{}\n";
  207. var key = Enumerable.Range(0, 32).Select(value => (byte)value).ToArray();
  208. var digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant();
  209. var canonical = MdpIngestProtocol.CanonicalSignature("POST", endpoint, accessKey, timestamp, nonce,
  210. digest, idempotencyKey, true, mediaType, null, version);
  211. var signature = Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(canonical)));
  212. return new
  213. {
  214. method = "POST", path = endpoint, accessKey, timestamp, nonce, idempotencyKey, mediaType, schemaVersion = version,
  215. payload, payloadSha256 = digest, exampleKeyBase64 = Convert.ToBase64String(key), canonical, signatureBase64 = signature
  216. };
  217. }
  218. }
  219. public sealed record MdpValidatePushSample(string? MediaType, string? Sample);