MdpPushKit.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. using System.IO.Compression;
  2. using System.Text;
  3. using System.Text.Json;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. internal static class MdpPushKit
  6. {
  7. internal static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true };
  8. private static readonly UTF8Encoding Utf8 = new(false);
  9. private static readonly string[] Clients = ["push.py", "push.mjs", "Push.cs", "Push.java"];
  10. internal static byte[] Build(JsonElement contract, string factory, string? configuredOrigin)
  11. {
  12. var origin = HttpsOrigin(configuredOrigin);
  13. var dataset = Text(contract, "datasetKey");
  14. var version = Text(contract, "schemaVersion");
  15. var endpoint = Text(contract, "endpoint");
  16. var status = Text(contract, "batchStatusEndpoint");
  17. var samples = contract.GetProperty("samples");
  18. using var output = new MemoryStream();
  19. using (var zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true))
  20. {
  21. AddJson("api-contract.json", contract);
  22. AddJson("row.schema.json", contract.GetProperty("rowSchema"));
  23. Add("source.schema.json", Text(contract, "schemaJson"));
  24. Add("sample.json", Text(samples, "json"));
  25. Add("sample.ndjson", Text(samples, "ndjson"));
  26. AddJson("signature-vector.json", contract.GetProperty("signatureVector"));
  27. AddJson("openapi.json", OpenApi(dataset, version, endpoint, status, origin));
  28. Add("client.env", $"INGRESS_BASE={origin}\nDATASET_ENDPOINT={endpoint}\nFACTORY_ID={factory}\nSCHEMA_VERSION={version}\n");
  29. var assembly = typeof(MdpPushKit).Assembly;
  30. foreach (var client in Clients)
  31. {
  32. using var input = assembly.GetManifestResourceStream("MdpPushKit." + client)
  33. ?? throw new InvalidOperationException("Missing API push kit client.");
  34. using var entry = zip.CreateEntry(client).Open();
  35. input.CopyTo(entry);
  36. }
  37. Add("README.md", Guide(dataset, version, factory, origin));
  38. void AddJson(string file, object value) => Add(file, JsonSerializer.Serialize(value, JsonOptions));
  39. void Add(string file, string contents)
  40. {
  41. using var writer = new StreamWriter(zip.CreateEntry(file).Open(), Utf8);
  42. writer.Write(contents);
  43. }
  44. }
  45. return output.ToArray();
  46. }
  47. internal static string FileName(string dataset, string version) => $"{Safe(dataset)}.{Safe(version)}.push-kit.zip";
  48. private static string Safe(string value) => new(value.Select(character => char.IsAsciiLetterOrDigit(character)
  49. || character is '.' or '_' or '-' ? character : '_').ToArray());
  50. private static string Text(JsonElement value, string name) => value.GetProperty(name).GetString()!;
  51. private static string? HttpsOrigin(string? configured) =>
  52. Uri.TryCreate(configured, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps
  53. && uri.UserInfo.Length == 0 && uri.AbsolutePath == "/" && uri.Query.Length == 0 && uri.Fragment.Length == 0
  54. ? uri.GetLeftPart(UriPartial.Authority) : null;
  55. private static object OpenApi(string dataset, string version, string endpoint, string status, string? origin)
  56. {
  57. var auth = new[] { "X-Access-Key", "X-Timestamp", "X-Nonce", "X-Content-SHA256", "X-Signature",
  58. "X-Signature-Version" }.Select(name => Parameter(name, "header")).ToArray();
  59. var receive = new
  60. {
  61. operationId = "pushDataset",
  62. parameters = auth.Concat([Parameter("Idempotency-Key", "header"), Parameter("X-Schema-Version", "header"),
  63. Parameter("X-Factory-Id", "header", false, "NDJSON 多工厂授权使用此头。JSON 使用信封中的 factoryId。")]),
  64. requestBody = new
  65. {
  66. required = true,
  67. content = new Dictionary<string, object>
  68. {
  69. ["application/json"] = new { schema = new { type = "object", required = new[] { "data" },
  70. properties = new { factoryId = new { type = "string" }, data = new { type = "object",
  71. required = new[] { "list" }, properties = new { list = new { type = "array", minItems = 1, maxItems = 100,
  72. items = new Dictionary<string, string> { ["$ref"] = "./row.schema.json" } } } } } } },
  73. ["application/x-ndjson"] = new { schema = new { type = "string" },
  74. example = "See sample.ndjson", description = "One row per line. Row schema is row.schema.json." }
  75. }
  76. },
  77. responses = Responses("202", "已持久接收。保留 batchId 以查询处理结果。")
  78. };
  79. return new
  80. {
  81. openapi = "3.1.0",
  82. info = new { title = dataset + " API 推送", version },
  83. servers = origin is null ? Array.Empty<object>() : [new { url = origin }],
  84. paths = new Dictionary<string, object>
  85. {
  86. [endpoint] = new { post = receive },
  87. [status] = new { get = new { operationId = "getBatchStatus",
  88. parameters = auth.Concat([Parameter("batchId", "path"),
  89. Parameter("X-Factory-Id", "header", false, "多工厂授权查询时填写。")]),
  90. responses = Responses("200", "批次处理及交接状态。") } }
  91. }
  92. };
  93. static object Parameter(string name, string location, bool required = true, string? description = null)
  94. {
  95. var parameter = new Dictionary<string, object>
  96. {
  97. ["name"] = name, ["in"] = location, ["required"] = required, ["schema"] = new { type = "string" }
  98. };
  99. if (description is not null) parameter["description"] = description;
  100. return parameter;
  101. }
  102. static Dictionary<string, object> Responses(string success, string description) => new()
  103. {
  104. [success] = new { description },
  105. ["default"] = new { description = "返回诊断码及请求追踪号。见 api-contract.json。" }
  106. };
  107. }
  108. private static string Guide(string dataset, string version, string factory, string? origin) => $"""
  109. # {dataset} 推送接入
  110. 此包对应 Schema `{version}` 和工厂 `{factory}`。{(origin is null
  111. ? "向维护人员领取 HTTPS 地址并填写 client.env 的 INGRESS_BASE。"
  112. : $"专用 HTTPS 地址为 `{origin}`。")}
  113. 通过独立安全渠道领取 Access Key 和 Base64 签名密钥,再在本机环境变量设置 `ACCESS_KEY` 和 `SIGNING_KEY_BASE64`。
  114. 本地沙箱使用专用测试 CA 时,请先领取公钥证书,在示例中通过 `INGRESS_CA_FILE` 配置。
  115. 从解压目录选择一种语言执行。先设置 `IDEMPOTENCY_KEY` 为本次批次的唯一标识。
  116. | 语言 | 提交样例 |
  117. | --- | --- |
  118. | Python 3 | `python3 push.py send sample.ndjson` |
  119. | Node.js 18+ | `node push.mjs send sample.ndjson` |
  120. | .NET SDK 10 | `dotnet run --file Push.cs -- send sample.ndjson` |
  121. | Java 17+ | `java Push.java send sample.ndjson` |
  122. 可把 `sample.ndjson` 换成 `sample.json`。提交成功返回 202 和 `batchId`。
  123. 查询时把每条命令中的 `send sample.ndjson` 换成 `status <batchId>`。核对 `handoffStatus=confirmed`、
  124. `workerStatus`、确认行数和隔离行数。提交 202 表示原文已持久接收。
  125. 遇到 429 按响应 `Retry-After` 等待。重试保持原样例字节和幂等键,示例每次重算签名和 Nonce。接收返回 409 时核对同键的报文是否改变。
  126. `api-contract.json` 含限额、错误码与重试参数,`signature-vector.json` 提供公开测试向量。
  127. `openapi.json`、`row.schema.json` 和 `source.schema.json` 应放在同一目录使用。
  128. """;
  129. }