openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
72 lines (71 loc) • 2.21 kB
JavaScript
import { GCProfiler } from "node:v8";
//#region src/infra/gc-observer.ts
const kinds = {
Scavenge: "scavenge",
MinorMarkSweep: "scavenge",
MarkSweepCompact: "mark_sweep_compact",
IncrementalMarking: "incremental",
ProcessWeakCallbacks: "weak_processing"
};
const subscribers = /* @__PURE__ */ new Set();
let profiler;
let timer;
let oldGenerationAfterGcBytes;
/** Last native major-GC epilogue, not memory sampled when JavaScript drains the profile. */
function getOldGenerationAfterGcBytes() {
return oldGenerationAfterGcBytes;
}
function drain(e) {
const t = profiler?.stop();
if (e) profiler?.start();
const n = [];
for (const e of t?.statistics ?? []) {
const t = kinds[e.gcType];
if (!t) continue;
const r = e.beforeGC.heapStatistics.usedHeapSize;
const i = {
kind: t,
reason: "other",
durationMs: e.cost / 1e3,
heapUsedBeforeBytes: r,
reclaimedBytes: Math.max(0, r - e.afterGC.heapStatistics.usedHeapSize)
};
if (t === "mark_sweep_compact") {
i.heapUsedAfterMajorGcBytes = e.afterGC.heapStatistics.usedHeapSize;
i.heapUsedAfterMajorGcTimestampSeconds = Date.now() / 1e3;
oldGenerationAfterGcBytes = 0;
for (const t of e.afterGC.heapSpaceStatistics) if (t.spaceName === "old_space" || t.spaceName === "large_object_space") oldGenerationAfterGcBytes += t.spaceUsedSize;
}
n.push(i);
}
if (n.length) for (const e of subscribers) e(n);
}
/** Include collections from short tasks before their worker can be terminated. */
function flushGcSamples() {
if (profiler) drain(true);
}
/** One native sampler per isolate; never enqueue JavaScript in response to a GC. */
function observeGcSamples(e) {
if (process.versions.bun) return;
if (profiler) drain(true);
else {
profiler = new GCProfiler();
profiler.start();
timer = setInterval(() => drain(true), 1e3).unref();
}
subscribers.add(e);
return () => {
if (!subscribers.has(e)) return;
const t = subscribers.size === 1;
drain(!t);
subscribers.delete(e);
if (t) {
clearInterval(timer);
timer = void 0;
profiler = void 0;
oldGenerationAfterGcBytes = void 0;
}
};
}
//#endregion
export { getOldGenerationAfterGcBytes as n, observeGcSamples as r, flushGcSamples as t };