Skip to content

Commit

Permalink
fix: download heapdump instead of writing to disk (#153)
Browse files Browse the repository at this point in the history
Stream the generated heapdump to the client instead of writing it
out to disk.

---------

Co-authored-by: Daniel Norman <1992255+2color@users.noreply.github.com>
  • Loading branch information
achingbrain and 2color authored Sep 24, 2024
1 parent 1921e35 commit 38cf657
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/create-rpc-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { createServer } from 'node:http'
import { decode } from 'node:querystring'
import { writeHeapSnapshot } from 'node:v8'
import { getHeapSnapshot } from 'node:v8'
import { enable } from '@libp2p/logger'

export interface RpcServerOptions {
Expand Down Expand Up @@ -31,9 +31,26 @@ const resources: Record<string, Record<string, Parameters<typeof createServer>[1
GET: (req, res) => {
// force nodejs to generate a heapdump
// you can analyze the heapdump with https://github.com/facebook/memlab#heap-analysis-and-investigation to get some really useful insights
const filename = writeHeapSnapshot(`./snapshot-dir/${(new Date()).toISOString()}.heapsnapshot`)
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(`OK ${filename}`)
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="${(new Date()).toISOString()}.heapsnapshot"`
})

const stream = getHeapSnapshot()
res.on('drain', () => {
stream.resume()
})
stream.on('data', (buf) => {
const sendMore = res.write(buf)

// respect backpressure
if (!sendMore) {
stream.pause()
}
})
stream.on('end', () => {
res.end()
})
}
},
'/api/v0/nodejs/log': {
Expand Down

0 comments on commit 38cf657

Please sign in to comment.