openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 7.2 kB
JavaScript
import{t as boundedJsonUtf8Bytes}from"./json-utf8-bytes-BzjXgHQ3.mjs";import{a as createInspectorProfileCapture,i as captureDiagnosticProfile,l as sanitizeDiagnosticProfileFrame,n as ProfileFailure,t as DIAGNOSTIC_PROFILE_MAX_BYTES}from"./diagnostic-profile-C4EYsS8Z.mjs";import{r as observeRuntimeProfileCapability}from"./runtime-capabilities-BZLmQGud.mjs";import{t as reserveDiagnosticProfileFile}from"./diagnostic-profile-file-oE7T0nkR.mjs";import fs from"node:fs/promises";import{setImmediate}from"node:timers/promises";
//!src/logging/diagnostic-heap-profile.ts
const SUMMARY_STACK_DEPTH=32;const MAX_FILE_BYTES=67108864;const WRITE_CHUNK_BYTES=65536;function*heapProfileParts(e){yield`{"head":`;const t=[e.head];while(t.length){const e=t.pop();if(typeof e===`string`){yield e;continue}yield`{"id":${e.id},"callFrame":${JSON.stringify(e.callFrame)},"selfSize":${e.selfSize},"children":[`;t.push(`]}`);for(let n=e.children.length-1;n>=0;n--){t.push(e.children[n]);if(n>0)t.push(`,`)}}yield`,"samples":[`;for(let t=0;t<e.samples.length;t+=1024)yield`${t?`,`:``}${JSON.stringify(e.samples.slice(t,t+1024)).slice(1,-1)}`;yield`]}`}async function sortAllocationSummaries(e){const compare=(e,t)=>t.totalBytes-e.totalBytes||t.selfBytes-e.selfBytes;let t=[];let n=[];for(const r of e){n.push(r);if(n.length===2048){t.push(n.toSorted(compare));n=[];await setImmediate()}}if(n.length)t.push(n.toSorted(compare));while(t.length>1){const e=[];for(let n=0;n<t.length;n+=2){const r=t[n];const i=t[n+1];if(!i){e.push(r);continue}const a=[];let o=0;let s=0;while(o<r.length||s<i.length){a.push(s===i.length||o<r.length&&compare(r[o],i[s])<=0?r[o++]:i[s++]);if(a.length%2048===0)await setImmediate()}e.push(a)}t=e}return t[0]??[]}async function sanitizeDiagnosticHeapProfile(e,t,n,r){const i=e.samples;const a=/* @__PURE__ */ new Map;const o=[{source:e.head}];let s=0;let c=0;for(const{source:e,parent:n}of o){if(++c%1024===0)await setImmediate();const{callFrame:r,redacted:i}=sanitizeDiagnosticProfileFrame(e.callFrame,t);s+=Number(i);const l={id:e.id,callFrame:r,selfSize:e.selfSize,children:[]};const u={node:l,parent:n,totalBytes:l.selfSize,count:0,frameId:0};a.set(l.id,u);n?.node.children.push(l);for(const t of e.children){o.push({source:t,parent:u});if(++c%1024===0)await setImmediate()}}o.length=0;const l=[];let u=0;let d=0;for(const e of i){if(++c%1024===0)await setImmediate();const t=a.get(e.nodeId);if(!t){u++;d+=e.size;continue}t.count++;l.push({size:e.size,nodeId:e.nodeId,ordinal:e.ordinal})}const f=[...a.values()];a.clear();for(let e=f.length-1;e>=0;e--){if(++c%1024===0)await setImmediate();const t=f[e];if(t.parent)t.parent.totalBytes+=t.totalBytes}const p={...n,redactedNodeCount:s,unattributedSampleCount:u,unattributedSampleBytes:d};const m={...p,truncated:u>0,profile:{head:f[0].node,samples:l}};if(boundedJsonUtf8Bytes(m,1048576).complete)return m;const h=await r?.(m.profile);const g=/* @__PURE__ */ new Map;const _=/* @__PURE__ */ new Map;const v=[];const y=[];const b=[];for(const e of f){if(++c%1024===0)await setImmediate();const t=JSON.stringify(e.node.callFrame);let n=g.get(t);if(n===void 0){n=g.size;g.set(t,n)}e.frameId=n;const{totalBytes:r,count:i}=e;if(r===0)continue;const a=e.node.selfSize;e.app=e.node.callFrame.url.startsWith(`openclaw:`)?e:e.parent?.app;e.owner=e.parent?.owner??e.app;let o=e.parent;for(let t=1;o&&t<=SUMMARY_STACK_DEPTH;t++,o=o.parent){if(o.frameId!==n)continue;let r=e.parent;let i=o.parent;let a=1;while(a<t&&r&&i&&r.frameId===i.frameId){r=r.parent;i=i.parent;a++}if(a===t){const n=o.cycle;e.cycle={width:t,count:n?.width===t?n.count+1:2,next:n?.width===t?n.next:i};break}}y.length=b.length=v.length=0;y.push(e);b.push(1);v.push(n);let s=e.parent;while(s&&y.length<SUMMARY_STACK_DEPTH){const e=s.cycle;const t=e&&e.width<=SUMMARY_STACK_DEPTH-y.length?e.width:1;const n=t===e?.width?e.count:1;const r=n>1?e.next:s.parent;for(let e=0;e<t;e++){const r=s;const i=e===t-1&&n>1;y.push(r);b.push(i?n:1);v.push(i?`${r.frameId}x${n}`:r.frameId);s=r.parent}s=r}if(s){const t=y[29].app;const n=t?t===e.owner?[t]:[t,e.owner]:[];y.length=b.length=v.length=29;y.push(void 0,...n);b.push(1,1,1);v.push(`...`,...n.map(e=>e.frameId))}const l=v.join(`,`);const u=_.get(l);if(u){u.selfBytes+=a;u.totalBytes+=r;u.count+=i}else{const t=[e.node.callFrame];for(let e=1;e<y.length;e++){const n=y[e]?.node.callFrame;t.push(!n?{functionName:`[...]`,url:``,scriptId:`0`,lineNumber:-1,columnNumber:-1}:b[e]>1?{...n,functionName:`${n.functionName} ×${b[e]}`}:n)}_.set(l,{stack:t,selfBytes:a,totalBytes:r,count:i})}}g.clear();y.length=0;f.length=0;const x={...p,...h,truncated:true,summary:[]};let S=Buffer.byteLength(JSON.stringify(x));for(const e of await sortAllocationSummaries(_.values())){if(++c%1024===0)await setImmediate();const t=Buffer.byteLength(JSON.stringify(e))+Number(x.summary.length>0);if(S+t>1048576)break;x.summary.push(e);S+=t}return x}async function captureDiagnosticHeapProfile(e){const t=Math.max(4096,e.samplingIntervalBytes??32768);const n={includeObjectsCollectedByMajorGC:e.includeObjectsCollectedByMajorGC??e.includeCollected??false,includeObjectsCollectedByMinorGC:e.includeObjectsCollectedByMinorGC??e.includeCollected??false};const r=n.includeObjectsCollectedByMajorGC||n.includeObjectsCollectedByMinorGC?3e4:9e5;const i=e.durationMs??5e3;const a=Math.min(r,Math.max(1,i));let o;const assertActive=()=>{if(e.signal.aborted||!e.hasAuthority())throw new ProfileFailure(`cancelled`)};const persistOverflow=async e=>{try{o=await reserveDiagnosticProfileFile(`heap-profile`,assertActive,MAX_FILE_BYTES);let t=0;let n=``;let r=0;for(const i of heapProfileParts(e)){const e=Buffer.byteLength(i);t+=e;if(t>MAX_FILE_BYTES)throw new ProfileFailure(`profile-too-large`);n+=i;r+=e;if(r>=WRITE_CHUNK_BYTES){assertActive();await o.handle.writeFile(n,`utf8`);n=``;r=0}}if(n){assertActive();await o.handle.writeFile(n,`utf8`)}return{path:o.path,sizeBytes:t}}catch(e){throw e instanceof ProfileFailure?e:new ProfileFailure(`capture-failed`)}};const s=await observeRuntimeProfileCapability(`heapSampling`,captureDiagnosticProfile({signal:e.signal,hasAuthority:e.hasAuthority,durationMs:a,create:e=>createInspectorProfileCapture(e,{setup:e=>e.post(`HeapProfiler.enable`),start:e=>e.post(`HeapProfiler.startSampling`,{samplingInterval:t,...n}),stop:e=>e.post(`HeapProfiler.stopSampling`),disable:e=>e.post(`HeapProfiler.disable`)}),sanitize:(e,o,s)=>sanitizeDiagnosticHeapProfile(e,o,{durationMs:s.durationMs,requestedDurationMs:i,effectiveDurationMs:a,actualDurationMs:s.durationMs,durationLimitReason:i<=r?null:r===3e4?`collected-samples`:`maximum-duration`,samplingIntervalBytes:t,...n,heapUsedBefore:s.before.heapUsed,heapUsedAfter:s.after.heapUsed,heapSpacesBefore:s.before.heapSpaces,heapSpacesAfter:s.after.heapSpaces,rssBefore:s.before.rss,rssAfter:s.after.rss},persistOverflow)}));const c=o?await o.handle.close().then(()=>false,()=>true):false;if(o&&(s.status===`unavailable`||c)){const e=await fs.unlink(o.path).then(()=>false,()=>true);if(s.status===`unavailable`)s.cleanupFailed||=c||e;else return{status:`unavailable`,reason:`cleanup-failed`,cleanupFailed:true}}return s}export{sanitizeDiagnosticHeapProfile as n,captureDiagnosticHeapProfile as t};