openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
222 lines (221 loc) • 7.04 kB
JavaScript
import { n as parseNodeOptionsEnvVar } from "./node-runtime-env-ncloLK-i.mjs";
import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { isMainThread } from "node:worker_threads";
import * as v8 from "node:v8";
import { setTimeout } from "node:timers/promises";
//#region src/logging/diagnostic-profile.ts
const DIAGNOSTIC_PROFILE_MAX_BYTES = 1048576;
const ENGINE_NAMES = /* @__PURE__ */ new Set([
"(root)",
"(program)",
"(idle)",
"(garbage collector)",
"(GC)",
"(PARSER)",
"(COMPILER)",
"(BYTECODE_COMPILER)",
"(V8 API)",
"(EXTERNAL)",
"(LOGGING)",
"(IDLE_EXTERNAL)",
"(IDLE)",
"(JS)",
"(deopt)"
]);
let capturing = false;
var ProfileFailure = class extends Error {
constructor(e) {
super(e);
this.reason = e;
}
};
function assertProfile(e) {
if (!e) throw new ProfileFailure("invalid-profile");
}
function parseNativeCpuProfile(e) {
const t = e.replace(/"functionName":"(.*?)"(,"lineNumber":-?\d+,"columnNumber":-?\d+,"scriptId":-?\d+,"url":)"(.*?)"}(?=,"(?:children|deoptReason|positionTicks)":|})/gs, (e, t, n, r) => `"functionName":${JSON.stringify(t)}${n}${JSON.stringify(r)}}`);
const n = JSON.parse(t);
const r = [];
for (const e of n.nodes) {
const t = e.callFrame;
r.push({
...e,
callFrame: {
...t,
scriptId: String(t.scriptId)
}
});
}
return {
...n,
nodes: r
};
}
function createInspectorProfileCapture(e, t) {
const n = new e.Session();
n.connect();
return {
setup: () => t.setup(n),
start: () => t.start(n),
stop: () => t.stop(n),
close: async () => {
let e = false;
try {
await t.disable(n);
e = true;
} catch {}
n.disconnect();
if (!e) throw new ProfileFailure("cleanup-failed");
}
};
}
function createNativeCpuProfileCapture(e) {
let t;
return {
start: () => t = v8.startCpuProfile({ sampleInterval: e / 1e3 }),
stop: () => t && { profile: parseNativeCpuProfile(t.stop()) },
close: () => t?.[Symbol.dispose]()
};
}
function hasProfilerConflict() {
const e = parseNodeOptionsEnvVar(process.env.NODE_OPTIONS);
return e === null || Boolean(process.env.NODE_V8_COVERAGE) || Boolean(process.versions.bun && (process.env.BUN_INSPECT || process.env.BUN_INSPECT_CONNECT_TO)) || [...process.execArgv, ...e ?? []].some((e) => /^--(?:inspect|cpu-prof|heap-prof|prof|perf-|.*coverage)/.test(e.replaceAll("_", "-")));
}
function codeUrl(e, t) {
if (/^node:[a-zA-Z0-9_./-]+$/.test(e)) return e;
if (e.length > 2048 || /[?#]/.test(e)) return;
let n = e;
if (e.startsWith("file:")) try {
n = fileURLToPath(e);
} catch {
return;
}
if (!path.isAbsolute(n)) return;
const r = t ? path.relative(t, n).split(path.sep).join("/") : "";
const i = (t && !r.startsWith("..") ? `/${r}` : path.normalize(n).split(path.sep).join("/")).match(/.*\/node_modules\/((?:@[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)?[a-zA-Z0-9_-][a-zA-Z0-9._-]*)\//)?.[1];
if (i) return `node_modules/${i}`;
return /^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?(?:src|dist)\/[a-zA-Z0-9_@./+-]+\.[cm]?js$/.test(r) || /^(?:packages\/[a-zA-Z0-9_@.+-]+\/)?src\/[a-zA-Z0-9_@./+-]+\.ts$/.test(r) ? `openclaw:${r}` : void 0;
}
/** Applies the same code-location and symbol policy to both native profilers. */
function sanitizeDiagnosticProfileFrame(e, t) {
assertProfile(Boolean(e) && typeof e.functionName === "string" && typeof e.url === "string" && typeof e.scriptId === "string" && /^-?\d{1,32}$/.test(e.scriptId) && Number.isSafeInteger(e.lineNumber) && Number.isSafeInteger(e.columnNumber));
const n = codeUrl(e.url, t);
const r = e.url === "" && ENGINE_NAMES.has(e.functionName);
const i = n?.startsWith("node_modules/") ? `[dep:${n.slice(13)}]` : e.scriptId === "0" && e.url === "" && e.lineNumber < 0 && !r ? "[native]" : void 0;
const a = r || n !== void 0 && e.functionName.length <= 256 && /^(?:(?:(?:get|set) )?[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*)?$/.test(e.functionName);
return {
redacted: !a && !i,
callFrame: {
functionName: i ?? (a ? e.functionName : "[redacted]"),
scriptId: e.scriptId,
url: n ?? "",
lineNumber: e.lineNumber,
columnNumber: e.columnNumber
}
};
}
/** Owns one ephemeral isolate-local capture; it never opens an inspector listener. */
async function captureDiagnosticProfile(e) {
const unavailable = (e, t = false) => ({
status: "unavailable",
reason: e,
cleanupFailed: t
});
if (capturing) return unavailable("busy");
capturing = true;
let t;
let n = false;
let r = false;
let i;
let a = false;
let o;
let s;
let c;
let l = 0;
let u = 0;
let d = null;
const assertActive = () => {
if (e.signal?.aborted || !e.hasAuthority()) throw new ProfileFailure("cancelled");
};
try {
assertActive();
const i = await import("node:inspector/promises").catch(() => {
throw new ProfileFailure("unsupported");
});
const a = !isMainThread && e.workerTracingInactive ? () => void 0 : (await import("node:trace_events").catch(() => {
throw new ProfileFailure("unsupported");
})).getEnabledCategories;
const assertTracingInactive = () => {
if (a()) throw new ProfileFailure("tracing-active");
};
d = await resolveOpenClawPackageRoot({ moduleUrl: import.meta.url });
assertActive();
if (i.url() || hasProfilerConflict()) throw new ProfileFailure("conflict");
assertTracingInactive();
t = e.create(i);
await t.setup?.();
assertActive();
assertTracingInactive();
s = {
...process.memoryUsage(),
heapSpaces: v8.getHeapSpaceStatistics()
};
const f = performance.now();
n = true;
const p = t.start();
u = performance.now() - f;
await p;
if (e.durationMs > 0) await setTimeout(e.durationMs, void 0, { signal: e.signal });
assertActive();
r = true;
const m = await t.stop();
if (!m) throw new ProfileFailure("capture-failed");
({profile: o} = m);
l = performance.now() - f;
c = {
...process.memoryUsage(),
heapSpaces: v8.getHeapSpaceStatistics()
};
} catch (t) {
i = t instanceof ProfileFailure ? t.reason : e.signal?.aborted ? "cancelled" : t instanceof Error && t.message.startsWith("Inspector error -32601:") ? "unsupported" : "capture-failed";
} finally {
if (t) {
if (n && !r) try {
await t.stop();
} catch {
a = true;
}
try {
await t.close();
} catch {
a = true;
}
}
}
if (i || a) {
capturing = false;
return unavailable(i ?? "cleanup-failed", a);
}
try {
assertActive();
const t = await e.sanitize(o, d, {
durationMs: l,
startBlockedMs: u,
before: s,
after: c
});
assertActive();
return {
status: "complete",
result: t
};
} catch (e) {
return unavailable(e instanceof ProfileFailure ? e.reason : "invalid-profile");
} finally {
capturing = false;
}
}
//#endregion
export { createInspectorProfileCapture as a, parseNativeCpuProfile as c, captureDiagnosticProfile as i, sanitizeDiagnosticProfileFrame as l, ProfileFailure as n, createNativeCpuProfileCapture as o, assertProfile as r, hasProfilerConflict as s, DIAGNOSTIC_PROFILE_MAX_BYTES as t };