using System.IO.Compression; using System.Text; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; internal static class MdpPushKit { internal static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; private static readonly UTF8Encoding Utf8 = new(false); private static readonly string[] Clients = ["push.py", "push.mjs", "Push.cs", "Push.java"]; internal static byte[] Build(JsonElement contract, string factory, string? configuredOrigin) { var origin = HttpsOrigin(configuredOrigin); var dataset = Text(contract, "datasetKey"); var version = Text(contract, "schemaVersion"); var endpoint = Text(contract, "endpoint"); var status = Text(contract, "batchStatusEndpoint"); var samples = contract.GetProperty("samples"); using var output = new MemoryStream(); using (var zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true)) { AddJson("api-contract.json", contract); AddJson("row.schema.json", contract.GetProperty("rowSchema")); Add("source.schema.json", Text(contract, "schemaJson")); Add("sample.json", Text(samples, "json")); Add("sample.ndjson", Text(samples, "ndjson")); AddJson("signature-vector.json", contract.GetProperty("signatureVector")); AddJson("openapi.json", OpenApi(dataset, version, endpoint, status, origin)); Add("client.env", $"INGRESS_BASE={origin}\nDATASET_ENDPOINT={endpoint}\nFACTORY_ID={factory}\nSCHEMA_VERSION={version}\n"); var assembly = typeof(MdpPushKit).Assembly; foreach (var client in Clients) { using var input = assembly.GetManifestResourceStream("MdpPushKit." + client) ?? throw new InvalidOperationException("Missing API push kit client."); using var entry = zip.CreateEntry(client).Open(); input.CopyTo(entry); } Add("README.md", Guide(dataset, version, factory, origin)); void AddJson(string file, object value) => Add(file, JsonSerializer.Serialize(value, JsonOptions)); void Add(string file, string contents) { using var writer = new StreamWriter(zip.CreateEntry(file).Open(), Utf8); writer.Write(contents); } } return output.ToArray(); } internal static string FileName(string dataset, string version) => $"{Safe(dataset)}.{Safe(version)}.push-kit.zip"; private static string Safe(string value) => new(value.Select(character => char.IsAsciiLetterOrDigit(character) || character is '.' or '_' or '-' ? character : '_').ToArray()); private static string Text(JsonElement value, string name) => value.GetProperty(name).GetString()!; private static string? HttpsOrigin(string? configured) => Uri.TryCreate(configured, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps && uri.UserInfo.Length == 0 && uri.AbsolutePath == "/" && uri.Query.Length == 0 && uri.Fragment.Length == 0 ? uri.GetLeftPart(UriPartial.Authority) : null; private static object OpenApi(string dataset, string version, string endpoint, string status, string? origin) { var auth = new[] { "X-Access-Key", "X-Timestamp", "X-Nonce", "X-Content-SHA256", "X-Signature", "X-Signature-Version" }.Select(name => Parameter(name, "header")).ToArray(); var receive = new { operationId = "pushDataset", parameters = auth.Concat([Parameter("Idempotency-Key", "header"), Parameter("X-Schema-Version", "header"), Parameter("X-Factory-Id", "header", false, "NDJSON 多工厂授权使用此头。JSON 使用信封中的 factoryId。")]), requestBody = new { required = true, content = new Dictionary { ["application/json"] = new { schema = new { type = "object", required = new[] { "data" }, properties = new { factoryId = new { type = "string" }, data = new { type = "object", required = new[] { "list" }, properties = new { list = new { type = "array", minItems = 1, maxItems = 100, items = new Dictionary { ["$ref"] = "./row.schema.json" } } } } } } }, ["application/x-ndjson"] = new { schema = new { type = "string" }, example = "See sample.ndjson", description = "One row per line. Row schema is row.schema.json." } } }, responses = Responses("202", "已持久接收。保留 batchId 以查询处理结果。") }; return new { openapi = "3.1.0", info = new { title = dataset + " API 推送", version }, servers = origin is null ? Array.Empty() : [new { url = origin }], paths = new Dictionary { [endpoint] = new { post = receive }, [status] = new { get = new { operationId = "getBatchStatus", parameters = auth.Concat([Parameter("batchId", "path"), Parameter("X-Factory-Id", "header", false, "多工厂授权查询时填写。")]), responses = Responses("200", "批次处理及交接状态。") } } } }; static object Parameter(string name, string location, bool required = true, string? description = null) { var parameter = new Dictionary { ["name"] = name, ["in"] = location, ["required"] = required, ["schema"] = new { type = "string" } }; if (description is not null) parameter["description"] = description; return parameter; } static Dictionary Responses(string success, string description) => new() { [success] = new { description }, ["default"] = new { description = "返回诊断码及请求追踪号。见 api-contract.json。" } }; } private static string Guide(string dataset, string version, string factory, string? origin) => $""" # {dataset} 推送接入 此包对应 Schema `{version}` 和工厂 `{factory}`。{(origin is null ? "向维护人员领取 HTTPS 地址并填写 client.env 的 INGRESS_BASE。" : $"专用 HTTPS 地址为 `{origin}`。")} 通过独立安全渠道领取 Access Key 和 Base64 签名密钥,再在本机环境变量设置 `ACCESS_KEY` 和 `SIGNING_KEY_BASE64`。 本地沙箱使用专用测试 CA 时,请先领取公钥证书,在示例中通过 `INGRESS_CA_FILE` 配置。 从解压目录选择一种语言执行。先设置 `IDEMPOTENCY_KEY` 为本次批次的唯一标识。 | 语言 | 提交样例 | | --- | --- | | Python 3 | `python3 push.py send sample.ndjson` | | Node.js 18+ | `node push.mjs send sample.ndjson` | | .NET SDK 10 | `dotnet run --file Push.cs -- send sample.ndjson` | | Java 17+ | `java Push.java send sample.ndjson` | 可把 `sample.ndjson` 换成 `sample.json`。提交成功返回 202 和 `batchId`。 查询时把每条命令中的 `send sample.ndjson` 换成 `status `。核对 `handoffStatus=confirmed`、 `workerStatus`、确认行数和隔离行数。提交 202 表示原文已持久接收。 遇到 429 按响应 `Retry-After` 等待。重试保持原样例字节和幂等键,示例每次重算签名和 Nonce。接收返回 409 时核对同键的报文是否改变。 `api-contract.json` 含限额、错误码与重试参数,`signature-vector.json` 提供公开测试向量。 `openapi.json`、`row.schema.json` 和 `source.schema.json` 应放在同一目录使用。 """; }