Skip to content
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

🐛 [RUMF-1449] workaround for Firefox memory leak when using Zone.js #1860

Merged
merged 4 commits into from
Dec 9, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
37 changes: 37 additions & 0 deletions packages/core/src/browser/addEventListener.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { stubZoneJs } from '../../test/specHelper'
import { noop } from '../tools/utils'

import { addEventListener, DOM_EVENT } from './addEventListener'

describe('addEventListener', () => {
describe('Zone.js support', () => {
let zoneJsStub: ReturnType<typeof stubZoneJs>

beforeEach(() => {
zoneJsStub = stubZoneJs()
})

afterEach(() => {
zoneJsStub.restore()
})

it('uses the original addEventListener method instead of the method patched by Zone.js', () => {
const zoneJsPatchedAddEventListener = jasmine.createSpy()
const eventTarget = document.createElement('div')
zoneJsStub.replaceProperty(eventTarget, 'addEventListener', zoneJsPatchedAddEventListener)

addEventListener(eventTarget, DOM_EVENT.CLICK, noop)
expect(zoneJsPatchedAddEventListener).not.toHaveBeenCalled()
})

it('uses the original removeEventListener method instead of the method patched by Zone.js', () => {
const zoneJsPatchedRemoveEventListener = jasmine.createSpy()
const eventTarget = document.createElement('div')
zoneJsStub.replaceProperty(eventTarget, 'removeEventListener', zoneJsPatchedRemoveEventListener)

const { stop } = addEventListener(eventTarget, DOM_EVENT.CLICK, noop)
stop()
expect(zoneJsPatchedRemoveEventListener).not.toHaveBeenCalled()
})
})
})
102 changes: 102 additions & 0 deletions packages/core/src/browser/addEventListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { monitor } from '../tools/monitor'
import { getZoneJsOriginalValue } from '../tools/getZoneJsOriginalValue'

export const enum DOM_EVENT {
BEFORE_UNLOAD = 'beforeunload',
CLICK = 'click',
DBL_CLICK = 'dblclick',
KEY_DOWN = 'keydown',
LOAD = 'load',
POP_STATE = 'popstate',
SCROLL = 'scroll',
TOUCH_START = 'touchstart',
TOUCH_END = 'touchend',
TOUCH_MOVE = 'touchmove',
VISIBILITY_CHANGE = 'visibilitychange',
DOM_CONTENT_LOADED = 'DOMContentLoaded',
POINTER_DOWN = 'pointerdown',
POINTER_UP = 'pointerup',
POINTER_CANCEL = 'pointercancel',
HASH_CHANGE = 'hashchange',
PAGE_HIDE = 'pagehide',
MOUSE_DOWN = 'mousedown',
MOUSE_UP = 'mouseup',
MOUSE_MOVE = 'mousemove',
FOCUS = 'focus',
BLUR = 'blur',
CONTEXT_MENU = 'contextmenu',
RESIZE = 'resize',
CHANGE = 'change',
INPUT = 'input',
PLAY = 'play',
PAUSE = 'pause',
SECURITY_POLICY_VIOLATION = 'securitypolicyviolation',
SELECTION_CHANGE = 'selectionchange',
}

interface AddEventListenerOptions {
once?: boolean
capture?: boolean
passive?: boolean
}

/**
* Add an event listener to an event target object (Window, Element, mock object...). This provides
* a few conveniences compared to using `element.addEventListener` directly:
*
* * supports IE11 by: using an option object only if needed and emulating the `once` option
*
* * wraps the listener with a `monitor` function
*
* * returns a `stop` function to remove the listener
*/
export function addEventListener<E extends Event>(
eventTarget: EventTarget,
event: DOM_EVENT,
listener: (event: E) => void,
options?: AddEventListenerOptions
) {
return addEventListeners(eventTarget, [event], listener, options)
}

/**
* Add event listeners to an event target object (Window, Element, mock object...). This provides
* a few conveniences compared to using `element.addEventListener` directly:
*
* * supports IE11 by: using an option object only if needed and emulating the `once` option
*
* * wraps the listener with a `monitor` function
*
* * returns a `stop` function to remove the listener
*
* * with `once: true`, the listener will be called at most once, even if different events are listened
*/
export function addEventListeners<E extends Event>(
eventTarget: EventTarget,
events: DOM_EVENT[],
listener: (event: E) => void,
{ once, capture, passive }: AddEventListenerOptions = {}
) {
const wrappedListener = monitor(
once
? (event: Event) => {
stop()
listener(event as E)
}
: (listener as (event: Event) => void)
)

const options = passive ? { capture, passive } : capture

const add = getZoneJsOriginalValue(eventTarget, 'addEventListener')
events.forEach((event) => add.call(eventTarget, event, wrappedListener, options))

function stop() {
const remove = getZoneJsOriginalValue(eventTarget, 'removeEventListener')
events.forEach((event) => remove.call(eventTarget, event, wrappedListener, options))
}

return {
stop,
}
}
2 changes: 1 addition & 1 deletion packages/core/src/browser/pageExitObservable.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Observable } from '../tools/observable'
import { addEventListener, DOM_EVENT } from '../tools/utils'
import { addEventListener, DOM_EVENT } from './addEventListener'

export const enum PageExitReason {
HIDDEN = 'visibility_hidden',
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/domain/report/reportObservable.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { toStackTraceString } from '../../tools/error'
import { monitor } from '../../tools/monitor'
import { mergeObservables, Observable } from '../../tools/observable'
import { DOM_EVENT, includes, addEventListener, safeTruncate } from '../../tools/utils'
import { includes, safeTruncate } from '../../tools/utils'
import { addEventListener, DOM_EVENT } from '../../browser/addEventListener'
import type { Report, BrowserWindow, ReportType } from './browser.types'

export const RawReportType = {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/domain/session/sessionManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import type { CookieOptions } from '../../browser/cookie'
import { COOKIE_ACCESS_DELAY, getCookie, setCookie } from '../../browser/cookie'
import type { Clock } from '../../../test/specHelper'
import { mockClock, restorePageVisibility, setPageVisibility, createNewEvent } from '../../../test/specHelper'
import { ONE_HOUR, DOM_EVENT, ONE_SECOND } from '../../tools/utils'
import { ONE_HOUR, ONE_SECOND } from '../../tools/utils'
import type { RelativeTime } from '../../tools/timeUtils'
import { isIE } from '../../tools/browserDetection'
import { DOM_EVENT } from '../../browser/addEventListener'
import type { SessionManager } from './sessionManager'
import { startSessionManager, stopSessionManager, VISIBILITY_CHECK_DELAY } from './sessionManager'
import { SESSION_COOKIE_NAME } from './sessionCookieStore'
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/domain/session/sessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ContextHistory } from '../../tools/contextHistory'
import type { RelativeTime } from '../../tools/timeUtils'
import { relativeNow, clocksOrigin } from '../../tools/timeUtils'
import { monitor } from '../../tools/monitor'
import { DOM_EVENT, addEventListener, addEventListeners } from '../../browser/addEventListener'
import { tryOldCookiesMigration } from './oldCookiesMigration'
import { startSessionStore } from './sessionStore'
import { SESSION_TIME_OUT_DELAY } from './sessionConstants'
Expand Down Expand Up @@ -70,9 +71,9 @@ export function stopSessionManager() {
}

function trackActivity(expandOrRenewSession: () => void) {
const { stop } = utils.addEventListeners(
const { stop } = addEventListeners(
window,
[utils.DOM_EVENT.CLICK, utils.DOM_EVENT.TOUCH_START, utils.DOM_EVENT.KEY_DOWN, utils.DOM_EVENT.SCROLL],
[DOM_EVENT.CLICK, DOM_EVENT.TOUCH_START, DOM_EVENT.KEY_DOWN, DOM_EVENT.SCROLL],
expandOrRenewSession,
{ capture: true, passive: true }
)
Expand All @@ -86,7 +87,7 @@ function trackVisibility(expandSession: () => void) {
}
})

const { stop } = utils.addEventListener(document, utils.DOM_EVENT.VISIBILITY_CHANGE, expandSessionWhenVisible)
const { stop } = addEventListener(document, DOM_EVENT.VISIBILITY_CHANGE, expandSessionWhenVisible)
stopCallbacks.push(stop)

const visibilityCheckInterval = setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY)
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export * from './tools/utils'
export * from './tools/createEventRateLimiter'
export * from './tools/browserDetection'
export { sendToExtension } from './tools/sendToExtension'
export { getZoneJsOriginalValue } from './tools/getZoneJsOriginalValue'
export { instrumentMethod, instrumentMethodAndCallOriginal, instrumentSetter } from './tools/instrumentMethod'
export {
ErrorSource,
Expand All @@ -75,6 +76,7 @@ export { areCookiesAuthorized, getCookie, setCookie, deleteCookie, COOKIE_ACCESS
export { initXhrObservable, XhrCompleteContext, XhrStartContext } from './browser/xhrObservable'
export { initFetchObservable, FetchResolveContext, FetchStartContext, FetchContext } from './browser/fetchObservable'
export { createPageExitObservable, PageExitEvent, PageExitReason } from './browser/pageExitObservable'
export * from './browser/addEventListener'
export { initConsoleObservable, ConsoleLog } from './domain/console/consoleObservable'
export { BoundedBuffer } from './tools/boundedBuffer'
export { catchUserErrors } from './tools/catchUserErrors'
Expand Down
35 changes: 35 additions & 0 deletions packages/core/src/tools/getZoneJsOriginalValue.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { stubZoneJs } from '../../test/specHelper'

import { getZoneJsOriginalValue } from './getZoneJsOriginalValue'
import { noop } from './utils'

describe('getZoneJsOriginalValue', () => {
let zoneJsStub: ReturnType<typeof stubZoneJs> | undefined

function originalValue() {
// just a function that does nothing but different than 'noop' as we'll want to differentiate
// them.
}
const object = {
name: originalValue,
}

afterEach(() => {
zoneJsStub?.restore()
})

it('returns the original value directly if Zone is not not defined', () => {
expect(getZoneJsOriginalValue(object, 'name')).toBe(originalValue)
})

it("returns undefined if Zone is defined but didn't patch that method", () => {
zoneJsStub = stubZoneJs()
expect(getZoneJsOriginalValue(object, 'name')).toBe(originalValue)
})

it('returns the original value if Zone did patch the method', () => {
zoneJsStub = stubZoneJs()
zoneJsStub.replaceProperty(object, 'name', noop)
expect(getZoneJsOriginalValue(object, 'name')).toBe(originalValue)
})
})
33 changes: 33 additions & 0 deletions packages/core/src/tools/getZoneJsOriginalValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
export interface BrowserWindowWithZoneJs extends Window {
Zone?: {
__symbol__: (name: string) => string
}
}

/**
* Gets the original value for a DOM API that was potentially patched by Zone.js.
*
* Zone.js[1] is a library that patches a bunch of JS and DOM APIs. It usually stores the original
* value of the patched functions/constructors/methods in a hidden property prefixed by
* __zone_symbol__.
*
* In multiple occasions, we observed that Zone.js is the culprit of important issues leading to
* browser resource exhaustion (memory leak, high CPU usage). This method is used as a workaround to
* use the original DOM API instead of the one patched by Zone.js.
*
* [1]: https://github.com/angular/angular/tree/main/packages/zone.js
*/
export function getZoneJsOriginalValue<Target, Name extends keyof Target & string>(
target: Target,
name: Name
): Target[Name] {
const browserWindow = window as BrowserWindowWithZoneJs
let original: Target[Name] | undefined
if (browserWindow.Zone) {
original = (target as any)[browserWindow.Zone.__symbol__(name)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ question: ‏Are we sure it works for all version of Angular/zone.js?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this is something we used before:

const zoneSymbol = browserWindow.Zone.__symbol__
and it works with all tested Zone.js versions (from old ones used by Angularjs 1 to latest ones)

}
if (!original) {
original = target[name]
}
return original
}
Loading