Skip to content

fix: memory leaks fix #1707 #1708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 55 additions & 9 deletions packages/rrweb-snapshot/src/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
attributes,
mediaAttributes,
DataURLOptions,
listenerHandler,
} from '@rrweb/types';
import {
Mirror,
Expand Down Expand Up @@ -282,7 +283,7 @@
// should warn? maybe a text node isn't attached to a parent node yet?
return false;
} else {
el = dom.parentElement(node)!;

Check warning on line 286 in packages/rrweb-snapshot/src/snapshot.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb-snapshot/src/snapshot.ts#L286

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
}
try {
if (typeof maskTextClass === 'string') {
Expand Down Expand Up @@ -312,6 +313,7 @@
iframeEl: HTMLIFrameElement,
listener: () => unknown,
iframeLoadTimeout: number,
signal: AbortSignal,
) {
const win = iframeEl.contentWindow;
if (!win) {
Expand All @@ -326,41 +328,64 @@
} catch (error) {
return;
}

if (signal.aborted) return;

const handlers: listenerHandler[] = [];
const removeEventListener = () => handlers.forEach((h) => h());
handlers.push(() => signal.removeEventListener('abort', removeEventListener));
signal.addEventListener('abort', removeEventListener);

if (readyState !== 'complete') {
const timer = setTimeout(() => {
removeEventListener();
if (!fired) {
listener();
fired = true;
}
}, iframeLoadTimeout);
iframeEl.addEventListener('load', () => {
clearTimeout(timer);
handlers.push(() => clearTimeout(timer));

const onIframeLoaded = () => {
removeEventListener();
fired = true;
listener();
});
};
handlers.push(() => iframeEl.removeEventListener('load', onIframeLoaded));

iframeEl.addEventListener('load', onIframeLoaded);
return;
}
// check blank frame for Chrome
const blankUrl = 'about:blank';
const onIframeLoaded = () => {
removeEventListener();
listener();
};
if (
win.location.href !== blankUrl ||
iframeEl.src === blankUrl ||
iframeEl.src === ''
) {
// iframe was already loaded, make sure we wait to trigger the listener
// till _after_ the mutation that found this iframe has had time to process
setTimeout(listener, 0);
const timer = setTimeout(() => {
removeEventListener();
listener();
}, 0);
handlers.push(() => clearTimeout(timer));

return iframeEl.addEventListener('load', listener); // keep listing for future loads
return iframeEl.addEventListener('load', onIframeLoaded); // keep listing for future loads
}
// use default listener
iframeEl.addEventListener('load', listener);
iframeEl.addEventListener('load', onIframeLoaded);
}

function onceStylesheetLoaded(
link: HTMLLinkElement,
listener: () => unknown,
styleSheetLoadTimeout: number,
signal: AbortSignal,
) {
let fired = false;
let styleSheetLoaded: StyleSheet | null;
Expand All @@ -371,19 +396,30 @@
}

if (styleSheetLoaded) return;
if (signal.aborted) return;

const handlers: listenerHandler[] = [];
const removeEventListener = () => handlers.forEach((h) => h());
handlers.push(() => signal.removeEventListener('abort', removeEventListener));
signal.addEventListener('abort', removeEventListener);

const timer = setTimeout(() => {
removeEventListener();
if (!fired) {
listener();
fired = true;
}
}, styleSheetLoadTimeout);
handlers.push(() => clearTimeout(timer));

link.addEventListener('load', () => {
clearTimeout(timer);
const onStylesheetLoaded = () => {
removeEventListener();
fired = true;
listener();
});
};

link.addEventListener('load', onStylesheetLoaded);
handlers.push(() => link.removeEventListener('load', onStylesheetLoaded));
}

function serializeNode(
Expand Down Expand Up @@ -702,10 +738,10 @@
const recordInlineImage = () => {
image.removeEventListener('load', recordInlineImage);
try {
canvasService!.width = image.naturalWidth;

Check warning on line 741 in packages/rrweb-snapshot/src/snapshot.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb-snapshot/src/snapshot.ts#L741

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
canvasService!.height = image.naturalHeight;

Check warning on line 742 in packages/rrweb-snapshot/src/snapshot.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb-snapshot/src/snapshot.ts#L742

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
canvasCtx!.drawImage(image, 0, 0);

Check warning on line 743 in packages/rrweb-snapshot/src/snapshot.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb-snapshot/src/snapshot.ts#L743

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
attributes.rr_dataURL = canvasService!.toDataURL(

Check warning on line 744 in packages/rrweb-snapshot/src/snapshot.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb-snapshot/src/snapshot.ts#L744

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
dataURLOptions.type,
dataURLOptions.quality,
);
Expand Down Expand Up @@ -907,6 +943,7 @@
maskTextSelector: string | null;
skipChild: boolean;
inlineStylesheet: boolean;
signal: AbortSignal;
newlyAddedElement?: boolean;
maskInputOptions?: MaskInputOptions;
needsMask?: boolean;
Expand Down Expand Up @@ -956,6 +993,7 @@
keepIframeSrcFn = () => false,
newlyAddedElement = false,
cssCaptured = false,
signal,
} = options;
let { needsMask } = options;
let { preserveWhiteSpace = true } = options;
Expand Down Expand Up @@ -1052,6 +1090,7 @@
maskTextSelector,
skipChild,
inlineStylesheet,
signal,
maskInputOptions,
maskTextFn,
maskInputFn,
Expand Down Expand Up @@ -1128,6 +1167,7 @@
maskTextSelector,
skipChild: false,
inlineStylesheet,
signal,
maskInputOptions,
maskTextFn,
maskInputFn,
Expand All @@ -1153,6 +1193,7 @@
}
},
iframeLoadTimeout,
signal,
);
}

Expand Down Expand Up @@ -1180,6 +1221,7 @@
maskTextSelector,
skipChild: false,
inlineStylesheet,
signal,
maskInputOptions,
maskTextFn,
maskInputFn,
Expand All @@ -1205,6 +1247,7 @@
}
},
stylesheetLoadTimeout,
signal,
);
}

Expand Down Expand Up @@ -1240,6 +1283,7 @@
) => unknown;
stylesheetLoadTimeout?: number;
keepIframeSrcFn?: KeepIframeSrcFn;
signal?: AbortSignal;
},
): serializedNodeWithId | null {
const {
Expand All @@ -1249,6 +1293,7 @@
maskTextClass = 'rr-mask',
maskTextSelector = null,
inlineStylesheet = true,
signal = new AbortController().signal,
inlineImages = false,
recordCanvas = false,
maskAllInputs = false,
Expand Down Expand Up @@ -1316,6 +1361,7 @@
maskTextSelector,
skipChild: false,
inlineStylesheet,
signal,
maskInputOptions,
maskTextFn,
maskInputFn,
Expand Down
6 changes: 6 additions & 0 deletions packages/rrweb/src/record/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@
mirror,
});

let abortController = new AbortController();

takeFullSnapshot = (isCheckout = false) => {
if (!recordDOM) {
return;
Expand All @@ -375,6 +377,8 @@
shadowDomManager.init();

mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting
abortController.abort();
abortController = new AbortController();
const node = snapshot(document, {
mirror,
blockClass,
Expand Down Expand Up @@ -409,6 +413,7 @@
stylesheetManager.attachLinkElement(linkEl, childSn);
},
keepIframeSrcFn,
signal: abortController.signal,
});

if (!node) {
Expand Down Expand Up @@ -557,7 +562,7 @@
plugins
?.filter((p) => p.observer)
?.map((p) => ({
observer: p.observer!,

Check warning on line 565 in packages/rrweb/src/record/index.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/index.ts#L565

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
options: p.options,
callback: (payload: object) =>
wrappedEmit({
Expand All @@ -575,7 +580,7 @@

iframeManager.addLoadListener((iframeEl) => {
try {
handlers.push(observe(iframeEl.contentDocument!));

Check warning on line 583 in packages/rrweb/src/record/index.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/index.ts#L583

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
} catch (error) {
// TODO: handle internal error
console.warn(error);
Expand Down Expand Up @@ -618,6 +623,7 @@
}
return () => {
handlers.forEach((h) => h());
abortController.abort();
processedNodeManager.destroy();
recording = false;
unregisterErrorHandler();
Expand Down
9 changes: 9 additions & 0 deletions packages/rrweb/src/record/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@
private canvasManager: observerParam['canvasManager'];
private processedNodeManager: observerParam['processedNodeManager'];
private unattachedDoc: HTMLDocument;
private serializeAbortController: AbortController = new AbortController();

public init(options: MutationBufferParam) {
(
Expand Down Expand Up @@ -262,6 +263,9 @@
};

public emit = () => {
this.serializeAbortController.abort();
this.serializeAbortController = new AbortController();

if (this.frozen || this.locked) {
return;
}
Expand Down Expand Up @@ -351,6 +355,7 @@
this.stylesheetManager.attachLinkElement(link, childSn);
},
cssCaptured,
signal: this.serializeAbortController.signal,
});
if (sn) {
adds.push({
Expand All @@ -363,13 +368,13 @@
};

while (this.mapRemoves.length) {
this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);

Check warning on line 371 in packages/rrweb/src/record/mutation.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/mutation.ts#L371

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
}

for (const n of this.movedSet) {
if (
isParentRemoved(this.removesSubTreeCache, n, this.mirror) &&
!this.movedSet.has(dom.parentNode(n)!)

Check warning on line 377 in packages/rrweb/src/record/mutation.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/mutation.ts#L377

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
) {
continue;
}
Expand Down Expand Up @@ -521,6 +526,10 @@
this.mutationCb(payload);
};

public destroy() {
this.serializeAbortController.abort();
}

private genTextAreaValueMutation = (textarea: HTMLTextAreaElement) => {
let item = this.attributeMap.get(textarea);
if (!item) {
Expand Down Expand Up @@ -836,7 +845,7 @@
function _isParentRemoved(
removes: Set<Node>,
n: Node,
_mirror: Mirror,

Check warning on line 848 in packages/rrweb/src/record/mutation.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/mutation.ts#L848

[@typescript-eslint/no-unused-vars] '_mirror' is defined but never used.
): boolean {
const node: ParentNode | null = dom.parentNode(n);
if (!node) return false;
Expand Down
18 changes: 13 additions & 5 deletions packages/rrweb/src/record/observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
export function initMutationObserver(
options: MutationBufferParam,
rootEl: Node,
): MutationObserver {
): listenerHandler {
const mutationBuffer = new MutationBuffer();
mutationBuffers.push(mutationBuffer);
// see mutation.ts for details
Expand All @@ -99,7 +99,15 @@
childList: true,
subtree: true,
});
return observer;

return () => {
observer.disconnect();
mutationBuffer.destroy();
const idx = mutationBuffers.indexOf(mutationBuffer);
if (idx > -1) {
mutationBuffers.splice(idx, 1);
}
};
}

function initMoveObserver({
Expand Down Expand Up @@ -131,7 +139,7 @@
| IncrementalSource.TouchMove
| IncrementalSource.Drag,
) => {
const totalOffset = Date.now() - timeBaseline!;

Check warning on line 142 in packages/rrweb/src/record/observer.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/rrweb/src/record/observer.ts#L142

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
mousemoveCb(
positions.map((p) => {
p.timeOffset -= totalOffset;
Expand Down Expand Up @@ -1306,9 +1314,9 @@
}

mergeHooks(o, hooks);
let mutationObserver: MutationObserver | undefined;
let removeMutationObserver: listenerHandler | undefined;
if (o.recordDOM) {
mutationObserver = initMutationObserver(o, o.doc);
removeMutationObserver = initMutationObserver(o, o.doc);
}
const mousemoveHandler = initMoveObserver(o);
const mouseInteractionHandler = initMouseInteractionObserver(o);
Expand Down Expand Up @@ -1350,7 +1358,7 @@

return callbackWrapper(() => {
mutationBuffers.forEach((b) => b.reset());
mutationObserver?.disconnect();
removeMutationObserver?.();
mousemoveHandler();
mouseInteractionHandler();
scrollHandler();
Expand Down
4 changes: 2 additions & 2 deletions packages/rrweb/src/record/shadow-dom-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class ShadowDomManager {
if (!isNativeShadowDom(shadowRoot)) return;
if (this.shadowDoms.has(shadowRoot)) return;
this.shadowDoms.add(shadowRoot);
const observer = initMutationObserver(
const removeObserver = initMutationObserver(
{
...this.bypassOptions,
doc,
Expand All @@ -63,7 +63,7 @@ export class ShadowDomManager {
},
shadowRoot,
);
this.restoreHandlers.push(() => observer.disconnect());
this.restoreHandlers.push(() => removeObserver());
this.restoreHandlers.push(
initScrollObserver({
...this.bypassOptions,
Expand Down
Loading