| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- /**
- * 热路径接口耗时探测:连续两次请求,第二次应为缓存命中。
- * 目标:热请求 < 300ms
- */
- const http = require("http");
- function timed(method, path, body) {
- const t0 = Date.now();
- return new Promise((resolve) => {
- const data = body == null ? null : JSON.stringify(body);
- const headers = { Accept: "application/json" };
- if (data) {
- headers["Content-Type"] = "application/json";
- headers["Content-Length"] = Buffer.byteLength(data);
- }
- const r = http.request(
- { hostname: "localhost", port: 8088, path: "/sjnmtybt" + path, method, headers },
- (res) => {
- let raw = "";
- res.on("data", (c) => (raw += c));
- res.on("end", () => {
- const ms = Date.now() - t0;
- let code = res.statusCode;
- try {
- const j = JSON.parse(raw);
- code = j.code != null ? j.code : code;
- } catch (_) {}
- resolve({ ms, code, bytes: raw.length });
- });
- }
- );
- r.on("error", (e) => resolve({ ms: Date.now() - t0, code: 0, error: e.message }));
- if (data) r.write(data);
- r.end();
- });
- }
- const cases = [
- ["GET", "/api/regions", null],
- ["GET", "/api/amount-standards/current?townId=T_YEXIE", null],
- ["GET", "/api/dashboard/region-stats?payMonth=202608&townId=T_YEXIE&months=6", null],
- ["GET", "/api/dashboard/summary?payMonth=202608&townId=T_YEXIE", null],
- ["GET", "/api/dashboard/workbench?payMonth=202608&townId=T_YEXIE&months=6", null],
- [
- "POST",
- "/api/batches/page",
- { pageNum: 1, pageSize: 20, townId: "T_YEXIE", batchLevel: "VILLAGE" },
- ],
- [
- "POST",
- "/api/personnel/page",
- { pageNum: 1, pageSize: 20, townId: "T_YEXIE", villageId: "V_YX_001" },
- ],
- [
- "POST",
- "/api/payments/details/page",
- { pageNum: 1, pageSize: 20, townId: "T_YEXIE" },
- ],
- ["POST", "/api/alerts/page", { pageNum: 1, pageSize: 20, townId: "T_YEXIE" }],
- ];
- (async () => {
- console.log("perf-hot-paths | threshold 300ms (warm)\n");
- let fail = 0;
- for (const [method, path, body] of cases) {
- const cold = await timed(method, path, body);
- const warm = await timed(method, path, body);
- const ok = warm.ms <= 300;
- if (!ok) fail++;
- console.log(
- (ok ? "OK " : "SLOW") +
- " | warm=" +
- String(warm.ms).padStart(4) +
- "ms cold=" +
- String(cold.ms).padStart(4) +
- "ms | " +
- method +
- " " +
- path.split("?")[0] +
- " | code=" +
- warm.code
- );
- }
- console.log("\n" + (fail ? "RESULT: " + fail + " slow endpoints" : "RESULT: all warm < 300ms"));
- process.exit(fail ? 1 : 0);
- })();
|