feat(api): expose REST-only agent routes
This commit is contained in:
@@ -2,7 +2,7 @@ import { CliError } from "../core/errors.js";
|
||||
import { emitApi, requestJson } from "../core/http.js";
|
||||
import { assignDatasetKeys, parseBurstFile, parseValveSettingFile } from "../core/files.js";
|
||||
import { optionalNumber, optionalString, optionalStringArray, parseOptions, requiredNumber, requiredString, validateChoice } from "../core/options.js";
|
||||
import { requireNetwork, requireUsername, resolveScheme } from "../core/runtime.js";
|
||||
import { resolveScheme } from "../core/runtime.js";
|
||||
import { parseTime } from "../core/time.js";
|
||||
import { success } from "../core/output.js";
|
||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||
@@ -12,17 +12,16 @@ function analysisBurst(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const [ids, sizes] = parseBurstFile(requiredString(values, "burst-file"));
|
||||
const schemeName = resolveScheme(ctx, optionalString(values, "scheme"), true)!;
|
||||
return emitApi(ctx, "爆管分析执行成功", {
|
||||
method: "GET",
|
||||
path: "/burst-analysis",
|
||||
method: "POST",
|
||||
path: "/burst-analyses",
|
||||
params: {
|
||||
network: requireNetwork(ctx),
|
||||
modify_pattern_start_time: parseTime(requiredString(values, "start-time"), "--start-time"),
|
||||
burst_ID: ids,
|
||||
burst_id: ids,
|
||||
burst_size: sizes,
|
||||
modify_total_duration: requiredNumber(values, "duration"),
|
||||
scheme_name: schemeName,
|
||||
},
|
||||
requireNetworkCtx: true,
|
||||
requireProject: true,
|
||||
}, [`tjwater-cli data scheme get --name ${schemeName}`, "tjwater-cli data scheme list"]);
|
||||
}
|
||||
|
||||
@@ -34,25 +33,24 @@ function analysisValve(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const startTime = optionalString(values, "start-time");
|
||||
if (!startTime || !valves) throw new CliError("CLI 参数错误", "INVALID_VALVE_CLOSE_ARGS", "close mode requires --start-time and at least one --valve", 2);
|
||||
return emitApi(ctx, "阀门关闭分析执行成功", {
|
||||
method: "GET",
|
||||
path: "/valve_close_analysis/",
|
||||
method: "POST",
|
||||
path: "/valve-isolation-analyses",
|
||||
params: {
|
||||
network: requireNetwork(ctx),
|
||||
start_time: parseTime(startTime, "--start-time"),
|
||||
valves,
|
||||
duration: optionalNumber(values, "duration") || 900,
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
},
|
||||
requireNetworkCtx: true,
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
const elements = optionalStringArray(values, "element");
|
||||
if (!elements) throw new CliError("CLI 参数错误", "INVALID_VALVE_ISOLATION_ARGS", "isolation mode requires at least one --element", 2);
|
||||
return emitApi(ctx, "阀门隔离分析执行成功", {
|
||||
method: "GET",
|
||||
path: "/valve-isolation-analysis",
|
||||
params: { network: requireNetwork(ctx), accident_element: elements, disabled_valves: optionalStringArray(values, "disabled-valve") },
|
||||
requireNetworkCtx: true,
|
||||
method: "POST",
|
||||
path: "/valve-isolation-analyses",
|
||||
params: { accident_element: elements, disabled_valves: optionalStringArray(values, "disabled-valve") },
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -60,36 +58,34 @@ function analysisFlushing(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv, { flow: "number", duration: "integer" });
|
||||
const [valves, openings] = parseValveSettingFile(requiredString(values, "valve-setting-file"));
|
||||
return emitApi(ctx, "冲洗分析执行成功", {
|
||||
method: "GET",
|
||||
path: "/flushing-analysis",
|
||||
method: "POST",
|
||||
path: "/flushing-analyses",
|
||||
params: {
|
||||
network: requireNetwork(ctx),
|
||||
start_time: parseTime(requiredString(values, "start-time"), "--start-time"),
|
||||
valves,
|
||||
valves_k: openings,
|
||||
drainage_node_ID: requiredString(values, "drainage-node"),
|
||||
drainage_node_id: requiredString(values, "drainage-node"),
|
||||
flush_flow: requiredNumber(values, "flow"),
|
||||
duration: optionalNumber(values, "duration") || 900,
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
},
|
||||
requireNetworkCtx: true,
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
|
||||
function analysisAge(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv, { duration: "integer" });
|
||||
return emitApi(ctx, "水龄分析执行成功", {
|
||||
method: "GET",
|
||||
path: "/age_analysis/",
|
||||
params: { network: requireNetwork(ctx), start_time: parseTime(requiredString(values, "start-time"), "--start-time"), duration: requiredNumber(values, "duration") },
|
||||
requireNetworkCtx: true,
|
||||
method: "POST",
|
||||
path: "/water-age-analyses",
|
||||
params: { start_time: parseTime(requiredString(values, "start-time"), "--start-time"), duration: requiredNumber(values, "duration") },
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
|
||||
function analysisContaminant(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv, { duration: "integer", concentration: "number" });
|
||||
const params: Record<string, unknown> = {
|
||||
network: requireNetwork(ctx),
|
||||
start_time: parseTime(requiredString(values, "start-time"), "--start-time"),
|
||||
source: requiredString(values, "source-node"),
|
||||
concentration: requiredNumber(values, "concentration"),
|
||||
@@ -98,55 +94,50 @@ function analysisContaminant(ctx: RuntimeContext, argv: string[]): Promise<void>
|
||||
};
|
||||
const pattern = optionalString(values, "pattern");
|
||||
if (pattern) params.pattern = pattern;
|
||||
return emitApi(ctx, "污染物模拟执行成功", { method: "GET", path: "/contaminant-simulation", params, requireNetworkCtx: true });
|
||||
return emitApi(ctx, "污染物模拟执行成功", { method: "POST", path: "/contaminant-simulations", params, requireProject: true });
|
||||
}
|
||||
|
||||
function sensorKmeans(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv, { count: "integer", "min-diameter": "integer" });
|
||||
return emitApi(ctx, "传感器选址执行成功", {
|
||||
method: "POST",
|
||||
path: "/pressure_sensor_placement_kmeans/",
|
||||
path: "/pressure-sensor-placement-kmeans",
|
||||
body: {
|
||||
name: requireNetwork(ctx),
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
sensor_number: requiredNumber(values, "count"),
|
||||
min_diameter: optionalNumber(values, "min-diameter") || 0,
|
||||
username: requireUsername(ctx),
|
||||
},
|
||||
requireNetworkCtx: true,
|
||||
requireUsernameCtx: true,
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
|
||||
function schemeAnalysis(ctx: RuntimeContext, argv: string[], summary: string, path: string, networkKey: string, startKey: string, endKey: string): Promise<void> {
|
||||
function schemeAnalysis(ctx: RuntimeContext, argv: string[], summary: string, path: string, startKey: string, endKey: string): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, summary, {
|
||||
method: "POST",
|
||||
path,
|
||||
body: {
|
||||
[networkKey]: requireNetwork(ctx),
|
||||
[startKey]: parseTime(requiredString(values, "start-time"), "--start-time"),
|
||||
[endKey]: parseTime(requiredString(values, "end-time"), "--end-time"),
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
},
|
||||
requireNetworkCtx: true,
|
||||
requireProject: true,
|
||||
});
|
||||
}
|
||||
|
||||
function schemeList(ctx: RuntimeContext, summary: string, path: string): Promise<void> {
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { network: requireNetwork(ctx) }, requireNetworkCtx: true });
|
||||
function schemeList(ctx: RuntimeContext, summary: string, schemeType: string): Promise<void> {
|
||||
return emitApi(ctx, summary, { method: "GET", path: "/schemes", params: { scheme_type: schemeType }, requireProject: true });
|
||||
}
|
||||
|
||||
function schemeGet(ctx: RuntimeContext, argv: string[], summary: string, path: string): Promise<void> {
|
||||
function schemeGet(ctx: RuntimeContext, argv: string[], summary: string, schemeType: string): Promise<void> {
|
||||
const { positionals } = parseOptions(argv);
|
||||
if (!positionals[0]) throw new CliError("CLI 参数错误", "MISSING_ARGUMENT", "Missing argument 'SCHEME_NAME'", 2);
|
||||
return emitApi(ctx, summary, { method: "GET", path: `${path}${positionals[0]}`, params: { network: requireNetwork(ctx) }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, summary, { method: "GET", path: `/schemes/${positionals[0]}`, params: { scheme_type: schemeType }, requireProject: true });
|
||||
}
|
||||
|
||||
function burstLocation(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv, { "burst-leakage": "number", "pressure-scada-id": "repeat", "flow-scada-id": "repeat", "use-scada-flow": "boolean" });
|
||||
const body: Record<string, unknown> = {
|
||||
network: requireNetwork(ctx),
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
data_source: optionalString(values, "data-source") || "monitoring",
|
||||
scada_burst_start: parseTime(requiredString(values, "start-time"), "--start-time"),
|
||||
@@ -162,18 +153,17 @@ function burstLocation(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const flowFile = optionalString(values, "flow-file");
|
||||
if (pressureFile) assignDatasetKeys(body, pressureFile, ["burst_pressure", "normal_pressure"], "pressure");
|
||||
if (flowFile) assignDatasetKeys(body, flowFile, ["burst_flow", "normal_flow"], "flow");
|
||||
return emitApi(ctx, "爆管定位执行成功", { method: "POST", path: "/burst-location/locate/", body, requireNetworkCtx: true });
|
||||
return emitApi(ctx, "爆管定位执行成功", { method: "POST", path: "/burst-locations", body, requireProject: true });
|
||||
}
|
||||
|
||||
function riskPipe(ctx: RuntimeContext, argv: string[], summary: string, path: string): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { network: requireNetwork(ctx), pipe_id: requiredString(values, "pipe") }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { pipe_id: requiredString(values, "pipe") }, requireProject: true });
|
||||
}
|
||||
|
||||
async function riskNetwork(ctx: RuntimeContext): Promise<void> {
|
||||
const network = requireNetwork(ctx);
|
||||
const [probabilities, a] = await requestJson(ctx, { method: "GET", path: "/getnetworkpiperiskprobabilitynow/", params: { network }, requireNetworkCtx: true });
|
||||
const [geometries, b] = await requestJson(ctx, { method: "GET", path: "/getpiperiskprobabilitygeometries/", params: { network }, requireNetworkCtx: true });
|
||||
const [probabilities, a] = await requestJson(ctx, { method: "GET", path: "/network-pipe-risk-probability-nows", requireProject: true });
|
||||
const [geometries, b] = await requestJson(ctx, { method: "GET", path: "/pipes/risk-probability-geometries", requireProject: true });
|
||||
success("读取全网风险成功", { probabilities, geometries }, ctx, a + b);
|
||||
}
|
||||
|
||||
@@ -184,16 +174,16 @@ export const analysisHandlers: HandlerMap = {
|
||||
"analysis age": analysisAge,
|
||||
"analysis contaminant": analysisContaminant,
|
||||
"analysis sensor-placement kmeans": sensorKmeans,
|
||||
"analysis leakage identify": (ctx, argv) => schemeAnalysis(ctx, argv, "漏损识别执行成功", "/leakage/identify/", "network", "scada_start", "scada_end"),
|
||||
"analysis leakage schemes list": (ctx) => schemeList(ctx, "读取漏损方案列表成功", "/leakage/schemes/"),
|
||||
"analysis leakage schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取漏损方案详情成功", "/leakage/schemes/"),
|
||||
"analysis burst-detection detect": (ctx, argv) => schemeAnalysis(ctx, argv, "爆管检测执行成功", "/burst-detection/detect/", "network", "scada_start", "scada_end"),
|
||||
"analysis burst-detection schemes list": (ctx) => schemeList(ctx, "读取爆管检测方案列表成功", "/burst-detection/schemes/"),
|
||||
"analysis burst-detection schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取爆管检测方案详情成功", "/burst-detection/schemes/"),
|
||||
"analysis leakage identify": (ctx, argv) => schemeAnalysis(ctx, argv, "漏损识别执行成功", "/leakage-identifications", "scada_start", "scada_end"),
|
||||
"analysis leakage schemes list": (ctx) => schemeList(ctx, "读取漏损方案列表成功", "dma_leak_identification"),
|
||||
"analysis leakage schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取漏损方案详情成功", "dma_leak_identification"),
|
||||
"analysis burst-detection detect": (ctx, argv) => schemeAnalysis(ctx, argv, "爆管检测执行成功", "/burst-detections", "scada_start", "scada_end"),
|
||||
"analysis burst-detection schemes list": (ctx) => schemeList(ctx, "读取爆管检测方案列表成功", "burst_detection"),
|
||||
"analysis burst-detection schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取爆管检测方案详情成功", "burst_detection"),
|
||||
"analysis burst-location locate": burstLocation,
|
||||
"analysis burst-location schemes list": (ctx) => schemeList(ctx, "读取爆管定位方案列表成功", "/burst-location/schemes/"),
|
||||
"analysis burst-location schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取爆管定位方案详情成功", "/burst-location/schemes/"),
|
||||
"analysis risk pipe-now": (ctx, argv) => riskPipe(ctx, argv, "读取当前管道风险成功", "/getpiperiskprobabilitynow/"),
|
||||
"analysis risk pipe-history": (ctx, argv) => riskPipe(ctx, argv, "读取历史管道风险成功", "/getpiperiskprobability/"),
|
||||
"analysis burst-location schemes list": (ctx) => schemeList(ctx, "读取爆管定位方案列表成功", "burst_location"),
|
||||
"analysis burst-location schemes get": (ctx, argv) => schemeGet(ctx, argv, "读取爆管定位方案详情成功", "burst_location"),
|
||||
"analysis risk pipe-now": (ctx, argv) => riskPipe(ctx, argv, "读取当前管道风险成功", "/pipes/risk-probability-now"),
|
||||
"analysis risk pipe-history": (ctx, argv) => riskPipe(ctx, argv, "读取历史管道风险成功", "/pipes/risk-probability"),
|
||||
"analysis risk network": riskNetwork,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { CliError } from "../core/errors.js";
|
||||
import { emitApi } from "../core/http.js";
|
||||
import { optionalString, parseOptions, requiredString, validateChoice } from "../core/options.js";
|
||||
import { requireNetwork } from "../core/runtime.js";
|
||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||
|
||||
type ComponentKind = "time" | "energy" | "pump-energy" | "network";
|
||||
@@ -10,22 +9,22 @@ function componentOption(ctx: RuntimeContext, argv: string[], schema: boolean):
|
||||
const { values } = parseOptions(argv);
|
||||
const kind = validateChoice(requiredString(values, "kind"), ["time", "energy", "pump-energy", "network"] as const, "--kind");
|
||||
const routes: Record<`${ComponentKind}:${boolean}`, string> = {
|
||||
"time:true": "/gettimeschema",
|
||||
"time:false": "/gettimeproperties/",
|
||||
"energy:true": "/getenergyschema/",
|
||||
"energy:false": "/getenergyproperties/",
|
||||
"pump-energy:true": "/getpumpenergyschema/",
|
||||
"pump-energy:false": "/getpumpenergyproperties//",
|
||||
"network:true": "/getoptionschema/",
|
||||
"network:false": "/getoptionproperties/",
|
||||
"time:true": "/network-schemas/time",
|
||||
"time:false": "/network-options/time",
|
||||
"energy:true": "/network-schemas/energy",
|
||||
"energy:false": "/network-options/energy",
|
||||
"pump-energy:true": "/network-schemas/pump-energy",
|
||||
"pump-energy:false": "/network-options/pump-energy",
|
||||
"network:true": "/network-schemas/option",
|
||||
"network:false": "/network-options",
|
||||
};
|
||||
const params: Record<string, unknown> = { network: requireNetwork(ctx) };
|
||||
const params: Record<string, unknown> = {};
|
||||
const pump = optionalString(values, "pump");
|
||||
if (kind === "pump-energy") {
|
||||
if (!schema && !pump) throw new CliError("CLI 参数错误", "PUMP_REQUIRED", "--pump is required when --kind pump-energy", 2);
|
||||
if (pump) params.pump = pump;
|
||||
}
|
||||
return emitApi(ctx, schema ? "读取选项 schema 成功" : "读取选项属性成功", { method: "GET", path: routes[`${kind}:${schema}`], params, requireNetworkCtx: true });
|
||||
return emitApi(ctx, schema ? "读取选项 schema 成功" : "读取选项属性成功", { method: "GET", path: routes[`${kind}:${schema}`], params, requireProject: true });
|
||||
}
|
||||
|
||||
export const componentHandlers: HandlerMap = {
|
||||
|
||||
+23
-19
@@ -2,7 +2,7 @@ import { SCADA_FIELDS, type ElementType } from "../core/constants.js";
|
||||
import { CliError } from "../core/errors.js";
|
||||
import { emitApi } from "../core/http.js";
|
||||
import { fieldsFor, optionalString, parseOptions, requiredString, requiredStringArray, validateChoice } from "../core/options.js";
|
||||
import { requireNetwork, resolveScheme } from "../core/runtime.js";
|
||||
import { resolveScheme } from "../core/runtime.js";
|
||||
import { parseTime } from "../core/time.js";
|
||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||
|
||||
@@ -20,7 +20,7 @@ function realtimeByIdTime(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, "读取实时模拟数据成功", {
|
||||
method: "GET",
|
||||
path: "/realtime/query/by-id-time",
|
||||
path: "/timeseries/realtime/simulation-results",
|
||||
params: { id: requiredString(values, "id"), type: validateChoice(requiredString(values, "type"), ["pipe", "junction"] as const, "--type"), query_time: parseTime(requiredString(values, "time"), "--time") },
|
||||
requireProject: true,
|
||||
});
|
||||
@@ -31,7 +31,7 @@ function realtimeByTimeProperty(ctx: RuntimeContext, argv: string[]): Promise<vo
|
||||
const type = validateChoice(requiredString(values, "type"), ["pipe", "junction"] as const, "--type");
|
||||
return emitApi(ctx, "读取实时属性聚合数据成功", {
|
||||
method: "GET",
|
||||
path: "/realtime/query/by-time-property",
|
||||
path: "/timeseries/realtime/records",
|
||||
params: { type, query_time: parseTime(requiredString(values, "time"), "--time"), property: validateChoice(requiredString(values, "property"), fieldsFor(type), "--property") },
|
||||
requireProject: true,
|
||||
});
|
||||
@@ -41,7 +41,7 @@ function schemeLinks(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, "读取方案管道数据成功", {
|
||||
method: "GET",
|
||||
path: "/scheme/links",
|
||||
path: "/timeseries/schemes/links",
|
||||
params: {
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
scheme_type: optionalString(values, "scheme-type") || "simulation",
|
||||
@@ -56,7 +56,7 @@ function schemeNodeField(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, "读取方案节点字段成功", {
|
||||
method: "GET",
|
||||
path: `/scheme/nodes/${requiredString(values, "node")}/field`,
|
||||
path: `/timeseries/schemes/nodes/${requiredString(values, "node")}/field`,
|
||||
params: {
|
||||
field: validateChoice(requiredString(values, "field"), fieldsFor("junction"), "--field"),
|
||||
scheme_name: resolveScheme(ctx, optionalString(values, "scheme"), true),
|
||||
@@ -80,10 +80,10 @@ function schemeSimulation(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
};
|
||||
if (query === "by-id-time") {
|
||||
params.id = requiredString(values, "id");
|
||||
return emitApi(ctx, "读取方案单点模拟数据成功", { method: "GET", path: "/scheme/query/by-id-time", params, requireProject: true });
|
||||
return emitApi(ctx, "读取方案单点模拟数据成功", { method: "GET", path: "/timeseries/schemes/simulation-results", params, requireProject: true });
|
||||
}
|
||||
params.property = validateChoice(requiredString(values, "property"), fieldsFor(type), "--property");
|
||||
return emitApi(ctx, "读取方案属性聚合数据成功", { method: "GET", path: "/scheme/query/by-scheme-time-property", params, requireProject: true });
|
||||
return emitApi(ctx, "读取方案属性聚合数据成功", { method: "GET", path: "/timeseries/schemes/records", params, requireProject: true });
|
||||
}
|
||||
|
||||
function scadaQuery(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
@@ -95,7 +95,7 @@ function scadaQuery(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
};
|
||||
const field = optionalString(values, "field");
|
||||
if (field) params.field = validateChoice(field, SCADA_FIELDS, "--field");
|
||||
return emitApi(ctx, "读取 SCADA 时序成功", { method: "GET", path: field ? "/scada/by-ids-field-time-range" : "/scada/by-ids-time-range", params, requireProject: true });
|
||||
return emitApi(ctx, "读取 SCADA 时序成功", { method: "GET", path: field ? "/timeseries/scada-readings/fields" : "/timeseries/scada-readings", params, requireProject: true });
|
||||
}
|
||||
|
||||
function composite(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
@@ -115,7 +115,12 @@ function composite(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
params.element_id = feature[0];
|
||||
params.use_cleaned = Boolean(values["use-cleaned"]);
|
||||
}
|
||||
return emitApi(ctx, kind === "scada-simulation" ? "读取复合 SCADA-模拟数据成功" : kind === "element-simulation" ? "读取复合元素模拟数据成功" : "读取元素关联 SCADA 数据成功", { method: "GET", path: `/composite/${kind}`, params, requireProject: true });
|
||||
const paths = {
|
||||
"scada-simulation": "/timeseries/views/scada-simulations",
|
||||
"element-simulation": "/timeseries/views/element-simulations",
|
||||
"element-scada": "/timeseries/views/element-scada-readings",
|
||||
} as const;
|
||||
return emitApi(ctx, kind === "scada-simulation" ? "读取复合 SCADA-模拟数据成功" : kind === "element-simulation" ? "读取复合元素模拟数据成功" : "读取元素关联 SCADA 数据成功", { method: "GET", path: paths[kind], params, requireProject: true });
|
||||
}
|
||||
|
||||
function pipelineHealth(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
@@ -124,33 +129,32 @@ function pipelineHealth(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
requiredString(values, "start-time");
|
||||
return emitApi(ctx, "读取管道健康预测成功", {
|
||||
method: "GET",
|
||||
path: "/composite/pipeline-health-prediction",
|
||||
params: { network_name: requireNetwork(ctx), query_time: parseTime(requiredString(values, "end-time"), "--end-time") },
|
||||
path: "/pipeline-health-predictions",
|
||||
params: { query_time: parseTime(requiredString(values, "end-time"), "--end-time") },
|
||||
requireProject: true,
|
||||
requireNetworkCtx: true,
|
||||
});
|
||||
}
|
||||
|
||||
function dataScadaGet(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
validateChoice(requiredString(values, "kind"), ["info"] as const, "--kind");
|
||||
return emitApi(ctx, "读取 SCADA 数据成功", { method: "GET", path: "/getscadainfo/", params: { network: requireNetwork(ctx), id: requiredString(values, "id") }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, "读取 SCADA 数据成功", { method: "GET", path: "/scada-info/detail", params: { id: requiredString(values, "id") }, requireProject: true });
|
||||
}
|
||||
|
||||
function dataScadaList(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
validateChoice(requiredString(values, "kind"), ["info"] as const, "--kind");
|
||||
return emitApi(ctx, "读取 SCADA 列表成功", { method: "GET", path: "/getallscadainfo/", params: { network: requireNetwork(ctx) }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, "读取 SCADA 列表成功", { method: "GET", path: "/scada-info", requireProject: true });
|
||||
}
|
||||
|
||||
function dataSchemeGet(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, "读取方案成功", { method: "GET", path: "/getscheme/", params: { network: requireNetwork(ctx), schema_name: requiredString(values, "name") }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, "读取方案成功", { method: "GET", path: "/schemes/detail", params: { schema_name: requiredString(values, "name") }, requireProject: true });
|
||||
}
|
||||
|
||||
export const dataHandlers: HandlerMap = {
|
||||
"data timeseries realtime links": (ctx, argv) => rangeGet(ctx, argv, "读取实时管道数据成功", "/realtime/links"),
|
||||
"data timeseries realtime nodes": (ctx, argv) => rangeGet(ctx, argv, "读取实时节点数据成功", "/realtime/nodes"),
|
||||
"data timeseries realtime links": (ctx, argv) => rangeGet(ctx, argv, "读取实时管道数据成功", "/timeseries/realtime/links"),
|
||||
"data timeseries realtime nodes": (ctx, argv) => rangeGet(ctx, argv, "读取实时节点数据成功", "/timeseries/realtime/nodes"),
|
||||
"data timeseries realtime simulation-by-id-time": realtimeByIdTime,
|
||||
"data timeseries realtime simulation-by-time-property": realtimeByTimeProperty,
|
||||
"data timeseries scheme links": schemeLinks,
|
||||
@@ -161,7 +165,7 @@ export const dataHandlers: HandlerMap = {
|
||||
"data timeseries composite pipeline-health": pipelineHealth,
|
||||
"data scada get": dataScadaGet,
|
||||
"data scada list": dataScadaList,
|
||||
"data scheme schema": (ctx) => emitApi(ctx, "读取方案 schema 成功", { method: "GET", path: "/getschemeschema/", params: { network: requireNetwork(ctx) }, requireNetworkCtx: true }),
|
||||
"data scheme schema": (ctx) => emitApi(ctx, "读取方案 schema 成功", { method: "GET", path: "/network-schemas/scheme", requireProject: true }),
|
||||
"data scheme get": dataSchemeGet,
|
||||
"data scheme list": (ctx) => emitApi(ctx, "读取方案列表成功", { method: "GET", path: "/schemes", params: { network: requireNetwork(ctx) }, requireNetworkCtx: true }),
|
||||
"data scheme list": (ctx) => emitApi(ctx, "读取方案列表成功", { method: "GET", path: "/schemes", requireProject: true }),
|
||||
};
|
||||
|
||||
+15
-16
@@ -1,27 +1,26 @@
|
||||
import { emitApi } from "../core/http.js";
|
||||
import { parseOptions, requiredString } from "../core/options.js";
|
||||
import { requireNetwork } from "../core/runtime.js";
|
||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||
|
||||
function legacyGet(ctx: RuntimeContext, argv: string[], summary: string, path: string, key: string): Promise<void> {
|
||||
function apiGet(ctx: RuntimeContext, argv: string[], summary: string, path: string, key: string): Promise<void> {
|
||||
const { values } = parseOptions(argv);
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { network: requireNetwork(ctx), [key]: requiredString(values, key) }, requireNetworkCtx: true });
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { [key]: requiredString(values, key) }, requireProject: true });
|
||||
}
|
||||
|
||||
function legacyGetAll(ctx: RuntimeContext, summary: string, path: string): Promise<void> {
|
||||
return emitApi(ctx, summary, { method: "GET", path, params: { network: requireNetwork(ctx) }, requireNetworkCtx: true });
|
||||
function apiGetAll(ctx: RuntimeContext, summary: string, path: string): Promise<void> {
|
||||
return emitApi(ctx, summary, { method: "GET", path, requireProject: true });
|
||||
}
|
||||
|
||||
export const networkHandlers: HandlerMap = {
|
||||
"network get-junction-properties": (ctx, argv) => legacyGet(ctx, argv, "读取节点属性成功", "/getjunctionproperties/", "junction"),
|
||||
"network get-pipe-properties": (ctx, argv) => legacyGet(ctx, argv, "读取管道属性成功", "/getpipeproperties/", "pipe"),
|
||||
"network get-all-pipes-properties": (ctx) => legacyGetAll(ctx, "读取全部管道属性成功", "/getallpipeproperties/"),
|
||||
"network get-reservoir-properties": (ctx, argv) => legacyGet(ctx, argv, "读取水库属性成功", "/getreservoirproperties/", "reservoir"),
|
||||
"network get-all-reservoirs-properties": (ctx) => legacyGetAll(ctx, "读取全部水库属性成功", "/getallreservoirproperties/"),
|
||||
"network get-tank-properties": (ctx, argv) => legacyGet(ctx, argv, "读取水箱属性成功", "/gettankproperties/", "tank"),
|
||||
"network get-all-tanks-properties": (ctx) => legacyGetAll(ctx, "读取全部水箱属性成功", "/getalltankproperties/"),
|
||||
"network get-pump-properties": (ctx, argv) => legacyGet(ctx, argv, "读取水泵属性成功", "/getpumpproperties/", "pump"),
|
||||
"network get-all-pumps-properties": (ctx) => legacyGetAll(ctx, "读取全部水泵属性成功", "/getallpumpproperties/"),
|
||||
"network get-valve-properties": (ctx, argv) => legacyGet(ctx, argv, "读取阀门属性成功", "/getvalveproperties/", "valve"),
|
||||
"network get-all-valves-properties": (ctx) => legacyGetAll(ctx, "读取全部阀门属性成功", "/getallvalveproperties/"),
|
||||
"network get-junction-properties": (ctx, argv) => apiGet(ctx, argv, "读取节点属性成功", "/junctions/properties", "junction"),
|
||||
"network get-pipe-properties": (ctx, argv) => apiGet(ctx, argv, "读取管道属性成功", "/pipes/properties", "pipe"),
|
||||
"network get-all-pipes-properties": (ctx) => apiGetAll(ctx, "读取全部管道属性成功", "/pipes"),
|
||||
"network get-reservoir-properties": (ctx, argv) => apiGet(ctx, argv, "读取水库属性成功", "/reservoirs/properties", "reservoir"),
|
||||
"network get-all-reservoirs-properties": (ctx) => apiGetAll(ctx, "读取全部水库属性成功", "/reservoirs"),
|
||||
"network get-tank-properties": (ctx, argv) => apiGet(ctx, argv, "读取水箱属性成功", "/tanks/properties", "tank"),
|
||||
"network get-all-tanks-properties": (ctx) => apiGetAll(ctx, "读取全部水箱属性成功", "/tanks"),
|
||||
"network get-pump-properties": (ctx, argv) => apiGet(ctx, argv, "读取水泵属性成功", "/pumps/properties", "pump"),
|
||||
"network get-all-pumps-properties": (ctx) => apiGetAll(ctx, "读取全部水泵属性成功", "/pumps"),
|
||||
"network get-valve-properties": (ctx, argv) => apiGet(ctx, argv, "读取阀门属性成功", "/valves/properties", "valve"),
|
||||
"network get-all-valves-properties": (ctx) => apiGetAll(ctx, "读取全部阀门属性成功", "/valves"),
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { emitApi } from "../core/http.js";
|
||||
import { parseOptions, requiredNumber, requiredString } from "../core/options.js";
|
||||
import { requireNetwork } from "../core/runtime.js";
|
||||
import { addMinutesPreservingOffset, parseTime } from "../core/time.js";
|
||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||
|
||||
@@ -9,11 +8,10 @@ function simulationRun(ctx: RuntimeContext, argv: string[]): Promise<void> {
|
||||
const start = parseTime(requiredString(values, "start-time"), "--start-time");
|
||||
const duration = requiredNumber(values, "duration");
|
||||
const end = addMinutesPreservingOffset(start, duration);
|
||||
const network = requireNetwork(ctx);
|
||||
return emitApi(
|
||||
ctx,
|
||||
"触发模拟成功",
|
||||
{ method: "POST", path: "/simulations/run-by-date", body: { name: network, start_time: start.replace(/\.\d+/, ""), duration }, requireNetworkCtx: true },
|
||||
{ method: "POST", path: "/simulation-runs", body: { start_time: start.replace(/\.\d+/, ""), duration }, requireProject: true },
|
||||
[
|
||||
`tjwater-cli data timeseries realtime links --start-time ${start} --end-time ${end}`,
|
||||
`tjwater-cli data timeseries realtime nodes --start-time ${start} --end-time ${end}`,
|
||||
|
||||
@@ -20,10 +20,10 @@ export function readJsonFile(path: string, label: string): unknown {
|
||||
export function parseBurstFile(path: string): [string[], number[]] {
|
||||
let raw = readJsonFile(path, "burst");
|
||||
if (isRecord(raw) && "bursts" in raw) raw = raw.bursts;
|
||||
if (isRecord(raw) && "burst_ID" in raw && "burst_size" in raw && Array.isArray(raw.burst_ID) && Array.isArray(raw.burst_size)) {
|
||||
const ids = raw.burst_ID.map(String);
|
||||
if (isRecord(raw) && "burst_id" in raw && "burst_size" in raw && Array.isArray(raw.burst_id) && Array.isArray(raw.burst_size)) {
|
||||
const ids = raw.burst_id.map(String);
|
||||
const sizes = raw.burst_size.map(Number);
|
||||
if (ids.length !== sizes.length) throw new CliError("CLI 参数错误", "BURST_FILE_INVALID", "burst file burst_ID and burst_size must have the same length", 2);
|
||||
if (ids.length !== sizes.length) throw new CliError("CLI 参数错误", "BURST_FILE_INVALID", "burst file burst_id and burst_size must have the same length", 2);
|
||||
return [ids, sizes];
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
@@ -35,7 +35,7 @@ export function parseBurstFile(path: string): [string[], number[]] {
|
||||
raw.map((item) => Number((item as Record<string, unknown>).size)),
|
||||
];
|
||||
}
|
||||
throw new CliError("CLI 参数错误", "BURST_FILE_INVALID", "burst file must be a JSON array or object with burst_ID/burst_size", 2);
|
||||
throw new CliError("CLI 参数错误", "BURST_FILE_INVALID", "burst file must be a JSON array or object with burst_id/burst_size", 2);
|
||||
}
|
||||
|
||||
export function parseValveSettingFile(path: string): [string[], number[]] {
|
||||
@@ -66,4 +66,3 @@ export function assignDatasetKeys(target: Record<string, unknown>, path: string,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-11
@@ -1,5 +1,4 @@
|
||||
import { CliError, errorMessage } from "./errors.js";
|
||||
import { requireNetwork, requireUsername } from "./runtime.js";
|
||||
import { success } from "./output.js";
|
||||
import type { RequestOptions, RuntimeContext } from "./types.js";
|
||||
|
||||
@@ -35,18 +34,10 @@ function appendParams(url: URL, params: Record<string, unknown> = {}): void {
|
||||
}
|
||||
}
|
||||
|
||||
function withNetworkParam(params: Record<string, unknown> | undefined, network: string): Record<string, unknown> {
|
||||
if (params?.network !== undefined || params?.network_name !== undefined || params?.name !== undefined) return params ?? {};
|
||||
return { ...(params ?? {}), network };
|
||||
}
|
||||
|
||||
export async function requestJson(ctx: RuntimeContext, request: RequestOptions): Promise<[unknown, number]> {
|
||||
const { method, path, params, body, requireAuth = true, requireProject = false, requireNetworkCtx = false, requireUsernameCtx = false } = request;
|
||||
const network = requireNetworkCtx ? requireNetwork(ctx) : null;
|
||||
if (requireUsernameCtx) requireUsername(ctx);
|
||||
const { method, path, params, body, requireAuth = true, requireProject = false } = request;
|
||||
const url = new URL(`/api/v1${path}`, ctx.server.replace(/\/+$/, ""));
|
||||
const requestParams = network && (params !== undefined || body === undefined) ? withNetworkParam(params, network) : params;
|
||||
appendParams(url, requestParams);
|
||||
appendParams(url, params);
|
||||
const started = performance.now();
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), ctx.timeout * 1000);
|
||||
|
||||
@@ -31,8 +31,6 @@ export async function loadAuthContext(authStdin: boolean): Promise<AuthContext>
|
||||
server: process.env.TJWATER_SERVER,
|
||||
access_token: process.env.TJWATER_ACCESS_TOKEN,
|
||||
project_id: process.env.TJWATER_PROJECT_ID,
|
||||
username: process.env.TJWATER_USERNAME,
|
||||
network: process.env.TJWATER_NETWORK,
|
||||
headers: process.env.TJWATER_EXTRA_HEADERS ? JSON.parse(process.env.TJWATER_EXTRA_HEADERS) : {},
|
||||
};
|
||||
const headers = (raw.headers ?? {}) as unknown;
|
||||
@@ -43,8 +41,6 @@ export async function loadAuthContext(authStdin: boolean): Promise<AuthContext>
|
||||
server: pick(raw, "server", "base_url"),
|
||||
accessToken: pick(raw, "access_token", "token", "accessToken"),
|
||||
projectId: pick(raw, "project_id", "projectId", "x_project_id"),
|
||||
username: pick(raw, "username", "preferred_username"),
|
||||
network: pick(raw, "network", "project_code", "projectCode", "project"),
|
||||
headers: Object.fromEntries(Object.entries(headers as Record<string, unknown>).map(([key, value]) => [String(key), String(value)])),
|
||||
};
|
||||
}
|
||||
@@ -81,16 +77,6 @@ export async function buildRuntime(globals: GlobalArgs): Promise<RuntimeContext>
|
||||
};
|
||||
}
|
||||
|
||||
export function requireNetwork(ctx: RuntimeContext): string {
|
||||
if (ctx.auth.network) return ctx.auth.network;
|
||||
throw new CliError("认证失败", "NETWORK_CONTEXT_REQUIRED", "missing network in auth context for legacy network-based endpoints", 3, false, null, ["add network to auth context"]);
|
||||
}
|
||||
|
||||
export function requireUsername(ctx: RuntimeContext): string {
|
||||
if (ctx.auth.username) return ctx.auth.username;
|
||||
throw new CliError("认证失败", "USERNAME_CONTEXT_REQUIRED", "missing username in auth context", 3, false, null, ["add username to auth context"]);
|
||||
}
|
||||
|
||||
export function resolveScheme(ctx: RuntimeContext, explicit: string | undefined, must = false): string | null {
|
||||
const scheme = explicit || ctx.scheme;
|
||||
if (must && !scheme) throw new CliError("CLI 参数错误", "SCHEME_REQUIRED", "missing scheme; use --scheme", 2);
|
||||
|
||||
@@ -6,8 +6,6 @@ export interface AuthContext {
|
||||
server: string | null;
|
||||
accessToken: string | null;
|
||||
projectId: string | null;
|
||||
username: string | null;
|
||||
network: string | null;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -48,8 +46,6 @@ export interface RequestOptions {
|
||||
body?: unknown;
|
||||
requireAuth?: boolean;
|
||||
requireProject?: boolean;
|
||||
requireNetworkCtx?: boolean;
|
||||
requireUsernameCtx?: boolean;
|
||||
}
|
||||
|
||||
export type Handler = (ctx: RuntimeContext, argv: string[]) => Promise<void> | void;
|
||||
|
||||
Reference in New Issue
Block a user