openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
81 lines (80 loc) • 2.77 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, n as ProfileFailure } from "./diagnostic-profile-2SXDazNA.mjs";
import { r as observeRuntimeProfileCapability } from "./runtime-capabilities-DcqfMou5.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { writeHeapSnapshot } from "node:v8";
//#region src/logging/diagnostic-heap-snapshot.ts
const MAX_HEAP_BYTES = 6 * 1024 ** 3;
const COOLDOWN_MS = 6e4;
const log = createSubsystemLogger("gateway").child("diagnostics/heap-snapshot");
let nextCaptureAt = 0;
/** Owns opt-in main-isolate snapshots; native capture cannot be interrupted. */
async function captureDiagnosticHeapSnapshot(e) {
let t;
let n = 0;
let r = 0;
const i = await observeRuntimeProfileCapability("heapSnapshot", captureDiagnosticProfile({
...e,
durationMs: 0,
create: (i) => {
const a = {
setup: async () => {
if (performance.now() < nextCaptureAt) throw new ProfileFailure("cooldown");
if (process.memoryUsage().heapUsed > MAX_HEAP_BYTES) throw new ProfileFailure("heap-too-large");
const n = path.join(resolveStateDir(), "diagnostics");
await fs.mkdir(n, {
recursive: true,
mode: 448
});
if (e.signal.aborted || !e.hasAuthority()) throw new ProfileFailure("cancelled");
const r = path.join(n, `heap-${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-")}.heapsnapshot`);
const i = await fs.open(r, "wx", 384);
t = r;
await i.close();
},
start: async () => {
const i = process.memoryUsage().heapUsed;
if (i > MAX_HEAP_BYTES) throw new ProfileFailure("heap-too-large");
log.warn("Writing heap snapshot: the main thread will block until capture finishes", {
heapUsedBefore: i,
reason: e.reason
});
const a = performance.now();
try {
writeHeapSnapshot(t);
} finally {
nextCaptureAt = performance.now() + COOLDOWN_MS;
}
n = performance.now() - a;
r = process.memoryUsage().heapUsed;
},
stop: async () => ({ profile: {
path: t,
sizeBytes: (await fs.stat(t)).size
} })
};
return process.versions.bun ? {
...a,
close: () => {}
} : createInspectorProfileCapture(i, {
...a,
disable: (e) => e.post("HeapProfiler.disable")
});
},
sanitize: (e, t, i) => ({
...e,
heapUsedBefore: i.before.heapUsed,
heapUsedAfter: r,
elapsedMs: n
})
}));
if (i.status === "unavailable" && t) {
const e = await fs.unlink(t).then(() => false, () => true);
i.cleanupFailed ||= e;
}
return i;
}
//#endregion
export { captureDiagnosticHeapSnapshot };