Skip to content

Commit 7eae3f0

Browse files
JacksonGLfacebook-github-bot
authored andcommitted
feat(api): API supports find memory leaks with specified heap snapshots (#76)
Summary: For OSS request #76 Reviewed By: tulga1970 Differential Revision: D45791349 fbshipit-source-id: 8efb8138fac629602e9baed201e204026abc5eca
1 parent a2a8d86 commit 7eae3f0

3 files changed

Lines changed: 132 additions & 3 deletions

File tree

‎packages/api/src/API.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ export async function takeSnapshots(
202202
}
203203

204204
/**
205-
* This API finds memory leaks by analyzing heap snapshot(s)
205+
* This API finds memory leaks by analyzing heap snapshot(s).
206206
* This is equivalent to `memlab find-leaks` in CLI.
207207
*
208208
* @param runResult return value of a browser interaction run
@@ -229,6 +229,35 @@ export async function findLeaks(
229229
return await analysis.checkLeak();
230230
}
231231

232+
/**
233+
* This API finds memory leaks by analyzing specified heap snapshots.
234+
* This is equivalent to `memlab find-leaks` with
235+
* the `--baseline`, `--target`, and `--final` flags in CLI.
236+
*
237+
* @param baselineSnapshot the file path of the baseline heap snapshot
238+
* @param targetSnapshot the file path of the target heap snapshot
239+
* @param finalSnapshot the file path of the final heap snapshot
240+
* @param options optionally, you can specify a working
241+
* directory (other than the default one) for heap analysis
242+
* @returns leak traces detected and clustered from the browser interaction
243+
*/
244+
export async function findLeaksBySnapshotFilePaths(
245+
baselineSnapshot: string,
246+
targetSnapshot: string,
247+
finalSnapshot: string,
248+
options: {workDir?: string} = {},
249+
): Promise<ISerializedInfo[]> {
250+
defaultConfig.useExternalSnapshot = true;
251+
defaultConfig.externalSnapshotFilePaths = [
252+
baselineSnapshot,
253+
targetSnapshot,
254+
finalSnapshot,
255+
];
256+
fileManager.initDirs(defaultConfig, {workDir: options.workDir});
257+
defaultConfig.chaseWeakMapEdge = false;
258+
return await analysis.checkLeak();
259+
}
260+
232261
/**
233262
* This API analyzes heap snapshot(s) with a specified heap analysis.
234263
* This is equivalent to `memlab analyze` in CLI.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @format
8+
* @oncall web_perf_infra
9+
*/
10+
11+
/* eslint-disable @typescript-eslint/ban-ts-comment */
12+
13+
import {fileManager} from '@memlab/core';
14+
15+
import path from 'path';
16+
import fs from 'fs-extra';
17+
import {takeSnapshots, findLeaksBySnapshotFilePaths} from '../../index';
18+
import {scenario, testSetup, testTimeout} from './lib/E2ETestSettings';
19+
20+
beforeEach(testSetup);
21+
22+
function injectDetachedDOMElements() {
23+
// @ts-ignore
24+
window.injectHookForLink4 = () => {
25+
class TestObject {
26+
key: 'value';
27+
}
28+
const arr = [];
29+
for (let i = 0; i < 23; ++i) {
30+
arr.push(document.createElement('div'));
31+
}
32+
// @ts-ignore
33+
window.__injectedValue = arr;
34+
// @ts-ignore
35+
window._path_1 = {x: {y: document.createElement('div')}};
36+
// @ts-ignore
37+
window._path_2 = new Set([document.createElement('div')]);
38+
// @ts-ignore
39+
window._randomObject = [new TestObject()];
40+
};
41+
}
42+
43+
test(
44+
'leak detector can find detached DOM elements',
45+
async () => {
46+
const result = await takeSnapshots({
47+
scenario,
48+
evalInBrowserAfterInitLoad: injectDetachedDOMElements,
49+
});
50+
// copy heap snapshots to a different location
51+
const snapshotFiles = result.getSnapshotFiles();
52+
const tmpDir = fileManager.generateTmpHeapDir();
53+
const newSnapshotFiles: string[] = [];
54+
snapshotFiles.forEach(file => {
55+
const newFile = path.join(tmpDir, path.basename(file));
56+
newSnapshotFiles.push(newFile);
57+
fs.moveSync(file, newFile);
58+
});
59+
fs.rmdirSync(result.getRootDirectory(), {recursive: true});
60+
61+
// find memory leaks with the new snapshot files
62+
const leaks = await findLeaksBySnapshotFilePaths(
63+
newSnapshotFiles[0],
64+
newSnapshotFiles[1],
65+
newSnapshotFiles[2],
66+
);
67+
68+
// detected all different leak trace cluster
69+
expect(leaks.length >= 1).toBe(true);
70+
// expect all traces are found
71+
expect(
72+
leaks.some(leak => JSON.stringify(leak).includes('__injectedValue')),
73+
);
74+
expect(leaks.some(leak => JSON.stringify(leak).includes('_path_1')));
75+
expect(leaks.some(leak => JSON.stringify(leak).includes('_path_2')));
76+
77+
// finally clean up the temporary directory
78+
fs.rmdirSync(tmpDir, {recursive: true});
79+
},
80+
testTimeout,
81+
);

‎website/docs/api/modules/api_src.md‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,13 @@ const {analyze, takeSnapshots, StringAnalysis} = require('@memlab/api');
7171
```
7272

7373
* **Source**:
74-
* api/src/API.ts:256
74+
* api/src/API.ts:285
7575

7676
___
7777

7878
### <a id="findleaks"></a>**findLeaks**(`runResult`)
7979

80-
This API finds memory leaks by analyzing heap snapshot(s)
80+
This API finds memory leaks by analyzing heap snapshot(s).
8181
This is equivalent to `memlab find-leaks` in CLI.
8282

8383
* **Parameters**:
@@ -101,6 +101,25 @@ const {findLeaks, takeSnapshots} = require('@memlab/api');
101101

102102
___
103103

104+
### <a id="findleaksbysnapshotfilepaths"></a>**findLeaksBySnapshotFilePaths**(`baselineSnapshot`, `targetSnapshot`, `finalSnapshot`, `options?`)
105+
106+
This API finds memory leaks by analyzing specified heap snapshots.
107+
This is equivalent to `memlab find-leaks` with
108+
the `--baseline`, `--target`, and `--final` flags in CLI.
109+
110+
* **Parameters**:
111+
* `baselineSnapshot`: `string` | the file path of the baseline heap snapshot
112+
* `targetSnapshot`: `string` | the file path of the target heap snapshot
113+
* `finalSnapshot`: `string` | the file path of the final heap snapshot
114+
* `options`: `Object` | optionally, you can specify a working directory (other than the default one) for heap analysis
115+
* `options.workDir?`: `string`
116+
* **Returns**: `Promise`<`ISerializedInfo`[]\> | leak traces detected and clustered from the browser interaction
117+
118+
* **Source**:
119+
* api/src/API.ts:244
120+
121+
___
122+
104123
### <a id="run"></a>**run**(`runOptions?`)
105124

106125
This API runs browser interaction and find memory leaks triggered in browser

0 commit comments

Comments
 (0)