feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface
This commit is contained in:
1 parent
26a6b7318c
commit
03195bbbe5
12 files changed
+649
-9
No files matched your search
@@ -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("测试值");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user