openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 1.65 kB
JavaScript
import{GCProfiler}from"node:v8";
//!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;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)}function flushGcSamples(){if(profiler)drain(true)}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}}}export{getOldGenerationAfterGcBytes as n,observeGcSamples as r,flushGcSamples as t};