openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
128 lines (127 loc) • 4.43 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as createInspectorProfileCapture, i as captureDiagnosticProfile } from "./diagnostic-profile-2SXDazNA.mjs";
import { n as sanitizeDiagnosticCpuProfile } from "./diagnostic-cpu-profile-DdoL1Lu2.mjs";
import { n as sanitizeDiagnosticHeapProfile } from "./diagnostic-heap-profile-BfedH24g.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { replaceFileAtomic } from "@openclaw/fs-safe/atomic";
//#region src/logging/diagnostic-worker-gc-profile.ts
const DURATION_MS = 5e3;
const SAMPLING_INTERVAL_BYTES = 262144;
const MAX_FILES = 20;
const FILE_PATTERN = /^code-mode-gc-\d+-[a-f0-9-]+\.(?:heapprofile|cpuprofile)\.json$/;
let writes = Promise.resolve();
/** The Gateway reports storms lazily; its registry retains the final capture admission. */
async function reportWorkerGcStorm(e, t, n) {
const { profiles: r, ...i } = e;
const a = {
...i,
workerThreadId: t,
workerSlot: n
};
const o = createSubsystemLogger("agents/code-mode");
if (r) try {
const e = await writeWorkerGcProfiles(r);
o.warn("Code Mode worker GC storm", {
...a,
profileFiles: e
});
} catch {
o.warn("Code Mode worker GC storm", {
...a,
captureStatus: "unavailable",
captureReason: "profile-write-failed"
});
}
else o.warn("Code Mode worker GC storm", a);
if (i.captureStatus === "requested") {
const { getEnabledCategories: e } = await import("node:trace_events");
if (e()) o.warn("Code Mode worker GC storm", {
...a,
captureStatus: "unavailable",
captureReason: "tracing-active"
});
else return i;
}
}
/** Runs only in the storming isolate; no inspector listener or guest values are captured. */
function captureWorkerGcProfiles() {
return captureDiagnosticProfile({
hasAuthority: () => true,
durationMs: DURATION_MS,
workerTracingInactive: true,
create: (e) => createInspectorProfileCapture(e, {
setup: async (e) => {
await e.post("HeapProfiler.enable");
await e.post("Profiler.enable");
await e.post("Profiler.setSamplingInterval", { interval: 1e4 });
},
start: async (e) => {
await e.post("HeapProfiler.startSampling", {
samplingInterval: SAMPLING_INTERVAL_BYTES,
includeObjectsCollectedByMajorGC: true,
includeObjectsCollectedByMinorGC: true
});
await e.post("Profiler.start");
},
stop: async (e) => {
const [t, n] = await Promise.all([e.post("HeapProfiler.stopSampling"), e.post("Profiler.stop")]);
return { profile: {
heap: t.profile,
cpu: n.profile
} };
},
disable: (e) => Promise.all([e.post("HeapProfiler.disable"), e.post("Profiler.disable")])
}),
sanitize: async ({ heap: e, cpu: t }, n, r) => ({
heap: JSON.stringify(await sanitizeDiagnosticHeapProfile(e, n, {
durationMs: r.durationMs,
requestedDurationMs: DURATION_MS,
effectiveDurationMs: DURATION_MS,
actualDurationMs: r.durationMs,
durationLimitReason: null,
samplingIntervalBytes: SAMPLING_INTERVAL_BYTES,
includeObjectsCollectedByMajorGC: true,
includeObjectsCollectedByMinorGC: true,
heapUsedBefore: r.before.heapUsed,
heapUsedAfter: r.after.heapUsed,
heapSpacesBefore: r.before.heapSpaces,
heapSpacesAfter: r.after.heapSpaces,
rssBefore: r.before.rss,
rssAfter: r.after.rss
})),
cpu: JSON.stringify(sanitizeDiagnosticCpuProfile(t, n, r))
})
});
}
/** The Gateway serializes all worker writes so the global file cap survives concurrent storms. */
function writeWorkerGcProfiles(e) {
const t = writes.then(async () => {
const t = path.join(resolveStateDir(), "diagnostics");
await fs.mkdir(t, {
recursive: true,
mode: 448
});
const n = (await fs.readdir(t)).filter((e) => FILE_PATTERN.test(e)).toSorted();
for (const e of n.slice(0, Math.max(0, n.length - MAX_FILES + 2))) await fs.unlink(path.join(t, e));
const r = `code-mode-gc-${Date.now()}-${randomUUID()}`;
const i = [];
for (const [n, a] of [["heap", e.heap], ["cpu", e.cpu]]) {
const e = `${r}.${n}profile.json`;
await replaceFileAtomic({
filePath: path.join(t, e),
content: a,
mode: 384,
dirMode: 448
});
i.push(e);
}
return i;
});
writes = t.catch(() => {});
return t;
}
//#endregion
export { captureWorkerGcProfiles, reportWorkerGcStorm };