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

⚡️ Process buffered performance entries in an idle callback #1337

Merged
20 changes: 20 additions & 0 deletions packages/core/src/tools/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,23 @@ export function combine(...sources: any[]): unknown {
}

export type TimeoutId = ReturnType<typeof setTimeout>

export function requestIdleCallback(callback: () => void, opts?: { timeout?: number }) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think we could still let this function here as it could be valuable at some point in other packages but let me know.

interface BrowserWindow extends Window {
requestIdleCallback: (callback: () => void, opts?: { timeout?: number }) => number
cancelIdleCallback: (handle?: number) => void
}
const browserWindow = window as unknown as BrowserWindow

// Use 'requestIdleCallback' when available: it will throttle the mutation processing if the
// browser is busy rendering frames (ex: when frames are below 60fps). When not available, the
// fallback on 'requestAnimationFrame' will still ensure the mutations are processed after any
// browser rendering process (Layout, Recalculate Style, etc.), so we can serialize DOM nodes
// efficiently.
if (browserWindow.requestIdleCallback) {
const id = browserWindow.requestIdleCallback(monitor(callback), opts)
return () => browserWindow.cancelIdleCallback(id)
}
const id = browserWindow.requestAnimationFrame(monitor(callback))
return () => browserWindow.cancelAnimationFrame(id)
}
20 changes: 19 additions & 1 deletion packages/rum-core/src/browser/performanceCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
monitor,
relativeNow,
runOnReadyState,
requestIdleCallback,
} from '@datadog/browser-core'
import type { RumConfiguration } from '../domain/configuration'
import type { LifeCycle } from '../domain/lifeCycle'
Expand Down Expand Up @@ -109,8 +110,14 @@ export function startPerformanceCollection(lifeCycle: LifeCycle, configuration:
})

if (supportPerformanceObject()) {
handleRumPerformanceEntries(lifeCycle, configuration, performance.getEntries())
const performanceEntries = performance.getEntries()
// Because the performance entry list can be quite large
// delay the computation to prevent the SDK from blocking the main thread on page load
amortemousque marked this conversation as resolved.
Show resolved Hide resolved
waitForRequestIdleOrUnload(lifeCycle, () => {
handleRumPerformanceEntries(lifeCycle, configuration, performanceEntries)
})
}

if (window.PerformanceObserver) {
const handlePerformanceEntryList = monitor((entries: PerformanceObserverEntryList) =>
handleRumPerformanceEntries(lifeCycle, configuration, entries.getEntries())
Expand Down Expand Up @@ -154,6 +161,17 @@ export function startPerformanceCollection(lifeCycle: LifeCycle, configuration:
}
}

function waitForRequestIdleOrUnload(lifeCycle: LifeCycle, callback: () => void) {
let hasBeenCalled = false
const callOnce = () => {
if (hasBeenCalled) return
hasBeenCalled = true
callback()
}
requestIdleCallback(callOnce)
amortemousque marked this conversation as resolved.
Show resolved Hide resolved
lifeCycle.subscribe(LifeCycleEventType.BEFORE_UNLOAD, callOnce)
Copy link
Contributor

Choose a reason for hiding this comment

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

❓ question: ‏what is the reasoning for calling it on unload?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't know the detail behind the idle period detection but, FMU we can have cases where they are no idle periods before the unload. This is why the requestIdleCallback API provides a timeout option.

Btw the documentation states: "A timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired." but in our case BEFORE_UNLOAD seems more appropriate.

Copy link
Contributor

@bcaudan bcaudan Feb 15, 2022

Choose a reason for hiding this comment

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

IMO, these kind of behaviors should be explained in the code and tested.
I am wondering if this processing is not likely to be aborted by the unload anyway 🤔.

On the other hand, if we are worried about the requestIdleCallback not being called due to too much activity, let's just use a setTimeout, it should at least split this processing from the init.

wdyt?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Other concern about the async call:
#1337 (comment)

}

export function retrieveInitialDocumentResourceTiming(callback: (timing: RumPerformanceResourceTiming) => void) {
runOnReadyState('interactive', () => {
let timing: RumPerformanceResourceTiming
Expand Down
24 changes: 2 additions & 22 deletions packages/rum/src/domain/record/mutationBatch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { monitor, noop } from '@datadog/browser-core'
import { noop, requestIdleCallback } from '@datadog/browser-core'
import type { RumMutationRecord } from './types'

/**
Expand All @@ -22,7 +22,7 @@ export function createMutationBatch(processMutationBatch: (mutations: RumMutatio
return {
addMutations: (mutations: RumMutationRecord[]) => {
if (pendingMutations.length === 0) {
cancelScheduledFlush = scheduleMutationFlush(flush)
cancelScheduledFlush = requestIdleCallback(flush, { timeout: MUTATION_PROCESS_MAX_DELAY })
}
pendingMutations.push(...mutations)
},
Expand All @@ -34,23 +34,3 @@ export function createMutationBatch(processMutationBatch: (mutations: RumMutatio
},
}
}

function scheduleMutationFlush(flush: () => void) {
interface BrowserWindow extends Window {
requestIdleCallback: (callback: () => void, opts?: { timeout?: number }) => number
cancelIdleCallback: (handle?: number) => void
}
const browserWindow = window as unknown as BrowserWindow

// Use 'requestIdleCallback' when available: it will throttle the mutation processing if the
// browser is busy rendering frames (ex: when frames are below 60fps). When not available, the
// fallback on 'requestAnimationFrame' will still ensure the mutations are processed after any
// browser rendering process (Layout, Recalculate Style, etc.), so we can serialize DOM nodes
// efficiently.
if (browserWindow.requestIdleCallback) {
const id = browserWindow.requestIdleCallback(monitor(flush), { timeout: MUTATION_PROCESS_MAX_DELAY })
return () => browserWindow.cancelIdleCallback(id)
}
const id = browserWindow.requestAnimationFrame(monitor(flush))
return () => browserWindow.cancelAnimationFrame(id)
}