feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface

This commit is contained in:
gitea committed 2026-10-15 11:00:18 +08:00
1 parent 26a6b7318c
commit 03195bbbe5
12 files changed
+649 -9

No files matched your search

+109
View File
@@ -405,4 +405,113 @@ describe("CLI - platform 命令与 record 动作", () => {
expect(execRes.stdout).toContain("已执行");
expect(editSpy).toHaveBeenCalled();
});
it("platform records 支持 --stats 画像统计(计算状态、重名与编码聚类)", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 3,
data: [
{ id: "r-1", dataLink: { id: "r-1", name: "场地A", code: "0-DT-2026-month-1", active: true } },
{ id: "r-2", dataLink: { id: "r-2", name: "场地A", code: "0-DT-2026-period-1", active: false } },
{ id: "r-3", dataLink: { id: "r-3", name: "场地B", code: "0-DT-2026-month-2", active: true } },
],
actions: [],
components: [],
path: null,
template: null,
})
);
// 1. 命令行表格输出测试
const textRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
dummyRuntime
);
expect(textRes.exitCode).toBe(0);
expect(textRes.stdout).toContain("宏观状态与数据画像");
expect(textRes.stdout).toContain("启用 2 条");
expect(textRes.stdout).toContain("停用 1 条");
expect(textRes.stdout).toContain("N-DT-N-month-N");
// 2. JSON 结构化输出测试
const jsonRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
{ ...dummyRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.total).toBe(3);
expect(parsed.activeCount).toBe(2);
expect(parsed.inactiveCount).toBe(1);
expect(parsed.duplicateNamesCount).toBe(1);
});
it("platform records 支持 --ndjson 流式逐行下发与 --flat 归一化", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 2,
data: [
{
id: "r-1",
dataLink: { id: "r-1", name: "项目1", code: "P1", active: true, customField: "测试值" },
},
{
id: "r-2",
dataLink: { id: "r-2", name: "项目2", code: "P2", active: false, customField: "停用值" },
},
],
actions: [],
components: [],
path: null,
template: null,
})
);
const streamedLines: string[] = [];
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
streamedLines.push(String(str));
return true;
});
spies.push(writeSpy);
const streamRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { ndjson: true },
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
},
dummyRuntime
);
expect(streamRes.exitCode).toBe(0);
expect(streamedLines.length).toBe(2);
const row1 = JSON.parse(streamedLines[0].trim());
expect(row1.id).toBe("r-1");
expect(row1.name).toBe("项目1");
expect(row1.code).toBe("P1");
expect(row1.active).toBe(true);
expect(row1.fields["自定义字段"]).toBe("测试值");
});
});
+3 -1
View File
@@ -28,7 +28,9 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "fields": return handleSchema(parsed, runtime);
case "records":
case "data":
case "search": return handleRecords(parsed, runtime);
case "search":
case "stats":
case "profile": return handleRecords(parsed, runtime);
case "audit":
case "check":
case "health": return handleAudit(parsed, runtime);
+95 -6
View File
@@ -3,8 +3,11 @@ import {
auditEntityRecords,
auditLedgerContinuityAndBaseline,
buildKeywordFilter,
calculateEntityRecordStats,
fetchAllEntityRecords,
filterRecordsByPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
searchEntityRecords,
selectRecordFields,
@@ -16,19 +19,100 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
const whereClause = stringOption(parsed.options, ["where"]);
const sumOption = stringOption(parsed.options, ["sum", "stats", "aggregate"]);
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
const isRaw = booleanOption(parsed.options, ["raw"], false);
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
const isAll = booleanOption(parsed.options, ["all", "a"], false);
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
const fetchAll = booleanOption(parsed.options, ["all", "a"], false) || Boolean(whereClause || sumOption);
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
const start = numberOption(parsed.options, ["start", "offset"], 0);
const count = numberOption(parsed.options, ["count", "limit"], 20);
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
if (isStream) {
let streamCount = 0;
const maxLimit = isAll ? Infinity : count;
for await (const rawRecord of iterateAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
)) {
if (whereClause) {
const matched = filterRecordsByPredicate([rawRecord], whereClause, resolved.entity);
if (matched.length === 0) continue;
}
let outputRecord: Record<string, unknown> = isRaw
? (rawRecord as Record<string, unknown>)
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
if (fields.length) {
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
}
process.stdout.write(JSON.stringify(outputRecord) + "\n");
streamCount++;
if (maxLimit !== undefined && streamCount >= maxLimit) break;
}
return { stdout: "", stderr: "", exitCode: 0 };
}
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
if (isProfileStats) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
);
let records = page.data;
if (whereClause) {
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
}
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
if (runtime.jsonMode) {
return { stdout: printJson(stats, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const patternRows: Array<Array<string | number>> = stats.codePatterns.map((p, idx) => [
idx + 1,
p.pattern,
p.sample,
p.count,
p.activeCount,
p.inactiveCount,
]);
const lines = [
`====== [${resolved.platform.name}] ${resolved.entity.name} 宏观状态与数据画像 (总数: ${stats.total}) ======`,
` - 状态分布: 🟢 启用 ${stats.activeCount} 条 (${stats.activeRate}) | 🔴 停用 ${stats.inactiveCount} 条`,
` - 名称画像: ${stats.uniqueNames} 个唯一名称 (其中 ${stats.duplicateNamesCount} 组存在重名,${stats.mixedStatusNamesCount} 组同时包含启用与停用)`,
` - 时间跨度: 最早创建 ${stats.earliestCreateTime || "-"} ~ 最晚更新 ${stats.latestUpdateTime || "-"}`,
"",
"── 编码结构与停用分布 ──",
printTable(["#", "编码模式", "样本", "总数", "启用数", "停用数"], patternRows),
];
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
const page = fetchAll
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
@@ -38,7 +122,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
}
// 1. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
if (sumOption) {
const sumFields = splitFields(sumOption);
const aggReport = aggregateRecordFields(data, resolved.entity, { fields: sumFields, groupBy });
@@ -84,7 +168,11 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 2. 常规记录查询模式
// 4. 常规记录查询模式 (支持 --flat 扁平归一化)
if (isFlat) {
data = data.map((item) => normalizeDatalinkRecord(item, resolved.entity) as unknown as Record<string, unknown>);
}
if (fields.length) {
data = data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields));
}
@@ -92,7 +180,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
const result = {
platform: resolved.platform,
entity: resolved.entity,
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields },
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
total: page.total,
returned: data.length,
data,
@@ -114,6 +202,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
}
export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
if (!resolved.entity) {
+1 -1
View File
@@ -41,7 +41,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all 全量拉取)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },