All files / wdio-devtools-service/src/gatherer trace.js

99.05% Statements 104/105
90.63% Branches 29/32
100% Functions 25/25
99.02% Lines 101/102

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444                              2x   2x                       19x 19x 19x 19x 19x   19x 133x               2x         2x 2x 2x 14x     2x 2x 2x 2x                 2x 1x 1x 1x 1x 1x             2x   2x 2x                   6x 1x 1x 1x 1x 1x 1x           5x               3x 3x     2x 2x 2x 2x                 2x 1x 1x 1x     2x               3x 1x                           2x     2x         2x 2x 1x 1x 1x 1x           1x     2x         2x 2x 2x       1x 1x       5x             2x 2x 2x           2x 2x 1x           1386x   1x     1x   1x 716x   1x 1x 1x           1x               1x 1x   1x 1x               1x 1x         1x 1x 7x 1x     1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                 1x 1x 1x 1x 1x        
import 'core-js/modules/web.url'
 
import EventEmitter from 'events'
import NetworkRecorder from 'lighthouse/lighthouse-core/lib/network-recorder'
import logger from '@wdio/logger'
 
import registerPerformanceObserverInPage from '../scripts/registerPerformanceObserverInPage'
import checkTimeSinceLastLongTask from '../scripts/checkTimeSinceLastLongTask'
 
import {
    DEFAULT_TRACING_CATEGORIES, FRAME_LOAD_START_TIMEOUT, TRACING_TIMEOUT,
    MAX_TRACE_WAIT_TIME, CPU_IDLE_TRESHOLD, NETWORK_IDLE_TIMEOUT
} from '../constants'
import { isSupportedUrl } from '../utils'
 
const log = logger('@wdio/devtools-service:TraceGatherer')
 
const NETWORK_RECORDER_EVENTS = [
    'Network.requestWillBeSent',
    'Network.requestServedFromCache',
    'Network.responseReceived',
    'Network.dataReceived',
    'Network.loadingFinished',
    'Network.loadingFailed',
    'Network.resourceChangedPriority'
]
 
export default class TraceGatherer extends EventEmitter {
    constructor (driver) {
        super()
        this.networkListeners = {}
        this.driver = driver
        this.failingFrameLoadIds = []
        this.pageLoadDetected = false
 
        NETWORK_RECORDER_EVENTS.forEach((method) => {
            this.networkListeners[method] = (params) => this.networkStatusMonitor.dispatch({ method, params })
        })
    }
 
    async startTracing (url) {
        /**
         * delete old trace
         */
        delete this.trace
 
        /**
         * register listener for network status monitoring
         */
        const session = await this.driver.getCDPSession()
        this.networkStatusMonitor = new NetworkRecorder()
        NETWORK_RECORDER_EVENTS.forEach((method) => {
            session.on(method, this.networkListeners[method])
        })
 
        this.traceStart = Date.now()
        log.info(`Start tracing frame with url ${url}`)
        const page = await this.driver.getActivePage()
        await page.tracing.start({
            categories: DEFAULT_TRACING_CATEGORIES,
            screenshots: true
        })
 
        /**
         * if this tracing was started from a click event
         * then we want to discard page trace if no load detected
         */
        if (url === 'click event') {
            log.info('Start checking for page load for click')
            this.clickTraceTimeout = setTimeout(async () => {
                log.info('No page load detected, canceling trace')
                await page.tracing.stop()
                return this.finishTracing()
            }, FRAME_LOAD_START_TIMEOUT)
        }
 
        /**
         * register performance observer
         */
        await page.evaluateOnNewDocument(registerPerformanceObserverInPage)
 
        this.waitForNetworkIdleEvent = this.waitForNetworkIdle(session)
        this.waitForCPUIdleEvent = this.waitForCPUIdle()
    }
 
    /**
     * store frame id of frames that are being traced
     */
    async onFrameNavigated (msgObj) {
        /**
         * page load failed, cancel tracing
         */
        if (this.failingFrameLoadIds.includes(msgObj.frame.id)) {
            delete this.traceStart
            this.waitForNetworkIdleEvent.cancel()
            this.waitForCPUIdleEvent.cancel()
            this.frameId = '"unsuccessful loaded frame"'
            this.finishTracing()
            return clearTimeout(this.clickTraceTimeout)
        }
 
        /**
         * ignore event if
         */
        if (
            // we already detected a frameId before
            this.frameId ||
            // the event was thrown for a sub frame (e.g. iframe)
            msgObj.frame.parentId ||
            // we don't support the url of given frame
            !isSupportedUrl(msgObj.frame.url)
        ) {
            log.info(`Ignore navigated frame with url ${msgObj.frame.url}`)
            return
        }
 
        this.frameId = msgObj.frame.id
        this.loaderId = msgObj.frame.loaderId
        this.pageUrl = msgObj.frame.url
        log.info(`Page load detected: ${this.pageUrl}, set frameId ${this.frameId}, set loaderId ${this.loaderId}`)
 
        /**
         * clear click tracing timeout if it's still waiting
         *
         * the reason we have to tie this to Page.frameNavigated instead of Page.frameStartedLoading
         * is because the latter can sometimes occur without the former, which will cause a hang
         * e.g. with duolingo's sign-in button
         */
        if (this.clickTraceTimeout && !this.pageLoadDetected) {
            log.info('Page load detected for click, clearing click trace timeout}')
            this.pageLoadDetected = true
            clearTimeout(this.clickTraceTimeout)
        }
 
        this.emit('tracingStarted', msgObj.frame.id)
    }
 
    /**
     * once the page load event has fired, we can grab some performance
     * metrics and timing
     */
    async onLoadEventFired () {
        if (!this.isTracing) {
            return
        }
 
        /**
         * Ensure that page is fully loaded and all metrics can be calculated.
         *
         * This can only be ensured if the following conditions are met:
         *  - Listener for onload. Resolves on first FCP event.
         *  - Listener for onload. Resolves pauseAfterLoadMs ms after load.
         *  - Network listener. Resolves when the network has been idle for networkQuietThresholdMs.
         *  - CPU listener. Resolves when the CPU has been idle for cpuQuietThresholdMs after network idle.
         *
         * See https://github.com/GoogleChrome/lighthouse/issues/627 for more.
         */
        const loadPromise = Promise.all([
            this.waitForNetworkIdleEvent.promise,
            this.waitForCPUIdleEvent.promise
        ]).then(() => () => {
            /**
             * ensure that we trace at least for 5s to ensure that we can
             * calculate firstInteractive
             */
            const minTraceTime = TRACING_TIMEOUT - (Date.now() - this.traceStart)
            if (minTraceTime > 0) {
                log.info(`page load happen to quick, waiting ${minTraceTime}ms more`)
                return new Promise(
                    (resolve) => setTimeout(
                        () => resolve(this.completeTracing()),
                        minTraceTime
                    )
                )
            }
 
            return this.completeTracing()
        })
 
        const cleanupFn = await Promise.race([
            loadPromise,
            this.waitForMaxTimeout()
        ])
 
        this.waitForNetworkIdleEvent.cancel()
        this.waitForCPUIdleEvent.cancel()
        return cleanupFn()
    }
 
    onFrameLoadFail (request) {
        const frame = request.frame()
        this.failingFrameLoadIds.push(frame._id)
    }
 
    get isTracing () {
        return typeof this.traceStart === 'number'
    }
 
    /**
     * once tracing has finished capture trace logs into memory
     */
    async completeTracing () {
        const traceDuration = Date.now() - this.traceStart
        log.info(`Tracing completed after ${traceDuration}ms, capturing performance data for frame ${this.frameId}`)
        const page = await this.driver.getActivePage()
 
        /**
         * download all tracing data
         * in case it fails, continue without capturing any data
         */
        try {
            const traceBuffer = await page.tracing.stop()
            const traceEvents = JSON.parse(traceBuffer.toString('utf8'))
 
            /**
             * modify pid of renderer frame to be the same as where tracing was started
             * possibly related to https://github.com/GoogleChrome/lighthouse/issues/6968
             */
            const startedInBrowserEvt = traceEvents.traceEvents.find(e => e.name === 'TracingStartedInBrowser')
            const mainFrame = (
                startedInBrowserEvt &&
                startedInBrowserEvt.args &&
                startedInBrowserEvt.args.data.frames &&
                startedInBrowserEvt.args.data.frames.find(frame => !frame.parent)
            )
            Eif (mainFrame && mainFrame.processId) {
                const threadNameEvt = traceEvents.traceEvents.find(e => e.ph === 'R' &&
                    e.cat === 'blink.user_timing' && e.name === 'navigationStart' && e.args.data.isLoadingMainFrame)
                Eif (threadNameEvt) {
                    log.info(`Replace mainFrame process id ${mainFrame.processId} with actual thread process id ${threadNameEvt.pid}`)
                    mainFrame.processId = threadNameEvt.pid
                } else {
                    log.info(`Couldn't replace mainFrame process id ${mainFrame.processId} with actual thread process id`)
                }
            }
 
            this.trace = {
                ...traceEvents,
                frameId: this.frameId,
                loaderId: this.loaderId,
                pageUrl: this.pageUrl,
                traceStart: this.traceStart,
                traceEnd: Date.now()
            }
            this.emit('tracingComplete', this.trace)
            this.finishTracing()
        } catch (err) {
            log.error(`Error capturing tracing logs: ${err.stack}`)
            return this.finishTracing()
        }
    }
 
    /**
     * clear tracing states and emit tracingFinished
     */
    finishTracing () {
        log.info(`Tracing for ${this.frameId} completed`)
        this.pageLoadDetected = false
 
        /**
         * clean up the listeners
         */
        this.driver.getCDPSession().then((session) => {
            NETWORK_RECORDER_EVENTS.forEach(
                (method) => session.removeListener(method, this.networkListeners[method]))
            delete this.networkStatusMonitor
        })
 
        delete this.traceStart
        delete this.frameId
        delete this.loaderId
        delete this.pageUrl
        this.waitForNetworkIdleEvent.cancel()
        this.waitForCPUIdleEvent.cancel()
        this.emit('tracingFinished')
    }
 
    /**
     * Returns a promise that resolves when the network has been idle (after DCL) for
     * `networkQuietThresholdMs` ms and a method to cancel internal network listeners/timeout.
     * (code from lighthouse source)
     * @param {number} networkQuietThresholdMs
     * @return {{promise: Promise<void>, cancel: function(): void}}
     * @private
     */
    /* istanbul ignore next */
    waitForNetworkIdle (session, networkQuietThresholdMs = NETWORK_IDLE_TIMEOUT) {
        let hasDCLFired = false
        let idleTimeout
        let cancel = () => {
            throw new Error('_waitForNetworkIdle.cancel() called before it was defined')
        }
 
        // Check here for networkStatusMonitor to satisfy type checker. Any further race condition
        // will be caught at runtime on calls to it.
        if (!this.networkStatusMonitor) {
            throw new Error('TraceGatherer.waitForNetworkIdle called with no networkStatusMonitor')
        }
        const networkStatusMonitor = this.networkStatusMonitor
 
        const promise = new Promise((resolve) => {
            const onIdle = () => {
                // eslint-disable-next-line no-use-before-define
                networkStatusMonitor.once('network-2-busy', onBusy)
                idleTimeout = setTimeout(() => {
                    log.info('Network became finally idle')
                    cancel()
                    resolve()
                }, networkQuietThresholdMs)
            }
 
            const onBusy = () => {
                networkStatusMonitor.once('network-2-idle', onIdle)
                idleTimeout && clearTimeout(idleTimeout)
            }
 
            const domContentLoadedListener = () => {
                hasDCLFired = true
                networkStatusMonitor.is2Idle()
                    ? onIdle()
                    : onBusy()
            }
 
            // We frequently need to debug why LH is still waiting for the page.
            // This listener is added to all network events to verbosely log what URLs we're waiting on.
            const logStatus = () => {
                if (!hasDCLFired) {
                    return log.info('Waiting on DomContentLoaded')
                }
 
                const inflightRecords = networkStatusMonitor.getInflightRecords()
                log.info(`Found ${inflightRecords.length} inflight network records`)
                // If there are more than 20 inflight requests, load is still in full swing.
                // Wait until it calms down a bit to be a little less spammy.
                if (inflightRecords.length < 10) {
                    for (const record of inflightRecords) {
                        log.info(`Waiting on ${record.url.slice(0, 120)} to finish`)
                    }
                }
            }
 
            networkStatusMonitor.on('requeststarted', logStatus)
            networkStatusMonitor.on('requestloaded', logStatus)
            networkStatusMonitor.on('network-2-busy', logStatus)
 
            session.once('Page.domContentEventFired', domContentLoadedListener)
 
            let canceled = false
            cancel = () => {
                if (canceled) return
                canceled = true
                log.info('Wait for network idle canceled')
                idleTimeout && clearTimeout(idleTimeout)
 
                session.removeListener('Page.domContentEventFired', domContentLoadedListener)
 
                networkStatusMonitor.removeListener('network-2-busy', onBusy)
                networkStatusMonitor.removeListener('network-2-idle', onIdle)
                networkStatusMonitor.removeListener('requeststarted', logStatus)
                networkStatusMonitor.removeListener('requestloaded', logStatus)
                networkStatusMonitor.removeListener('network-2-busy', logStatus)
            }
        })
 
        return { promise, cancel }
    }
 
    /**
     * Resolves when there have been no long tasks for at least waitForCPUIdle ms.
     * (code from lighthouse source)
     * @param {number} waitForCPUIdle
     * @return {{promise: Promise<void>, cancel: function(): void}}
     */
    /* istanbul ignore next */
    waitForCPUIdle (waitForCPUIdle = CPU_IDLE_TRESHOLD) {
        if (!waitForCPUIdle) {
            return {
                promise: Promise.resolve(),
                cancel: () => undefined
            }
        }
 
        /** @type {NodeJS.Timer|undefined} */
        let lastTimeout
        let canceled = false
 
        const checkForQuietExpression = `(${checkTimeSinceLastLongTask.toString()})()`
        async function checkForQuiet (resolve, reject) {
            if (canceled) return
            const page = await this.driver.getActivePage()
            let timeSinceLongTask
            try {
                timeSinceLongTask = await page.evaluate(checkForQuietExpression)
            } catch (e) {
                log.warn(`Page evaluate rejected while evaluating checkForQuietExpression: ${e.stack}`)
                return setTimeout(() => checkForQuiet.call(this, resolve, reject), 100)
            }
 
            if (canceled) return
 
            if (typeof timeSinceLongTask !== 'number') {
                log.warn(`unexpected value for timeSinceLongTask: ${timeSinceLongTask}`)
                return reject(new Error('timeSinceLongTask is not a number'))
            }
 
            log.info('Driver', `CPU has been idle for ${timeSinceLongTask} ms`)
 
            if (timeSinceLongTask >= waitForCPUIdle) {
                log.info('Driver', `CPU has been idle for ${timeSinceLongTask} ms`)
                return resolve()
            }
 
            log.info('Driver', `CPU has been idle for ${timeSinceLongTask} ms`)
            const timeToWait = waitForCPUIdle - timeSinceLongTask
            lastTimeout = setTimeout(() => checkForQuiet.call(this, resolve, reject), timeToWait)
        }
 
        let cancel = () => {
            throw new Error('_waitForCPUIdle.cancel() called before it was defined')
        }
        const promise = new Promise((resolve, reject) => {
            log.info('Waiting for CPU to become idle')
            checkForQuiet.call(this, resolve, reject)
            cancel = () => {
                if (canceled) return
                canceled = true
                if (lastTimeout) clearTimeout(lastTimeout)
                resolve(new Error('Wait for CPU idle canceled'))
            }
        })
 
        return { promise, cancel }
    }
 
    waitForMaxTimeout (maxWaitForLoadedMs = MAX_TRACE_WAIT_TIME) {
        return new Promise(
            (resolve) => setTimeout(resolve, maxWaitForLoadedMs)
        ).then(() => async () => {
            log.error('Neither network nor CPU idle time could be detected within timeout, wrapping up tracing')
            return this.completeTracing()
        })
    }
}