Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

flame-control.ts

123 lines2.8 KB

1import fs from 'node:fs'
2import { createRequire } from 'node:module'
3import path from 'node:path'
4​
5const flameEnabled = process.env.TSR_MEMORY_FLAME === '1'
6const heapIntervalBytes = 512 * 1024
7const heapStackDepth = 64
8​
9interface HeapProfile {
10 encode: () => Uint8Array
12​
13interface HeapProfiler {
14 start: (intervalBytes: number, stackDepth: number) => void
15 stop: () => void
16 v8Profile: () => unknown
17 convertProfile: (
18 v8Profile: unknown,
19 ignoreSamplePath?: string,
20 sourceMapper?: unknown,
21 ) => HeapProfile
23​
24interface SourceMapperConstructor {
25 create: (searchDirs: Array<string>) => Promise<unknown>
27​
28interface PprofModule {
29 heap: HeapProfiler
30 SourceMapper: SourceMapperConstructor
32​
33function loadPprof() {
34 const requireFrom = process.env.TSR_MEMORY_REQUIRE_FROM
35 ? path.resolve(process.env.TSR_MEMORY_REQUIRE_FROM)
36 : import.meta.url
37 const require = createRequire(requireFrom)
38​
39 return require('@datadog/pprof') as PprofModule
41​
42function getSourcemapDirs() {
43 return (process.env.TSR_MEMORY_SOURCEMAP_DIRS ?? '')
44 .split(path.delimiter)
45 .filter(Boolean)
47​
48async function createSourceMapper(pprof: PprofModule) {
49 const sourcemapDirs = getSourcemapDirs()
50​
51 if (sourcemapDirs.length === 0) {
52 return undefined
53 }
54​
55 return pprof.SourceMapper.create(sourcemapDirs)
57​
58function formatTimestamp() {
59 return new Date().toISOString().replace(/[:.]/g, '-')
61​
62function formatProfileFileName(profileName?: string) {
63 const profileNameSlug = profileName
64 ?.trim()
65 .toLowerCase()
66 .replace(/[^a-z0-9]+/g, '-')
67 .replace(/^-+|-+$/g, '')
68 const profileNamePart = profileNameSlug ? `${profileNameSlug}-` : ''
69​
70 return `heap-profile-${profileNamePart}${formatTimestamp()}.pb`
72​
73export async function profileFlameWorkload(
74 workload: () => Promise<void> | void,
75 profileName?: string,
76) {
77 if (!flameEnabled) {
78 await workload()
79 return
80 }
81​
82 const profileDir = process.env.TSR_MEMORY_PROFILE_DIR
83​
84 if (!profileDir) {
85 throw new Error('TSR_MEMORY_PROFILE_DIR must be set for flame profiling')
86 }
87​
88 fs.mkdirSync(profileDir, { recursive: true })
89​
90 const pprof = loadPprof()
91 const sourceMapper = await createSourceMapper(pprof)
92​
93 pprof.heap.start(heapIntervalBytes, heapStackDepth)
94​
95 let workloadError: unknown = undefined
96 let v8Profile: unknown = undefined
97​
98 try {
99 await workload()
100 } catch (error) {
101 workloadError = error
102 } finally {
103 try {
104 v8Profile = pprof.heap.v8Profile()
105 } finally {
106 pprof.heap.stop()
107 }
108 }
109​
110 const heapProfile = pprof.heap.convertProfile(
111 v8Profile,
112 undefined,
113 sourceMapper,
114 )
115 const profilePath = path.join(profileDir, formatProfileFileName(profileName))
116​
117 fs.writeFileSync(profilePath, heapProfile.encode())
118 console.log(`Heap profile written to: ${profilePath}`)
119​
120 if (workloadError) {
121 throw workloadError
122 }