@paulirish/trace_engine 0.0.21 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/analyze-trace.mjs +24 -16
- package/generated/protocol.d.ts +26 -3
- package/models/cpu_profile/CPUProfileDataModel.d.ts +1 -1
- package/models/cpu_profile/CPUProfileDataModel.js +6 -6
- package/models/cpu_profile/CPUProfileDataModel.js.map +1 -1
- package/models/trace/ModelImpl.d.ts +0 -6
- package/models/trace/ModelImpl.js +1 -10
- package/models/trace/ModelImpl.js.map +1 -1
- package/models/trace/Processor.d.ts +0 -1
- package/models/trace/Processor.js +13 -14
- package/models/trace/Processor.js.map +1 -1
- package/models/trace/TracingManager.js.map +1 -1
- package/models/trace/handlers/AuctionWorkletsHandler.js +1 -0
- package/models/trace/handlers/AuctionWorkletsHandler.js.map +1 -1
- package/models/trace/handlers/ExtensionTraceDataHandler.js +18 -5
- package/models/trace/handlers/ExtensionTraceDataHandler.js.map +1 -1
- package/models/trace/handlers/LayoutShiftsHandler.js +1 -0
- package/models/trace/handlers/LayoutShiftsHandler.js.map +1 -1
- package/models/trace/handlers/NetworkRequestsHandler.d.ts +1 -1
- package/models/trace/handlers/NetworkRequestsHandler.js +6 -8
- package/models/trace/handlers/NetworkRequestsHandler.js.map +1 -1
- package/models/trace/handlers/PageLoadMetricsHandler.js +1 -1
- package/models/trace/handlers/PageLoadMetricsHandler.js.map +1 -1
- package/models/trace/handlers/RendererHandler.js +17 -7
- package/models/trace/handlers/RendererHandler.js.map +1 -1
- package/models/trace/handlers/SamplesHandler.d.ts +1 -0
- package/models/trace/handlers/SamplesHandler.js +11 -5
- package/models/trace/handlers/SamplesHandler.js.map +1 -1
- package/models/trace/handlers/ScreenshotsHandler.js +1 -0
- package/models/trace/handlers/ScreenshotsHandler.js.map +1 -1
- package/models/trace/handlers/Threads.js +2 -2
- package/models/trace/handlers/Threads.js.map +1 -1
- package/models/trace/handlers/UserInteractionsHandler.js +1 -0
- package/models/trace/handlers/UserInteractionsHandler.js.map +1 -1
- package/models/trace/handlers/WarningsHandler.js +0 -1
- package/models/trace/handlers/WarningsHandler.js.map +1 -1
- package/models/trace/helpers/Extensions.js +4 -0
- package/models/trace/helpers/Extensions.js.map +1 -1
- package/models/trace/helpers/SamplesIntegrator.d.ts +6 -1
- package/models/trace/helpers/SamplesIntegrator.js +36 -8
- package/models/trace/helpers/SamplesIntegrator.js.map +1 -1
- package/models/trace/helpers/Trace.d.ts +80 -7
- package/models/trace/helpers/Trace.js +190 -24
- package/models/trace/helpers/Trace.js.map +1 -1
- package/models/trace/helpers/TreeHelpers.d.ts +20 -0
- package/models/trace/helpers/TreeHelpers.js +50 -0
- package/models/trace/helpers/TreeHelpers.js.map +1 -1
- package/models/trace/insights/CumulativeLayoutShift.d.ts +29 -0
- package/models/trace/insights/CumulativeLayoutShift.js +81 -0
- package/models/trace/insights/CumulativeLayoutShift.js.map +1 -0
- package/models/trace/insights/InsightRunners.d.ts +1 -0
- package/models/trace/insights/InsightRunners.js +1 -0
- package/models/trace/insights/InsightRunners.js.map +1 -1
- package/models/trace/insights/RenderBlocking.js +14 -0
- package/models/trace/insights/RenderBlocking.js.map +1 -1
- package/models/trace/insights/insights-tsconfig.json +1 -0
- package/models/trace/trace-tsconfig.json +0 -1
- package/models/trace/trace.d.ts +1 -2
- package/models/trace/trace.js +1 -4
- package/models/trace/trace.js.map +1 -1
- package/models/trace/types/Configuration.d.ts +16 -28
- package/models/trace/types/Configuration.js +7 -27
- package/models/trace/types/Configuration.js.map +1 -1
- package/models/trace/types/TraceEvents.d.ts +84 -19
- package/models/trace/types/TraceEvents.js +22 -1
- package/models/trace/types/TraceEvents.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Processor.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/Processor.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAC7B,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AAS,GAAG,EAAE,CAAC;YACnB,KAAK,MAAM,OAAO,IAAI,OAAO,EAAE,CAAC;gBAC9B,IAAI,SAAS,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;oBACzC,SAAS,IAAI,GAAG,OAAO,IAAI,CAAC;gBAC9B,CAAC;YACH,CAAC;YACD,SAAS,IAAI,WAAW,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,mDAAmD,SAAS,EAAE,CAAC,CAAC;QAClF,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACzB,MAAM,OAAO,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO;QACT,CAAC;QACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;QAC9B,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC7B,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC,CAAC;IAEF,KAAK,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;QACrD,YAAY,CAAC,WAAmD,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright 2023 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\nimport * as Handlers from './handlers/handlers.js';\nimport * as Insights from './insights/insights.js';\nimport * as Types from './types/types.js';\n\nconst enum Status {\n IDLE = 'IDLE',\n PARSING = 'PARSING',\n FINISHED_PARSING = 'FINISHED_PARSING',\n ERRORED_WHILE_PARSING = 'ERRORED_WHILE_PARSING',\n}\n\nexport type TraceParseEventProgressData = {\n index: number,\n total: number,\n};\n\nexport class TraceParseProgressEvent extends Event {\n static readonly eventName = 'traceparseprogress';\n constructor(public data: TraceParseEventProgressData, init: EventInit = {bubbles: true}) {\n super(TraceParseProgressEvent.eventName, init);\n }\n}\ndeclare global {\n interface HTMLElementEventMap {\n [TraceParseProgressEvent.eventName]: TraceParseProgressEvent;\n }\n}\n\nexport class TraceProcessor<EnabledModelHandlers extends {[key: string]: Handlers.Types.TraceEventHandler}> extends\n EventTarget {\n // We force the Meta handler to be enabled, so the TraceHandlers type here is\n // the model handlers the user passes in and the Meta handler.\n readonly #traceHandlers: Handlers.Types.HandlersWithMeta<EnabledModelHandlers>;\n #status = Status.IDLE;\n #modelConfiguration = Types.Configuration.DEFAULT;\n #data: Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>|null = null;\n #insights: Insights.Types.TraceInsightData<EnabledModelHandlers>|null = null;\n\n static createWithAllHandlers(): TraceProcessor<typeof Handlers.ModelHandlers> {\n return new TraceProcessor(Handlers.ModelHandlers, Types.Configuration.DEFAULT);\n }\n\n constructor(traceHandlers: EnabledModelHandlers, modelConfiguration?: Types.Configuration.Configuration) {\n super();\n\n this.#verifyHandlers(traceHandlers);\n this.#traceHandlers = {\n Meta: Handlers.ModelHandlers.Meta,\n ...traceHandlers,\n };\n if (modelConfiguration) {\n this.#modelConfiguration = modelConfiguration;\n }\n this.#passConfigToHandlers();\n }\n\n updateConfiguration(config: Types.Configuration.Configuration): void {\n this.#modelConfiguration = config;\n this.#passConfigToHandlers();\n }\n\n #passConfigToHandlers(): void {\n for (const handler of Object.values(this.#traceHandlers)) {\n // Bit of an odd double check, but without this TypeScript refuses to let\n // you call the function as it thinks it might be undefined.\n if ('handleUserConfig' in handler && handler.handleUserConfig) {\n handler.handleUserConfig(this.#modelConfiguration);\n }\n }\n }\n\n /**\n * When the user passes in a set of handlers, we want to ensure that we have all\n * the required handlers. Handlers can depend on other handlers, so if the user\n * passes in FooHandler which depends on BarHandler, they must also pass in\n * BarHandler too. This method verifies that all dependencies are met, and\n * throws if not.\n **/\n #verifyHandlers(providedHandlers: EnabledModelHandlers): void {\n // Tiny optimisation: if the amount of provided handlers matches the amount\n // of handlers in the Handlers.ModelHandlers object, that means that the\n // user has passed in every handler we have. So therefore they cannot have\n // missed any, and there is no need to iterate through the handlers and\n // check the dependencies.\n if (Object.keys(providedHandlers).length === Object.keys(Handlers.ModelHandlers).length) {\n return;\n }\n const requiredHandlerKeys: Set<Handlers.Types.TraceEventHandlerName> = new Set();\n for (const [handlerName, handler] of Object.entries(providedHandlers)) {\n requiredHandlerKeys.add(handlerName as Handlers.Types.TraceEventHandlerName);\n for (const depName of (handler.deps?.() || [])) {\n requiredHandlerKeys.add(depName);\n }\n }\n\n const providedHandlerKeys = new Set(Object.keys(providedHandlers));\n // We always force the Meta handler to be enabled when creating the\n // Processor, so if it is missing from the set the user gave us that is OK,\n // as we will have enabled it anyway.\n requiredHandlerKeys.delete('Meta');\n\n for (const requiredKey of requiredHandlerKeys) {\n if (!providedHandlerKeys.has(requiredKey)) {\n throw new Error(`Required handler ${requiredKey} not provided.`);\n }\n }\n }\n\n reset(): void {\n if (this.#status === Status.PARSING) {\n throw new Error('Trace processor can\\'t reset while parsing.');\n }\n\n const handlers = Object.values(this.#traceHandlers);\n for (const handler of handlers) {\n handler.reset();\n }\n\n this.#data = null;\n this.#insights = null;\n this.#status = Status.IDLE;\n }\n\n async parse(traceEvents: readonly Types.TraceEvents.TraceEventData[], freshRecording = false): Promise<void> {\n if (this.#status !== Status.IDLE) {\n throw new Error(`Trace processor can't start parsing when not idle. Current state: ${this.#status}`);\n }\n try {\n this.#status = Status.PARSING;\n await this.#parse(traceEvents, freshRecording);\n this.#status = Status.FINISHED_PARSING;\n } catch (e) {\n this.#status = Status.ERRORED_WHILE_PARSING;\n throw e;\n }\n }\n\n async #parse(traceEvents: readonly Types.TraceEvents.TraceEventData[], freshRecording: boolean): Promise<void> {\n // This iterator steps through all events, periodically yielding back to the\n // main thread to avoid blocking execution. It uses `dispatchEvent` to\n // provide status update events, and other various bits of config like the\n // pause duration and frequency.\n const {pauseDuration, eventsPerChunk} = this.#modelConfiguration.processing;\n\n // Convert to array so that we are able to iterate all handlers multiple times.\n const sortedHandlers = [...sortHandlers(this.#traceHandlers).values()];\n // Reset.\n for (const handler of sortedHandlers) {\n handler.reset();\n }\n\n // Initialize.\n for (const handler of sortedHandlers) {\n handler.initialize?.(freshRecording);\n }\n\n // Handle each event.\n for (let i = 0; i < traceEvents.length; ++i) {\n // Every so often we take a break just to render.\n if (i % eventsPerChunk === 0 && i) {\n // Take the opportunity to provide status update events.\n this.dispatchEvent(new TraceParseProgressEvent({index: i, total: traceEvents.length}));\n // Wait for rendering before resuming.\n // TODO(paulirish): consider using `scheduler.await()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, pauseDuration));\n }\n const event = traceEvents[i];\n for (let j = 0; j < sortedHandlers.length; ++j) {\n sortedHandlers[j].handleEvent(event);\n }\n }\n\n // Finalize.\n for (const handler of sortedHandlers) {\n await handler.finalize?.();\n }\n }\n\n get traceParsedData(): Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n if (this.#data) {\n return this.#data;\n }\n\n // Handlers that depend on other handlers do so via .data(), which used to always\n // return a shallow clone of its internal data structures. However, that pattern\n // easily results in egregious amounts of allocation. Now .data() does not do any\n // cloning, and it happens here instead so that users of the trace processor may\n // still assume that the parsed data is theirs.\n // See: crbug/41484172\n const shallowClone = (value: unknown, recurse = true): unknown => {\n if (value instanceof Map) {\n return new Map(value);\n }\n if (value instanceof Set) {\n return new Set(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (typeof value === 'object' && value && recurse) {\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n obj[key] = shallowClone(v, false);\n }\n return obj;\n }\n return value;\n };\n\n const traceParsedData = {};\n for (const [name, handler] of Object.entries(this.#traceHandlers)) {\n const data = shallowClone(handler.data());\n Object.assign(traceParsedData, {[name]: data});\n }\n\n this.#data = traceParsedData as Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>;\n return this.#data;\n }\n\n #getEnabledInsightRunners(traceParsedData: Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>):\n Insights.Types.EnabledInsightRunners<EnabledModelHandlers> {\n const enabledInsights = {} as Insights.Types.EnabledInsightRunners<EnabledModelHandlers>;\n for (const [name, insight] of Object.entries(Insights.InsightRunners)) {\n const deps = insight.deps();\n if (deps.some(dep => !traceParsedData[dep])) {\n continue;\n }\n Object.assign(enabledInsights, {[name]: insight.generateInsight});\n }\n return enabledInsights;\n }\n\n get insights(): Insights.Types.TraceInsightData<EnabledModelHandlers>|null {\n if (!this.traceParsedData) {\n return null;\n }\n\n if (this.#insights) {\n return this.#insights;\n }\n\n this.#insights = new Map();\n\n const enabledInsightRunners = this.#getEnabledInsightRunners(this.traceParsedData);\n\n for (const nav of this.traceParsedData.Meta.mainFrameNavigations) {\n if (!nav.args.frame || !nav.args.data?.navigationId) {\n continue;\n }\n\n const context = {\n frameId: nav.args.frame,\n navigationId: nav.args.data.navigationId,\n };\n\n const navInsightData = {} as Insights.Types.NavigationInsightData<EnabledModelHandlers>;\n for (const [name, generateInsight] of Object.entries(enabledInsightRunners)) {\n let insightResult;\n try {\n insightResult = generateInsight(this.traceParsedData, context);\n } catch (err) {\n insightResult = err;\n }\n Object.assign(navInsightData, {[name]: insightResult});\n }\n\n this.#insights.set(context.navigationId, navInsightData);\n }\n\n return this.#insights;\n }\n}\n\n/**\n * Some Handlers need data provided by others. Dependencies of a handler handler are\n * declared in the `deps` field.\n * @returns A map from trace event handler name to trace event hander whose entries\n * iterate in such a way that each handler is visited after its dependencies.\n */\nexport function sortHandlers(\n traceHandlers: Partial<{[key in Handlers.Types.TraceEventHandlerName]: Handlers.Types.TraceEventHandler}>):\n Map<Handlers.Types.TraceEventHandlerName, Handlers.Types.TraceEventHandler> {\n const sortedMap = new Map<Handlers.Types.TraceEventHandlerName, Handlers.Types.TraceEventHandler>();\n const visited = new Set<Handlers.Types.TraceEventHandlerName>();\n const visitHandler = (handlerName: Handlers.Types.TraceEventHandlerName): void => {\n if (sortedMap.has(handlerName)) {\n return;\n }\n if (visited.has(handlerName)) {\n let stackPath = '';\n for (const handler of visited) {\n if (stackPath || handler === handlerName) {\n stackPath += `${handler}->`;\n }\n }\n stackPath += handlerName;\n throw new Error(`Found dependency cycle in trace event handlers: ${stackPath}`);\n }\n visited.add(handlerName);\n const handler = traceHandlers[handlerName];\n if (!handler) {\n return;\n }\n const deps = handler.deps?.();\n if (deps) {\n deps.forEach(visitHandler);\n }\n sortedMap.set(handlerName, handler);\n };\n\n for (const handlerName of Object.keys(traceHandlers)) {\n visitHandler(handlerName as Handlers.Types.TraceEventHandlerName);\n }\n return sortedMap;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Processor.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/Processor.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAC7B,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAc1C,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAE7B;IADnB,MAAM,CAAU,SAAS,GAAG,oBAAoB,CAAC;IACjD,YAAmB,IAAiC,EAAE,OAAkB,EAAC,OAAO,EAAE,IAAI,EAAC;QACrF,KAAK,CAAC,uBAAuB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAD9B,SAAI,GAAJ,IAAI,CAA6B;IAEpD,CAAC;;AAQH,MAAM,OAAO,cAA+F,SACxG,WAAW;IACb,6EAA6E;IAC7E,8DAA8D;IACrD,cAAc,CAAwD;IAC/E,OAAO,4BAAe;IACtB,mBAAmB,GAAG,KAAK,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;IACrD,KAAK,GAAyE,I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pE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright 2023 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\nimport * as Handlers from './handlers/handlers.js';\nimport * as Insights from './insights/insights.js';\nimport * as Types from './types/types.js';\n\nconst enum Status {\n IDLE = 'IDLE',\n PARSING = 'PARSING',\n FINISHED_PARSING = 'FINISHED_PARSING',\n ERRORED_WHILE_PARSING = 'ERRORED_WHILE_PARSING',\n}\n\nexport type TraceParseEventProgressData = {\n index: number,\n total: number,\n};\n\nexport class TraceParseProgressEvent extends Event {\n static readonly eventName = 'traceparseprogress';\n constructor(public data: TraceParseEventProgressData, init: EventInit = {bubbles: true}) {\n super(TraceParseProgressEvent.eventName, init);\n }\n}\ndeclare global {\n interface HTMLElementEventMap {\n [TraceParseProgressEvent.eventName]: TraceParseProgressEvent;\n }\n}\n\nexport class TraceProcessor<EnabledModelHandlers extends {[key: string]: Handlers.Types.TraceEventHandler}> extends\n EventTarget {\n // We force the Meta handler to be enabled, so the TraceHandlers type here is\n // the model handlers the user passes in and the Meta handler.\n readonly #traceHandlers: Handlers.Types.HandlersWithMeta<EnabledModelHandlers>;\n #status = Status.IDLE;\n #modelConfiguration = Types.Configuration.defaults();\n #data: Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>|null = null;\n #insights: Insights.Types.TraceInsightData<EnabledModelHandlers>|null = null;\n\n static createWithAllHandlers(): TraceProcessor<typeof Handlers.ModelHandlers> {\n return new TraceProcessor(Handlers.ModelHandlers, Types.Configuration.defaults());\n }\n\n constructor(traceHandlers: EnabledModelHandlers, modelConfiguration?: Types.Configuration.Configuration) {\n super();\n\n this.#verifyHandlers(traceHandlers);\n this.#traceHandlers = {\n Meta: Handlers.ModelHandlers.Meta,\n ...traceHandlers,\n };\n if (modelConfiguration) {\n this.#modelConfiguration = modelConfiguration;\n }\n this.#passConfigToHandlers();\n }\n\n #passConfigToHandlers(): void {\n for (const handler of Object.values(this.#traceHandlers)) {\n // Bit of an odd double check, but without this TypeScript refuses to let\n // you call the function as it thinks it might be undefined.\n if ('handleUserConfig' in handler && handler.handleUserConfig) {\n handler.handleUserConfig(this.#modelConfiguration);\n }\n }\n }\n\n /**\n * When the user passes in a set of handlers, we want to ensure that we have all\n * the required handlers. Handlers can depend on other handlers, so if the user\n * passes in FooHandler which depends on BarHandler, they must also pass in\n * BarHandler too. This method verifies that all dependencies are met, and\n * throws if not.\n **/\n #verifyHandlers(providedHandlers: EnabledModelHandlers): void {\n // Tiny optimisation: if the amount of provided handlers matches the amount\n // of handlers in the Handlers.ModelHandlers object, that means that the\n // user has passed in every handler we have. So therefore they cannot have\n // missed any, and there is no need to iterate through the handlers and\n // check the dependencies.\n if (Object.keys(providedHandlers).length === Object.keys(Handlers.ModelHandlers).length) {\n return;\n }\n const requiredHandlerKeys: Set<Handlers.Types.TraceEventHandlerName> = new Set();\n for (const [handlerName, handler] of Object.entries(providedHandlers)) {\n requiredHandlerKeys.add(handlerName as Handlers.Types.TraceEventHandlerName);\n for (const depName of (handler.deps?.() || [])) {\n requiredHandlerKeys.add(depName);\n }\n }\n\n const providedHandlerKeys = new Set(Object.keys(providedHandlers));\n // We always force the Meta handler to be enabled when creating the\n // Processor, so if it is missing from the set the user gave us that is OK,\n // as we will have enabled it anyway.\n requiredHandlerKeys.delete('Meta');\n\n for (const requiredKey of requiredHandlerKeys) {\n if (!providedHandlerKeys.has(requiredKey)) {\n throw new Error(`Required handler ${requiredKey} not provided.`);\n }\n }\n }\n\n reset(): void {\n if (this.#status === Status.PARSING) {\n throw new Error('Trace processor can\\'t reset while parsing.');\n }\n\n const handlers = Object.values(this.#traceHandlers);\n for (const handler of handlers) {\n handler.reset();\n }\n\n this.#data = null;\n this.#insights = null;\n this.#status = Status.IDLE;\n }\n\n async parse(traceEvents: readonly Types.TraceEvents.TraceEventData[], freshRecording = false): Promise<void> {\n if (this.#status !== Status.IDLE) {\n throw new Error(`Trace processor can't start parsing when not idle. Current state: ${this.#status}`);\n }\n try {\n this.#status = Status.PARSING;\n await this.#parse(traceEvents, freshRecording);\n this.#status = Status.FINISHED_PARSING;\n } catch (e) {\n this.#status = Status.ERRORED_WHILE_PARSING;\n throw e;\n }\n }\n\n async #parse(traceEvents: readonly Types.TraceEvents.TraceEventData[], freshRecording: boolean): Promise<void> {\n /**\n * We want to yield regularly to maintain responsiveness. If we yield too often, we're wasting idle time.\n * We could do this by checking `performance.now()` regularly, but it's an expensive call in such a hot loop.\n * `eventsPerChunk` is an approximated proxy metric.\n * But how big a chunk? We're aiming for long tasks that are no smaller than 100ms and not bigger than 200ms.\n * It's CPU dependent, so it should be calibrated on oldish hardware.\n * Illustration of a previous change to `eventsPerChunk`: https://imgur.com/wzp8BnR\n */\n const eventsPerChunk = 50_000;\n\n // Convert to array so that we are able to iterate all handlers multiple times.\n const sortedHandlers = [...sortHandlers(this.#traceHandlers).values()];\n // Reset.\n for (const handler of sortedHandlers) {\n handler.reset();\n }\n\n // Initialize.\n for (const handler of sortedHandlers) {\n handler.initialize?.(freshRecording);\n }\n\n // Handle each event.\n for (let i = 0; i < traceEvents.length; ++i) {\n // Every so often we take a break just to render.\n if (i % eventsPerChunk === 0 && i) {\n // Take the opportunity to provide status update events.\n this.dispatchEvent(new TraceParseProgressEvent({index: i, total: traceEvents.length}));\n // TODO(paulirish): consider using `scheduler.yield()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, 0));\n }\n const event = traceEvents[i];\n for (let j = 0; j < sortedHandlers.length; ++j) {\n sortedHandlers[j].handleEvent(event);\n }\n }\n\n // Finalize.\n for (const handler of sortedHandlers) {\n await handler.finalize?.();\n }\n }\n\n get traceParsedData(): Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n if (this.#data) {\n return this.#data;\n }\n\n // Handlers that depend on other handlers do so via .data(), which used to always\n // return a shallow clone of its internal data structures. However, that pattern\n // easily results in egregious amounts of allocation. Now .data() does not do any\n // cloning, and it happens here instead so that users of the trace processor may\n // still assume that the parsed data is theirs.\n // See: crbug/41484172\n const shallowClone = (value: unknown, recurse = true): unknown => {\n if (value instanceof Map) {\n return new Map(value);\n }\n if (value instanceof Set) {\n return new Set(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (typeof value === 'object' && value && recurse) {\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n obj[key] = shallowClone(v, false);\n }\n return obj;\n }\n return value;\n };\n\n const traceParsedData = {};\n for (const [name, handler] of Object.entries(this.#traceHandlers)) {\n const data = shallowClone(handler.data());\n Object.assign(traceParsedData, {[name]: data});\n }\n\n this.#data = traceParsedData as Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>;\n return this.#data;\n }\n\n #getEnabledInsightRunners(traceParsedData: Handlers.Types.EnabledHandlerDataWithMeta<EnabledModelHandlers>):\n Insights.Types.EnabledInsightRunners<EnabledModelHandlers> {\n const enabledInsights = {} as Insights.Types.EnabledInsightRunners<EnabledModelHandlers>;\n for (const [name, insight] of Object.entries(Insights.InsightRunners)) {\n const deps = insight.deps();\n if (deps.some(dep => !traceParsedData[dep])) {\n continue;\n }\n Object.assign(enabledInsights, {[name]: insight.generateInsight});\n }\n return enabledInsights;\n }\n\n get insights(): Insights.Types.TraceInsightData<EnabledModelHandlers>|null {\n if (!this.traceParsedData) {\n return null;\n }\n\n if (this.#insights) {\n return this.#insights;\n }\n\n this.#insights = new Map();\n\n const enabledInsightRunners = this.#getEnabledInsightRunners(this.traceParsedData);\n\n for (const nav of this.traceParsedData.Meta.mainFrameNavigations) {\n if (!nav.args.frame || !nav.args.data?.navigationId) {\n continue;\n }\n\n const context = {\n frameId: nav.args.frame,\n navigationId: nav.args.data.navigationId,\n };\n\n const navInsightData = {} as Insights.Types.NavigationInsightData<EnabledModelHandlers>;\n for (const [name, generateInsight] of Object.entries(enabledInsightRunners)) {\n let insightResult;\n try {\n insightResult = generateInsight(this.traceParsedData, context);\n } catch (err) {\n insightResult = err;\n }\n Object.assign(navInsightData, {[name]: insightResult});\n }\n\n this.#insights.set(context.navigationId, navInsightData);\n }\n\n return this.#insights;\n }\n}\n\n/**\n * Some Handlers need data provided by others. Dependencies of a handler handler are\n * declared in the `deps` field.\n * @returns A map from trace event handler name to trace event hander whose entries\n * iterate in such a way that each handler is visited after its dependencies.\n */\nexport function sortHandlers(\n traceHandlers: Partial<{[key in Handlers.Types.TraceEventHandlerName]: Handlers.Types.TraceEventHandler}>):\n Map<Handlers.Types.TraceEventHandlerName, Handlers.Types.TraceEventHandler> {\n const sortedMap = new Map<Handlers.Types.TraceEventHandlerName, Handlers.Types.TraceEventHandler>();\n const visited = new Set<Handlers.Types.TraceEventHandlerName>();\n const visitHandler = (handlerName: Handlers.Types.TraceEventHandlerName): void => {\n if (sortedMap.has(handlerName)) {\n return;\n }\n if (visited.has(handlerName)) {\n let stackPath = '';\n for (const handler of visited) {\n if (stackPath || handler === handlerName) {\n stackPath += `${handler}->`;\n }\n }\n stackPath += handlerName;\n throw new Error(`Found dependency cycle in trace event handlers: ${stackPath}`);\n }\n visited.add(handlerName);\n const handler = traceHandlers[handlerName];\n if (!handler) {\n return;\n }\n const deps = handler.deps?.();\n if (deps) {\n deps.forEach(visitHandler);\n }\n sortedMap.set(handlerName, handler);\n };\n\n for (const handlerName of Object.keys(traceHandlers)) {\n visitHandler(handlerName as Handlers.Types.TraceEventHandlerName);\n }\n return sortedMap;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TracingManager.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/TracingManager.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;
|
|
1
|
+
{"version":3,"file":"TracingManager.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/TracingManager.ts"],"names":[],"mappings":"AAAA,4DAA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Q,CAAC,cAAc,EAAE,EAAC,YAAY,yCAA+B,EAAE,SAAS,EAAE,KAAK,EAAC,CAAC,CAAC","sourcesContent":["// Copyright 2014 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as SDK from '../../core/sdk/sdk.js';\nimport type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js';\nimport * as Protocol from '../../generated/protocol.js';\n\nimport type * as Types from './types/types.js';\n\nexport class TracingManager extends SDK.SDKModel.SDKModel<void> {\n readonly #tracingAgent: ProtocolProxyApi.TracingApi;\n #activeClient: TracingManagerClient|null;\n #eventBufferSize: number|null;\n #eventsRetrieved: number;\n #finishing?: boolean;\n constructor(target: SDK.Target.Target) {\n super(target);\n this.#tracingAgent = target.tracingAgent();\n target.registerTracingDispatcher(new TracingDispatcher(this));\n\n this.#activeClient = null;\n this.#eventBufferSize = 0;\n this.#eventsRetrieved = 0;\n }\n\n bufferUsage(usage?: number, eventCount?: number, percentFull?: number): void {\n this.#eventBufferSize = eventCount === undefined ? null : eventCount;\n if (this.#activeClient) {\n this.#activeClient.tracingBufferUsage(usage || percentFull || 0);\n }\n }\n\n eventsCollected(events: Types.TraceEvents.TraceEventData[]): void {\n if (!this.#activeClient) {\n return;\n }\n this.#activeClient.traceEventsCollected(events);\n this.#eventsRetrieved += events.length;\n if (!this.#eventBufferSize) {\n this.#activeClient.eventsRetrievalProgress(0);\n return;\n }\n\n if (this.#eventsRetrieved > this.#eventBufferSize) {\n this.#eventsRetrieved = this.#eventBufferSize;\n }\n this.#activeClient.eventsRetrievalProgress(this.#eventsRetrieved / this.#eventBufferSize);\n }\n\n tracingComplete(): void {\n this.#eventBufferSize = 0;\n this.#eventsRetrieved = 0;\n if (this.#activeClient) {\n this.#activeClient.tracingComplete();\n this.#activeClient = null;\n }\n this.#finishing = false;\n }\n\n async reset(): Promise<void> {\n // If we have an active client, we should try to stop\n // it before resetting it, else we will leave the\n // backend in a broken state where it thinks we are in\n // the middle of tracing, but we think we are not.\n // Then, any subsequent attempts to record will fail\n // because the backend will not let us start a second\n // tracing session.\n if (this.#activeClient) {\n await this.#tracingAgent.invoke_end();\n }\n this.#eventBufferSize = 0;\n this.#eventsRetrieved = 0;\n this.#activeClient = null;\n this.#finishing = false;\n }\n\n // TODO(petermarshall): Use the traceConfig argument instead of deprecated\n // categories + options.\n async start(client: TracingManagerClient, categoryFilter: string, options: string):\n Promise<Protocol.ProtocolResponseWithError> {\n if (this.#activeClient) {\n throw new Error('Tracing is already started');\n }\n const bufferUsageReportingIntervalMs = 500;\n this.#activeClient = client;\n const args = {\n bufferUsageReportingInterval: bufferUsageReportingIntervalMs,\n categories: categoryFilter,\n options: options,\n transferMode: Protocol.Tracing.StartRequestTransferMode.ReportEvents,\n };\n const response = await this.#tracingAgent.invoke_start(args);\n if (response.getError()) {\n this.#activeClient = null;\n }\n return response;\n }\n\n stop(): void {\n if (!this.#activeClient) {\n throw new Error('Tracing is not started');\n }\n if (this.#finishing) {\n throw new Error('Tracing is already being stopped');\n }\n this.#finishing = true;\n void this.#tracingAgent.invoke_end();\n }\n}\n\nexport interface TracingManagerClient {\n traceEventsCollected(events: Types.TraceEvents.TraceEventData[]): void;\n\n tracingComplete(): void;\n tracingBufferUsage(usage: number): void;\n eventsRetrievalProgress(progress: number): void;\n}\n\nclass TracingDispatcher implements ProtocolProxyApi.TracingDispatcher {\n readonly #tracingManager: TracingManager;\n constructor(tracingManager: TracingManager) {\n this.#tracingManager = tracingManager;\n }\n\n bufferUsage({value, eventCount, percentFull}: Protocol.Tracing.BufferUsageEvent): void {\n this.#tracingManager.bufferUsage(value, eventCount, percentFull);\n }\n\n dataCollected({value}: Protocol.Tracing.DataCollectedEvent): void {\n this.#tracingManager.eventsCollected(value);\n }\n\n tracingComplete(): void {\n this.#tracingManager.tracingComplete();\n }\n}\n\nSDK.SDKModel.SDKModel.register(TracingManager, {capabilities: SDK.Target.Capability.Tracing, autostart: false});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuctionWorkletsHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/AuctionWorkletsHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,sBAAsB,GACuE,IAAI,GAAG,EAAE,CAAC;AAC7G,MAAM,qBAAqB,GACuE,IAAI,GAAG,EAAE,CAAC;AAE5G,gFAAgF;AAChF,MAAM,sBAAsB,GACxB,IAAI,GAAG,EAAE,CAAC;AAEd,0EAA0E;AAC1E,qCAAqC;AACrC,qEAAqE;AACrE,6EAA6E;AAC7E,qCAAqC;AACrC,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,cAAc,GAA6E,IAAI,GAAG,EAAE,CAAC;AAC3G,MAAM,eAAe,GAA6E,IAAI,GAAG,EAAE,CAAC;AAE5G,MAAM,UAAU,KAAK;IACnB,sBAAsB,CAAC,KAAK,EAAE,CAAC;IAC/B,qBAAqB,CAAC,KAAK,EAAE,CAAC;IAC9B,sBAAsB,CAAC,KAAK,EAAE,CAAC;IAC/B,cAAc,CAAC,KAAK,EAAE,CAAC;IACvB,eAAe,CAAC,KAAK,EAAE,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,KAAuC;IACjE,IAAI,KAAK,CAAC,WAAW,CAAC,0CAA0C,CAAC,KAAK,CAAC,EAAE,CAAC;QACxE,sBAAsB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACvD,OAAO;IACT,CAAC;IAED,IAAI,KAAK,CAAC,WAAW,CAAC,yCAAyC,CAAC,KAAK,CAAC,EAAE,CAAC;QACvE,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,C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AE,CAAC;YAC5B,SAAS;QACX,CAAC;QACD,sBAAsB,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AAMD,MAAM,UAAU,IAAI;IAClB,OAAO;QACL,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC;KAC1C,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2023 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as Types from '../types/types.js';\n\n/**\n * There are two metadata events that we care about.\n * => AuctionWorkletRunningInProcess tells us which process the Auction Worklet\n * has taken to run in.\n * => AuctionWorkletDoneWithProcess tells us when the worklet is done with that\n * process. This is less useful - but in the future we might want to surface\n * this information so we still parse and return the event.\n *\n * It is important to note that the top level PID on these events is NOT the\n * PID that the worklet is running on; instead we have to look at its\n * args.data.pid property, which is the PID of the process that it is running\n * on.\n *\n * For any given RunningInProcess event, we would typically expect to see a\n * DoneWithProcess event, however this is not guaranteed, especially as users\n * can record any chunk of time in DevTools.\n *\n * Similarly, it is also possible to see a DoneWithProcess event without a\n * RunningInProcess event, if the user started recording after the auction\n * worklets started. Therefore we are happy to create\n * SyntheticAuctionWorkletEvents as long as we see just one of these events.\n *\n * If we do get two events and need to pair them, we can use the\n * args.data.target property, which is a string ID shared by both\n * events.\n */\nconst runningInProcessEvents:\n Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventAuctionWorkletRunningInProcess> = new Map();\nconst doneWithProcessEvents:\n Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventAuctionWorkletDoneWithProcess> = new Map();\n\n// Keyed by the PID defined in `args.data.pid` on AuctionWorklet trace events..\nconst createdSyntheticEvents: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.SyntheticAuctionWorkletEvent> =\n new Map();\n\n// Each AuctonWorklet takes over a process and has 2 threads (that we care\n// about and want to show as tracks):\n// 1. A CrUtilityMain thread which is known as the \"control process\".\n// 2. A AuctionV8HelperThread which is the actual auction worklet and will be\n// either a \"Seller\" or a \"Bidder\"\n// To detect these we look for the metadata thread_name events. We key these by\n// PID so that we can easily look them up later without having to loop through.\nconst utilityThreads: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventThreadName> = new Map();\nconst v8HelperThreads: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventThreadName> = new Map();\n\nexport function reset(): void {\n runningInProcessEvents.clear();\n doneWithProcessEvents.clear();\n createdSyntheticEvents.clear();\n utilityThreads.clear();\n v8HelperThreads.clear();\n}\n\nexport function handleEvent(event: Types.TraceEvents.TraceEventData): void {\n if (Types.TraceEvents.isTraceEventAuctionWorkletRunningInProcess(event)) {\n runningInProcessEvents.set(event.args.data.pid, event);\n return;\n }\n\n if (Types.TraceEvents.isTraceEventAuctionWorkletDoneWithProcess(event)) {\n doneWithProcessEvents.set(event.args.data.pid, event);\n return;\n }\n\n if (Types.TraceEvents.isThreadName(event)) {\n if (event.args.name === 'auction_worklet.CrUtilityMain') {\n utilityThreads.set(event.pid, event);\n return;\n }\n if (event.args.name === 'AuctionV8HelperThread') {\n v8HelperThreads.set(event.pid, event);\n }\n }\n}\n\nfunction workletType(input: string): Types.TraceEvents.AuctionWorkletType {\n switch (input) {\n case 'seller':\n return Types.TraceEvents.AuctionWorkletType.SELLER;\n case 'bidder':\n return Types.TraceEvents.AuctionWorkletType.BIDDER;\n default:\n return Types.TraceEvents.AuctionWorkletType.UNKNOWN;\n }\n}\n\n/**\n * We cannot make the full event without knowing the type of event, but we can\n * create everything other than the `args` field, as those are identical\n * regardless of the type of event.\n */\nfunction makeSyntheticEventBase(event: Types.TraceEvents.TraceEventAuctionWorkletDoneWithProcess|\n Types.TraceEvents.TraceEventAuctionWorkletRunningInProcess):\n Omit<Types.TraceEvents.SyntheticAuctionWorkletEvent, 'args'> {\n return {\n name: 'SyntheticAuctionWorkletEvent',\n s: Types.TraceEvents.TraceEventScope.THREAD,\n cat: event.cat,\n tid: event.tid,\n ts: event.ts,\n ph: Types.TraceEvents.Phase.INSTANT,\n pid: event.args.data.pid,\n host: event.args.data.host,\n target: event.args.data.target,\n type: workletType(event.args.data.type),\n };\n}\n\nexport async function finalize(): Promise<void> {\n // Loop through the utility threads we found to create the worklet events. We\n // expect each worklet to have a utility thread, so we can use them as the\n // root of our list of worklets.\n for (const [pid, utilityThreadNameEvent] of utilityThreads) {\n const v8HelperEvent = v8HelperThreads.get(pid);\n if (!v8HelperEvent) {\n // Bad trace data - AuctionWorklets are expected to always have both threads.\n continue;\n }\n\n const runningEvent = runningInProcessEvents.get(pid);\n const doneWithEvent = doneWithProcessEvents.get(pid);\n\n // We can create a worklet from either the runningEvent or doneWithEvent -\n // we do not need both. We cannot express that to TypeScript with an early\n // return here, so instead we set the event initially to null, and then\n // create it from either the running event or the doneWith event. If it is\n // still null after this, that means neither event was found, and we drop\n // the worklet as we do not have enough information to create the synthetic\n // event.\n\n let syntheticEvent: Types.TraceEvents.SyntheticAuctionWorkletEvent|null = null;\n\n if (runningEvent) {\n syntheticEvent = {\n ...makeSyntheticEventBase(runningEvent),\n args: {\n data: {\n runningInProcessEvent: runningEvent,\n utilityThread: utilityThreadNameEvent,\n v8HelperThread: v8HelperEvent,\n },\n },\n };\n if (doneWithEvent) {\n syntheticEvent.args.data.doneWithProcessEvent = doneWithEvent;\n }\n } else if (doneWithEvent) {\n syntheticEvent = {\n ...makeSyntheticEventBase(doneWithEvent),\n args: {\n data: {\n doneWithProcessEvent: doneWithEvent,\n utilityThread: utilityThreadNameEvent,\n v8HelperThread: v8HelperEvent,\n },\n },\n };\n if (runningEvent) {\n syntheticEvent.args.data.runningInProcessEvent = runningEvent;\n }\n }\n if (syntheticEvent === null) {\n continue;\n }\n createdSyntheticEvents.set(pid, syntheticEvent);\n }\n}\n\nexport interface AuctionWorkletsData {\n worklets: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.SyntheticAuctionWorkletEvent>;\n}\n\nexport function data(): AuctionWorkletsData {\n return {\n worklets: new Map(createdSyntheticEvents),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AuctionWorkletsHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/AuctionWorkletsHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,sBAAsB,GACuE,IAAI,GAAG,EAAE,CAAC;AAC7G,MAAM,qBAAqB,GACuE,IAAI,GAAG,EAAE,CAAC;AAE5G,gFAAgF;AAChF,MAAM,sBAAsB,GACxB,IAAI,GAAG,EAAE,CAAC;AAEd,0EAA0E;AAC1E,qCAAqC;AACrC,qEAAqE;AACrE,6EAA6E;AAC7E,qCAAqC;AACrC,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,cAAc,GAA6E,IAAI,GAAG,EAAE,CAAC;AAC3G,MAAM,eAAe,GAA6E,IAAI,GAAG,EAAE,CAAC;AAE5G,MAAM,UAAU,KAAK;IACnB,sBAAsB,CAAC,KAAK,EAAE,CAAC;IAC/B,qBAAqB,CAAC,KAAK,EAAE,CAAC;IAC9B,sBAAsB,CAAC,KAAK,EAAE,CAAC;IAC/B,cAAc,CAAC,KAAK,EAAE,CAAC;IACvB,eAAe,CAAC,KAAK,EAAE,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,KAAuC;IACjE,IAAI,KAAK,CAAC,WAAW,CAAC,0CAA0C,CAAC,KAAK,CAAC,EAAE,CAAC;QACxE,sBAAsB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACvD,OAAO;IACT,CAAC;IAED,IAAI,KAAK,CAAC,WAAW,CAAC,yCAAyC,CAAC,KAAK,CAAC,EAAE,CAAC;QACvE,qBAAqB,CAAC,G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YAAY,CAAC;YAChE,CAAC;QACH,CAAC;QACD,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;YAC5B,SAAS;QACX,CAAC;QACD,sBAAsB,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AAMD,MAAM,UAAU,IAAI;IAClB,OAAO;QACL,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC;KAC1C,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2023 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as Types from '../types/types.js';\n\n/**\n * There are two metadata events that we care about.\n * => AuctionWorkletRunningInProcess tells us which process the Auction Worklet\n * has taken to run in.\n * => AuctionWorkletDoneWithProcess tells us when the worklet is done with that\n * process. This is less useful - but in the future we might want to surface\n * this information so we still parse and return the event.\n *\n * It is important to note that the top level PID on these events is NOT the\n * PID that the worklet is running on; instead we have to look at its\n * args.data.pid property, which is the PID of the process that it is running\n * on.\n *\n * For any given RunningInProcess event, we would typically expect to see a\n * DoneWithProcess event, however this is not guaranteed, especially as users\n * can record any chunk of time in DevTools.\n *\n * Similarly, it is also possible to see a DoneWithProcess event without a\n * RunningInProcess event, if the user started recording after the auction\n * worklets started. Therefore we are happy to create\n * SyntheticAuctionWorkletEvents as long as we see just one of these events.\n *\n * If we do get two events and need to pair them, we can use the\n * args.data.target property, which is a string ID shared by both\n * events.\n */\nconst runningInProcessEvents:\n Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventAuctionWorkletRunningInProcess> = new Map();\nconst doneWithProcessEvents:\n Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventAuctionWorkletDoneWithProcess> = new Map();\n\n// Keyed by the PID defined in `args.data.pid` on AuctionWorklet trace events..\nconst createdSyntheticEvents: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.SyntheticAuctionWorkletEvent> =\n new Map();\n\n// Each AuctonWorklet takes over a process and has 2 threads (that we care\n// about and want to show as tracks):\n// 1. A CrUtilityMain thread which is known as the \"control process\".\n// 2. A AuctionV8HelperThread which is the actual auction worklet and will be\n// either a \"Seller\" or a \"Bidder\"\n// To detect these we look for the metadata thread_name events. We key these by\n// PID so that we can easily look them up later without having to loop through.\nconst utilityThreads: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventThreadName> = new Map();\nconst v8HelperThreads: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.TraceEventThreadName> = new Map();\n\nexport function reset(): void {\n runningInProcessEvents.clear();\n doneWithProcessEvents.clear();\n createdSyntheticEvents.clear();\n utilityThreads.clear();\n v8HelperThreads.clear();\n}\n\nexport function handleEvent(event: Types.TraceEvents.TraceEventData): void {\n if (Types.TraceEvents.isTraceEventAuctionWorkletRunningInProcess(event)) {\n runningInProcessEvents.set(event.args.data.pid, event);\n return;\n }\n\n if (Types.TraceEvents.isTraceEventAuctionWorkletDoneWithProcess(event)) {\n doneWithProcessEvents.set(event.args.data.pid, event);\n return;\n }\n\n if (Types.TraceEvents.isThreadName(event)) {\n if (event.args.name === 'auction_worklet.CrUtilityMain') {\n utilityThreads.set(event.pid, event);\n return;\n }\n if (event.args.name === 'AuctionV8HelperThread') {\n v8HelperThreads.set(event.pid, event);\n }\n }\n}\n\nfunction workletType(input: string): Types.TraceEvents.AuctionWorkletType {\n switch (input) {\n case 'seller':\n return Types.TraceEvents.AuctionWorkletType.SELLER;\n case 'bidder':\n return Types.TraceEvents.AuctionWorkletType.BIDDER;\n default:\n return Types.TraceEvents.AuctionWorkletType.UNKNOWN;\n }\n}\n\n/**\n * We cannot make the full event without knowing the type of event, but we can\n * create everything other than the `args` field, as those are identical\n * regardless of the type of event.\n */\nfunction makeSyntheticEventBase(event: Types.TraceEvents.TraceEventAuctionWorkletDoneWithProcess|\n Types.TraceEvents.TraceEventAuctionWorkletRunningInProcess):\n Omit<Types.TraceEvents.SyntheticAuctionWorkletEvent, 'args'> {\n return {\n rawSourceEvent: event,\n name: 'SyntheticAuctionWorkletEvent',\n s: Types.TraceEvents.TraceEventScope.THREAD,\n cat: event.cat,\n tid: event.tid,\n ts: event.ts,\n ph: Types.TraceEvents.Phase.INSTANT,\n pid: event.args.data.pid,\n host: event.args.data.host,\n target: event.args.data.target,\n type: workletType(event.args.data.type),\n };\n}\n\nexport async function finalize(): Promise<void> {\n // Loop through the utility threads we found to create the worklet events. We\n // expect each worklet to have a utility thread, so we can use them as the\n // root of our list of worklets.\n for (const [pid, utilityThreadNameEvent] of utilityThreads) {\n const v8HelperEvent = v8HelperThreads.get(pid);\n if (!v8HelperEvent) {\n // Bad trace data - AuctionWorklets are expected to always have both threads.\n continue;\n }\n\n const runningEvent = runningInProcessEvents.get(pid);\n const doneWithEvent = doneWithProcessEvents.get(pid);\n\n // We can create a worklet from either the runningEvent or doneWithEvent -\n // we do not need both. We cannot express that to TypeScript with an early\n // return here, so instead we set the event initially to null, and then\n // create it from either the running event or the doneWith event. If it is\n // still null after this, that means neither event was found, and we drop\n // the worklet as we do not have enough information to create the synthetic\n // event.\n\n let syntheticEvent: Types.TraceEvents.SyntheticAuctionWorkletEvent|null = null;\n\n if (runningEvent) {\n syntheticEvent = {\n ...makeSyntheticEventBase(runningEvent),\n args: {\n data: {\n runningInProcessEvent: runningEvent,\n utilityThread: utilityThreadNameEvent,\n v8HelperThread: v8HelperEvent,\n },\n },\n };\n if (doneWithEvent) {\n syntheticEvent.args.data.doneWithProcessEvent = doneWithEvent;\n }\n } else if (doneWithEvent) {\n syntheticEvent = {\n ...makeSyntheticEventBase(doneWithEvent),\n args: {\n data: {\n doneWithProcessEvent: doneWithEvent,\n utilityThread: utilityThreadNameEvent,\n v8HelperThread: v8HelperEvent,\n },\n },\n };\n if (runningEvent) {\n syntheticEvent.args.data.runningInProcessEvent = runningEvent;\n }\n }\n if (syntheticEvent === null) {\n continue;\n }\n createdSyntheticEvents.set(pid, syntheticEvent);\n }\n}\n\nexport interface AuctionWorkletsData {\n worklets: Map<Types.TraceEvents.ProcessID, Types.TraceEvents.SyntheticAuctionWorkletEvent>;\n}\n\nexport function data(): AuctionWorkletsData {\n return {\n worklets: new Map(createdSyntheticEvents),\n };\n}\n"]}
|
|
@@ -69,14 +69,27 @@ export function extensionDataInTiming(timing) {
|
|
|
69
69
|
if (!timingDetail) {
|
|
70
70
|
return null;
|
|
71
71
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
try {
|
|
73
|
+
// Attempt to parse the detail as an object that might be coming from a
|
|
74
|
+
// DevTools Perf extension.
|
|
75
|
+
// Wrapped in a try-catch because timingDetail might either:
|
|
76
|
+
// 1. Not be `json.parse`-able (it should, but just in case...)
|
|
77
|
+
// 2.Not be an object - in which case the `in` check will error.
|
|
78
|
+
// If we hit either of these cases, we just ignore this mark and move on.
|
|
79
|
+
const detailObj = JSON.parse(timingDetail);
|
|
80
|
+
if (!('devtools' in detailObj)) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
if (!('metadata' in detailObj['devtools'])) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return detailObj.devtools;
|
|
75
87
|
}
|
|
76
|
-
|
|
88
|
+
catch (e) {
|
|
89
|
+
// No need to worry about this error, just discard this event and don't
|
|
90
|
+
// treat it as having any useful information for the purposes of extensions
|
|
77
91
|
return null;
|
|
78
92
|
}
|
|
79
|
-
return detailObj.devtools;
|
|
80
93
|
}
|
|
81
94
|
export function data() {
|
|
82
95
|
if (handlerState !== 3 /* HandlerState.FINALIZED */) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExtensionTraceDataHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/ExtensionTraceDataHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAm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O,IAAI,CAAC;IACd,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"ExtensionTraceDataHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/ExtensionTraceDataHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAG3C,OAAO,EAAC,IAAI,IAAI,eAAe,EAAC,MAAM,yBAAyB,CAAC;AAEhE,MAAM,0BAA0B,GAAyD,EAAE,CAAC;AAC5F,MAAM,kBAAkB,GAA0C,EAAE,CAAC;AACrE,MAAM,gBAAgB,GAAgD,EAAE,CAAC;AAMzE,IAAI,YAAY,qCAA6B,CAAC;AAE9C,MAAM,UAAU,WAAW,CAAC,MAAwC;IAClE,4EAA4E;AAC9E,CAAC;AAED,MAAM,UAAU,KAAK;IACnB,YAAY,mCAA2B,CAAC;IACxC,0BAA0B,CAAC,MAAM,GAAG,CAAC,CAAC;IACtC,kBAAkB,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9B,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC;AAC9B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,IAAI,YAAY,qCAA6B,EAAE,CAAC;QAC9C,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IACD,gCAAgC,EAAE,CAAC;IACnC,YAAY,iCAAyB,CAAC;AACxC,CAAC;AAED,SAAS,gCAAgC;IACvC,MAAM,cAAc,GAAyD,eAAe,EAAE,CAAC,mBAAmB,CAAC;IACnH,MAAM,KAAK,GAA2D,eAAe,EAAE,CAAC,gBAAgB,CAAC;IACzG,MAAM,wBAAwB,GAAG,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC,cA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// Copyright 2024 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {HandlerState, type TraceEventHandlerName} from './types.js';\nimport {data as userTimingsData} from './UserTimingsHandler.js';\n\nconst extensionFlameChartEntries: Types.Extensions.SyntheticExtensionFlameChartEntry[] = [];\nconst extensionTrackData: Types.Extensions.ExtensionTrackData[] = [];\nconst extensionMarkers: Types.Extensions.SyntheticExtensionMarker[] = [];\n\nexport interface ExtensionTraceData {\n extensionTrackData: readonly Types.Extensions.ExtensionTrackData[];\n extensionMarkers: readonly Types.Extensions.SyntheticExtensionMarker[];\n}\nlet handlerState = HandlerState.UNINITIALIZED;\n\nexport function handleEvent(_event: Types.TraceEvents.TraceEventData): void {\n // Implementation not needed because data is sourced from UserTimingsHandler\n}\n\nexport function reset(): void {\n handlerState = HandlerState.INITIALIZED;\n extensionFlameChartEntries.length = 0;\n extensionTrackData.length = 0;\n extensionMarkers.length = 0;\n}\n\nexport async function finalize(): Promise<void> {\n if (handlerState !== HandlerState.INITIALIZED) {\n throw new Error('ExtensionTraceData handler is not initialized');\n }\n createExtensionFlameChartEntries();\n handlerState = HandlerState.FINALIZED;\n}\n\nfunction createExtensionFlameChartEntries(): void {\n const pairedMeasures: readonly Types.TraceEvents.SyntheticUserTimingPair[] = userTimingsData().performanceMeasures;\n const marks: readonly Types.TraceEvents.TraceEventPerformanceMark[] = userTimingsData().performanceMarks;\n const mergedRawExtensionEvents = Helpers.Trace.mergeEventsInOrder(pairedMeasures, marks);\n\n extractExtensionEntries(mergedRawExtensionEvents);\n Helpers.Extensions.buildTrackDataFromExtensionEntries(extensionFlameChartEntries, extensionTrackData);\n}\n\nexport function extractExtensionEntries(\n timings: (Types.TraceEvents.SyntheticUserTimingPair|Types.TraceEvents.TraceEventPerformanceMark)[]): void {\n for (const timing of timings) {\n const extensionPayload = extensionDataInTiming(timing);\n if (!extensionPayload) {\n // Not an extension user timing.\n continue;\n }\n const extensionName = extensionPayload.metadata.extensionName;\n if (!extensionName) {\n continue;\n }\n const extensionSyntheticEntry = {\n name: timing.name,\n ph: Types.TraceEvents.Phase.COMPLETE,\n pid: Types.TraceEvents.ProcessID(0),\n tid: Types.TraceEvents.ThreadID(0),\n ts: timing.ts,\n selfTime: Types.Timing.MicroSeconds(0),\n dur: timing.dur as Types.Timing.MicroSeconds,\n cat: 'devtools.extension',\n args: extensionPayload,\n };\n if (Types.Extensions.isExtensionPayloadMarker(extensionPayload)) {\n extensionMarkers.push(extensionSyntheticEntry as Types.Extensions.SyntheticExtensionMarker);\n continue;\n }\n if (Types.Extensions.isExtensionPayloadFlameChartEntry(extensionPayload)) {\n extensionFlameChartEntries.push(extensionSyntheticEntry as Types.Extensions.SyntheticExtensionFlameChartEntry);\n continue;\n }\n }\n}\n\nexport function extensionDataInTiming(timing: Types.TraceEvents.SyntheticUserTimingPair|\n Types.TraceEvents.TraceEventPerformanceMark):\n Types.Extensions.ExtensionDataPayload|null {\n const timingDetail = Types.TraceEvents.isTraceEventPerformanceMark(timing) ? timing.args.data?.detail :\n timing.args.data.beginEvent.args.detail;\n if (!timingDetail) {\n return null;\n }\n try {\n // Attempt to parse the detail as an object that might be coming from a\n // DevTools Perf extension.\n // Wrapped in a try-catch because timingDetail might either:\n // 1. Not be `json.parse`-able (it should, but just in case...)\n // 2.Not be an object - in which case the `in` check will error.\n // If we hit either of these cases, we just ignore this mark and move on.\n const detailObj = JSON.parse(timingDetail);\n if (!('devtools' in detailObj)) {\n return null;\n }\n if (!('metadata' in detailObj['devtools'])) {\n return null;\n }\n return detailObj.devtools;\n } catch (e) {\n // No need to worry about this error, just discard this event and don't\n // treat it as having any useful information for the purposes of extensions\n return null;\n }\n}\n\nexport function data(): ExtensionTraceData {\n if (handlerState !== HandlerState.FINALIZED) {\n throw new Error('ExtensionTraceData handler is not finalized');\n }\n\n return {\n extensionTrackData: [...extensionTrackData],\n extensionMarkers: [...extensionMarkers],\n };\n}\n\nexport function deps(): TraceEventHandlerName[] {\n return ['UserTimings'];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LayoutShiftsHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/LayoutShiftsHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,QAAQ,MAAM,oCAAoC,CAAC;AAE/D,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,IAAI,IAAI,eAAe,EAAC,MAAM,kBAAkB,CAAC;AA6CzD,4EAA4E;AAC5E,YAAY;AACZ,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAE/G,8EAA8E;AAC9E,0DAA0D;AAC1D,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAE/G,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,UAAU;AACV,MAAM,iBAAiB,GAA8C,EAAE,CAAC;AAExE,+EAA+E;AAC/E,qDAAqD;AACrD,MAAM,wBAAwB,GAA6D,EAAE,CAAC;AAC9F,MAAM,+BAA+B,GAAoE,EAAE,CAAC;AAC5G,MAAM,6BAA6B,GAAkE,EAAE,CAAC;AAExG,MAAM,cAAc,GAAG,IAAI,GAAG,EAA8B,CAAC;AAE7D,2EAA2E;AAC3E,mFAAmF;AACnF,wEAAwE;AACxE,sBAAsB;AACtB,MAAM,cAAc,GAA2C,EAAE,C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I,KAAK,wCAA2B,CAAC;IACrC,IAAI,KAAK,qDAA2C,EAAE,CAAC;QACrD,KAAK,oCAAyB,CAAC;IACjC,CAAC;IAED,IAAI,KAAK,wCAA6B,EAAE,CAAC;QACvC,KAAK,sCAA0B,CAAC;IAClC,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright 2022 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as Platform from '../../../core/platform/platform.js';\nimport type * as Protocol from '../../../generated/protocol.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {data as metaHandlerData} from './MetaHandler.js';\nimport {ScoreClassification} from './PageLoadMetricsHandler.js';\nimport {HandlerState, type TraceEventHandlerName} from './types.js';\n\n// We start with a score of zero and step through all Layout Shift records from\n// all renderers. Each record not only tells us which renderer it is, but also\n// the unweighted and weighted scores. The unweighted score is the score we would\n// get if the renderer were the only one in the viewport. The weighted score, on\n// the other hand, accounts for how much of the viewport that particular render\n// takes up when the shift happened. An ad frame in the corner of the viewport\n// that shifts is considered less disruptive, therefore, than if it were taking\n// up the whole viewport.\n//\n// Next, we step through all the records from all renderers and add the weighted\n// score to a running total across all of the renderers. We create a new \"cluster\"\n// and reset the running total when:\n//\n// 1. We observe a outermost frame navigation, or\n// 2. When there's a gap between records of > 1s, or\n// 3. When there's more than 5 seconds of continuous layout shifting.\n//\n// Note that for it to be Cumulative Layout Shift in the sense described in the\n// documentation we would need to guarantee that we are tracking from navigation\n// to unload. However, we don't make any such guarantees here (since a developer\n// can record and stop when they please), so we support the cluster approach,\n// and we can give them a score, but it is effectively a \"session\" score, a\n// score for the given recording, and almost certainly not the\n// navigation-to-unload CLS score.\n\ninterface LayoutShifts {\n clusters: readonly LayoutShiftCluster[];\n sessionMaxScore: number;\n // The session window which contains the SessionMaxScore\n clsWindowID: number;\n // We use these to calculate root causes for a given LayoutShift\n // TODO(crbug/41484172): should be readonly\n prePaintEvents: Types.TraceEvents.TraceEventPrePaint[];\n layoutInvalidationEvents: readonly Types.TraceEvents.TraceEventLayoutInvalidationTracking[];\n scheduleStyleInvalidationEvents: readonly Types.TraceEvents.TraceEventScheduleStyleInvalidationTracking[];\n styleRecalcInvalidationEvents: readonly Types.TraceEvents.TraceEventStyleRecalcInvalidationTracking[];\n scoreRecords: readonly ScoreRecord[];\n // TODO(crbug/41484172): should be readonly\n backendNodeIds: Protocol.DOM.BackendNodeId[];\n}\n\n// This represents the maximum #time we will allow a cluster to go before we\n// reset it.\nexport const MAX_CLUSTER_DURATION = Helpers.Timing.millisecondsToMicroseconds(Types.Timing.MilliSeconds(5000));\n\n// This represents the maximum #time we will allow between layout shift events\n// before considering it to be the start of a new cluster.\nexport const MAX_SHIFT_TIME_DELTA = Helpers.Timing.millisecondsToMicroseconds(Types.Timing.MilliSeconds(1000));\n\n// Layout shifts are reported globally to the developer, irrespective of which\n// frame they originated in. However, each process does have its own individual\n// CLS score, so we need to segment by process. This means Layout Shifts from\n// sites with one process (no subframes, or subframes from the same origin)\n// will be reported together. In the case of multiple renderers (frames across\n// different origins), we offer the developer the ability to switch renderer in\n// the UI.\nconst layoutShiftEvents: Types.TraceEvents.TraceEventLayoutShift[] = [];\n\n// These events denote potential node resizings. We store them to link captured\n// layout shifts to the resizing of unsized elements.\nconst layoutInvalidationEvents: Types.TraceEvents.TraceEventLayoutInvalidationTracking[] = [];\nconst scheduleStyleInvalidationEvents: Types.TraceEvents.TraceEventScheduleStyleInvalidationTracking[] = [];\nconst styleRecalcInvalidationEvents: Types.TraceEvents.TraceEventStyleRecalcInvalidationTracking[] = [];\n\nconst backendNodeIds = new Set<Protocol.DOM.BackendNodeId>();\n\n// Layout shifts happen during PrePaint as part of the rendering lifecycle.\n// We determine if a LayoutInvalidation event is a potential root cause of a layout\n// shift if the next PrePaint after the LayoutInvalidation is the parent\n// node of such shift.\nconst prePaintEvents: Types.TraceEvents.TraceEventPrePaint[] = [];\n\nlet sessionMaxScore = 0;\n\nlet clsWindowID = -1;\n\nconst clusters: LayoutShiftCluster[] = [];\n\n// Represents a point in time in which a LS score change\n// was recorded.\ntype ScoreRecord = {\n ts: number,\n score: number,\n};\n\n// The complete timeline of LS score changes in a trace.\n// Includes drops to 0 when session windows end.\nconst scoreRecords: ScoreRecord[] = [];\n\nlet handlerState = HandlerState.UNINITIALIZED;\n\nexport function initialize(): void {\n if (handlerState !== HandlerState.UNINITIALIZED) {\n throw new Error('LayoutShifts Handler was not reset');\n }\n handlerState = HandlerState.INITIALIZED;\n}\n\nexport function reset(): void {\n handlerState = HandlerState.UNINITIALIZED;\n layoutShiftEvents.length = 0;\n layoutInvalidationEvents.length = 0;\n scheduleStyleInvalidationEvents.length = 0;\n styleRecalcInvalidationEvents.length = 0;\n prePaintEvents.length = 0;\n backendNodeIds.clear();\n clusters.length = 0;\n sessionMaxScore = 0;\n scoreRecords.length = 0;\n clsWindowID = -1;\n}\n\nexport function handleEvent(event: Types.TraceEvents.TraceEventData): void {\n if (handlerState !== HandlerState.INITIALIZED) {\n throw new Error('Handler is not initialized');\n }\n\n if (Types.TraceEvents.isTraceEventLayoutShift(event) && !event.args.data?.had_recent_input) {\n layoutShiftEvents.push(event);\n return;\n }\n if (Types.TraceEvents.isTraceEventLayoutInvalidationTracking(event)) {\n layoutInvalidationEvents.push(event);\n return;\n }\n if (Types.TraceEvents.isTraceEventScheduleStyleInvalidationTracking(event)) {\n scheduleStyleInvalidationEvents.push(event);\n }\n if (Types.TraceEvents.isTraceEventStyleRecalcInvalidationTracking(event)) {\n styleRecalcInvalidationEvents.push(event);\n }\n if (Types.TraceEvents.isTraceEventPrePaint(event)) {\n prePaintEvents.push(event);\n return;\n }\n}\n\nfunction traceWindowFromTime(time: Types.Timing.MicroSeconds): Types.Timing.TraceWindowMicroSeconds {\n return {\n min: time,\n max: time,\n range: Types.Timing.MicroSeconds(0),\n };\n}\n\nfunction updateTraceWindowMax(\n traceWindow: Types.Timing.TraceWindowMicroSeconds, newMax: Types.Timing.MicroSeconds): void {\n traceWindow.max = newMax;\n traceWindow.range = Types.Timing.MicroSeconds(traceWindow.max - traceWindow.min);\n}\n\nfunction buildScoreRecords(): void {\n const {traceBounds} = metaHandlerData();\n scoreRecords.push({ts: traceBounds.min, score: 0});\n\n for (const cluster of clusters) {\n let clusterScore = 0;\n if (cluster.events[0].args.data) {\n scoreRecords.push({ts: cluster.clusterWindow.min, score: cluster.events[0].args.data.weighted_score_delta});\n }\n for (let i = 0; i < cluster.events.length; i++) {\n const event = cluster.events[i];\n if (!event.args.data) {\n continue;\n }\n clusterScore += event.args.data.weighted_score_delta;\n scoreRecords.push({ts: event.ts, score: clusterScore});\n }\n scoreRecords.push({ts: cluster.clusterWindow.max, score: 0});\n }\n}\n\n/**\n * Collects backend node ids coming from LayoutShift and LayoutInvalidation\n * events.\n */\nfunction collectNodes(): void {\n backendNodeIds.clear();\n\n // Collect the node ids present in the shifts.\n for (const layoutShift of layoutShiftEvents) {\n if (!layoutShift.args.data?.impacted_nodes) {\n continue;\n }\n for (const node of layoutShift.args.data.impacted_nodes) {\n backendNodeIds.add(node.node_id);\n }\n }\n\n // Collect the node ids present in LayoutInvalidation & scheduleStyleInvalidation events.\n for (const layoutInvalidation of layoutInvalidationEvents) {\n if (!layoutInvalidation.args.data?.nodeId) {\n continue;\n }\n backendNodeIds.add(layoutInvalidation.args.data.nodeId);\n }\n for (const scheduleStyleInvalidation of scheduleStyleInvalidationEvents) {\n if (!scheduleStyleInvalidation.args.data?.nodeId) {\n continue;\n }\n backendNodeIds.add(scheduleStyleInvalidation.args.data.nodeId);\n }\n}\n\nexport async function finalize(): Promise<void> {\n // Ensure the events are sorted by #time ascending.\n layoutShiftEvents.sort((a, b) => a.ts - b.ts);\n prePaintEvents.sort((a, b) => a.ts - b.ts);\n layoutInvalidationEvents.sort((a, b) => a.ts - b.ts);\n\n // Each function transforms the data used by the next, as such the invoke order\n // is important.\n await buildLayoutShiftsClusters();\n buildScoreRecords();\n collectNodes();\n handlerState = HandlerState.FINALIZED;\n}\n\nasync function buildLayoutShiftsClusters(): Promise<void> {\n const {navigationsByFrameId, mainFrameId, traceBounds} = metaHandlerData();\n const navigations = navigationsByFrameId.get(mainFrameId) || [];\n if (layoutShiftEvents.length === 0) {\n return;\n }\n let firstShiftTime = layoutShiftEvents[0].ts;\n let lastShiftTime = layoutShiftEvents[0].ts;\n let lastShiftNavigation = null;\n // Now step through each and create clusters.\n // A cluster is equivalent to a session window (see https://web.dev/cls/#what-is-cls).\n // To make the line chart clear, we explicitly demark the limits of each session window\n // by starting the cumulative score of the window at the time of the first layout shift\n // and ending it (dropping the line back to 0) when the window ends according to the\n // thresholds (MAX_CLUSTER_DURATION, MAX_SHIFT_TIME_DELTA).\n for (const event of layoutShiftEvents) {\n // First detect if either the cluster duration or the #time between this and\n // the last shift has been exceeded.\n const clusterDurationExceeded = event.ts - firstShiftTime > MAX_CLUSTER_DURATION;\n const maxTimeDeltaSinceLastShiftExceeded = event.ts - lastShiftTime > MAX_SHIFT_TIME_DELTA;\n\n // Next take a look at navigations. If between this and the last shift we have navigated,\n // note it.\n const currentShiftNavigation = Platform.ArrayUtilities.nearestIndexFromEnd(navigations, nav => nav.ts < event.ts);\n const hasNavigated = lastShiftNavigation !== currentShiftNavigation && currentShiftNavigation !== null;\n\n // If any of the above criteria are met or if we don't have any cluster yet we should\n // start a new one.\n if (clusterDurationExceeded || maxTimeDeltaSinceLastShiftExceeded || hasNavigated || !clusters.length) {\n // The cluster starts #time should be the timestamp of the first layout shift in it.\n const clusterStartTime = event.ts;\n\n // If the last session window ended because the max delta time between shifts\n // was exceeded set the endtime to MAX_SHIFT_TIME_DELTA microseconds after the\n // last shift in the session.\n const endTimeByMaxSessionDuration = clusterDurationExceeded ? firstShiftTime + MAX_CLUSTER_DURATION : Infinity;\n\n // If the last session window ended because the max session duration was\n // surpassed, set the endtime so that the window length = MAX_CLUSTER_DURATION;\n const endTimeByMaxShiftGap = maxTimeDeltaSinceLastShiftExceeded ? lastShiftTime + MAX_SHIFT_TIME_DELTA : Infinity;\n\n // If there was a navigation during the last window, close it at the time\n // of the navigation.\n const endTimeByNavigation = hasNavigated ? navigations[currentShiftNavigation].ts : Infinity;\n\n // End the previous cluster at the time of the first of the criteria above that was met.\n const previousClusterEndTime = Math.min(endTimeByMaxSessionDuration, endTimeByMaxShiftGap, endTimeByNavigation);\n\n // If there is an existing cluster update its closing time.\n if (clusters.length > 0) {\n const currentCluster = clusters[clusters.length - 1];\n updateTraceWindowMax(currentCluster.clusterWindow, Types.Timing.MicroSeconds(previousClusterEndTime));\n }\n\n clusters.push({\n events: [],\n clusterWindow: traceWindowFromTime(clusterStartTime),\n clusterCumulativeScore: 0,\n scoreWindows: {\n good: traceWindowFromTime(clusterStartTime),\n needsImprovement: null,\n bad: null,\n },\n });\n\n firstShiftTime = clusterStartTime;\n }\n\n // Given the above we should have a cluster available, so pick the most\n // recent one and append the shift, bump its score and window values accordingly.\n const currentCluster = clusters[clusters.length - 1];\n const timeFromNavigation = currentShiftNavigation !== null ?\n Types.Timing.MicroSeconds(event.ts - navigations[currentShiftNavigation].ts) :\n undefined;\n\n currentCluster.clusterCumulativeScore += event.args.data ? event.args.data.weighted_score_delta : 0;\n if (!event.args.data) {\n continue;\n }\n const shift: Types.TraceEvents.SyntheticLayoutShift = {\n ...event,\n args: {\n frame: event.args.frame,\n data: {\n ...event.args.data,\n rawEvent: event,\n },\n },\n parsedData: {\n timeFromNavigation,\n cumulativeWeightedScoreInWindow: currentCluster.clusterCumulativeScore,\n // The score of the session window is temporarily set to 0 just\n // to initialize it. Since we need to get the score of all shifts\n // in the session window to determine its value, its definite\n // value is set when stepping through the built clusters.\n sessionWindowData: {cumulativeWindowScore: 0, id: clusters.length},\n },\n };\n currentCluster.events.push(shift);\n updateTraceWindowMax(currentCluster.clusterWindow, event.ts);\n\n lastShiftTime = event.ts;\n lastShiftNavigation = currentShiftNavigation;\n }\n\n // Now step through each cluster and set up the times at which the value\n // goes from Good, to needs improvement, to Bad. Note that if there is a\n // large jump we may go from Good to Bad without ever creating a Needs\n // Improvement window at all.\n for (const cluster of clusters) {\n let weightedScore = 0;\n let windowID = -1;\n // If this is the last cluster update its window. The cluster duration is determined\n // by the minimum between: time to next navigation, trace end time, time to maximum\n // cluster duration and time to maximum gap between layout shifts.\n if (cluster === clusters[clusters.length - 1]) {\n const clusterEndByMaxDuration = MAX_CLUSTER_DURATION + cluster.clusterWindow.min;\n const clusterEndByMaxGap = cluster.clusterWindow.max + MAX_SHIFT_TIME_DELTA;\n const nextNavigationIndex =\n Platform.ArrayUtilities.nearestIndexFromBeginning(navigations, nav => nav.ts > cluster.clusterWindow.max);\n const nextNavigationTime = nextNavigationIndex ? navigations[nextNavigationIndex].ts : Infinity;\n const clusterEnd = Math.min(clusterEndByMaxDuration, clusterEndByMaxGap, traceBounds.max, nextNavigationTime);\n updateTraceWindowMax(cluster.clusterWindow, Types.Timing.MicroSeconds(clusterEnd));\n }\n for (const shift of cluster.events) {\n weightedScore += shift.args.data ? shift.args.data.weighted_score_delta : 0;\n windowID = shift.parsedData.sessionWindowData.id;\n const ts = shift.ts;\n // Update the the CLS score of this shift's session window now that\n // we have it.\n shift.parsedData.sessionWindowData.cumulativeWindowScore = cluster.clusterCumulativeScore;\n if (weightedScore < LayoutShiftsThreshold.NEEDS_IMPROVEMENT) {\n // Expand the Good window.\n updateTraceWindowMax(cluster.scoreWindows.good, ts);\n } else if (\n weightedScore >= LayoutShiftsThreshold.NEEDS_IMPROVEMENT && weightedScore < LayoutShiftsThreshold.BAD) {\n if (!cluster.scoreWindows.needsImprovement) {\n // Close the Good window, and open the needs improvement window.\n updateTraceWindowMax(cluster.scoreWindows.good, Types.Timing.MicroSeconds(ts - 1));\n cluster.scoreWindows.needsImprovement = traceWindowFromTime(ts);\n }\n\n // Expand the needs improvement window.\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, ts);\n } else if (weightedScore >= LayoutShiftsThreshold.BAD) {\n if (!cluster.scoreWindows.bad) {\n // We may jump from Good to Bad here, so update whichever window is open.\n if (cluster.scoreWindows.needsImprovement) {\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, Types.Timing.MicroSeconds(ts - 1));\n } else {\n updateTraceWindowMax(cluster.scoreWindows.good, Types.Timing.MicroSeconds(ts - 1));\n }\n\n cluster.scoreWindows.bad = traceWindowFromTime(shift.ts);\n }\n\n // Expand the Bad window.\n updateTraceWindowMax(cluster.scoreWindows.bad, ts);\n }\n\n // At this point the windows are set by the timestamps of the events, but the\n // next cluster begins at the timestamp of its first event. As such we now\n // need to expand the score window to the end of the cluster, and we do so\n // by using the Bad widow if it's there, or the NI window, or finally the\n // Good window.\n if (cluster.scoreWindows.bad) {\n updateTraceWindowMax(cluster.scoreWindows.bad, cluster.clusterWindow.max);\n } else if (cluster.scoreWindows.needsImprovement) {\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, cluster.clusterWindow.max);\n } else {\n updateTraceWindowMax(cluster.scoreWindows.good, cluster.clusterWindow.max);\n }\n }\n if (weightedScore > sessionMaxScore) {\n clsWindowID = windowID;\n sessionMaxScore = weightedScore;\n }\n }\n}\n\nexport function data(): LayoutShifts {\n if (handlerState !== HandlerState.FINALIZED) {\n throw new Error('Layout Shifts Handler is not finalized');\n }\n\n return {\n clusters,\n sessionMaxScore: sessionMaxScore,\n clsWindowID,\n prePaintEvents,\n layoutInvalidationEvents,\n scheduleStyleInvalidationEvents,\n styleRecalcInvalidationEvents: [],\n scoreRecords,\n // TODO(crbug/41484172): change the type so no need to clone\n backendNodeIds: [...backendNodeIds],\n };\n}\n\nexport function deps(): TraceEventHandlerName[] {\n return ['Screenshots', 'Meta'];\n}\n\nexport function stateForLayoutShiftScore(score: number): ScoreClassification {\n let state = ScoreClassification.GOOD;\n if (score >= LayoutShiftsThreshold.NEEDS_IMPROVEMENT) {\n state = ScoreClassification.OK;\n }\n\n if (score >= LayoutShiftsThreshold.BAD) {\n state = ScoreClassification.BAD;\n }\n\n return state;\n}\n\nexport interface LayoutShiftCluster {\n clusterWindow: Types.Timing.TraceWindowMicroSeconds;\n clusterCumulativeScore: number;\n events: Types.TraceEvents.SyntheticLayoutShift[];\n // For convenience we split apart the cluster into good, NI, and bad windows.\n // Since a cluster may remain in the good window, we mark NI and bad as being\n // possibly null.\n scoreWindows: {\n good: Types.Timing.TraceWindowMicroSeconds,\n needsImprovement: Types.Timing.TraceWindowMicroSeconds|null,\n bad: Types.Timing.TraceWindowMicroSeconds|null,\n };\n}\n\n// Based on https://web.dev/cls/\nexport const enum LayoutShiftsThreshold {\n GOOD = 0,\n NEEDS_IMPROVEMENT = 0.1,\n BAD = 0.25,\n}\n"]}
|
|
1
|
+
{"version":3,"file":"LayoutShiftsHandler.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/handlers/LayoutShiftsHandler.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,QAAQ,MAAM,oCAAoC,CAAC;AAE/D,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,IAAI,IAAI,eAAe,EAAC,MAAM,kBAAkB,CAAC;AA6CzD,4EAA4E;AAC5E,YAAY;AACZ,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAE/G,8EAA8E;AAC9E,0DAA0D;AAC1D,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAE/G,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,UAAU;AACV,MAAM,i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,OAAO;QACL,QAAQ;QACR,eAAe,EAAE,eAAe;QAChC,WAAW;QACX,cAAc;QACd,wBAAwB;QACxB,+BAA+B;QAC/B,6BAA6B,EAAE,EAAE;QACjC,YAAY;QACZ,4DAA4D;QAC5D,cAAc,EAAE,CAAC,GAAG,cAAc,CAAC;KACpC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,IAAI;IAClB,OAAO,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACpD,IAAI,KAAK,wCAA2B,CAAC;IACrC,IAAI,KAAK,qDAA2C,EAAE,CAAC;QACrD,KAAK,oCAAyB,CAAC;IACjC,CAAC;IAED,IAAI,KAAK,wCAA6B,EAAE,CAAC;QACvC,KAAK,sCAA0B,CAAC;IAClC,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright 2022 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as Platform from '../../../core/platform/platform.js';\nimport type * as Protocol from '../../../generated/protocol.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {data as metaHandlerData} from './MetaHandler.js';\nimport {ScoreClassification} from './PageLoadMetricsHandler.js';\nimport {HandlerState, type TraceEventHandlerName} from './types.js';\n\n// We start with a score of zero and step through all Layout Shift records from\n// all renderers. Each record not only tells us which renderer it is, but also\n// the unweighted and weighted scores. The unweighted score is the score we would\n// get if the renderer were the only one in the viewport. The weighted score, on\n// the other hand, accounts for how much of the viewport that particular render\n// takes up when the shift happened. An ad frame in the corner of the viewport\n// that shifts is considered less disruptive, therefore, than if it were taking\n// up the whole viewport.\n//\n// Next, we step through all the records from all renderers and add the weighted\n// score to a running total across all of the renderers. We create a new \"cluster\"\n// and reset the running total when:\n//\n// 1. We observe a outermost frame navigation, or\n// 2. When there's a gap between records of > 1s, or\n// 3. When there's more than 5 seconds of continuous layout shifting.\n//\n// Note that for it to be Cumulative Layout Shift in the sense described in the\n// documentation we would need to guarantee that we are tracking from navigation\n// to unload. However, we don't make any such guarantees here (since a developer\n// can record and stop when they please), so we support the cluster approach,\n// and we can give them a score, but it is effectively a \"session\" score, a\n// score for the given recording, and almost certainly not the\n// navigation-to-unload CLS score.\n\ninterface LayoutShifts {\n clusters: readonly LayoutShiftCluster[];\n sessionMaxScore: number;\n // The session window which contains the SessionMaxScore\n clsWindowID: number;\n // We use these to calculate root causes for a given LayoutShift\n // TODO(crbug/41484172): should be readonly\n prePaintEvents: Types.TraceEvents.TraceEventPrePaint[];\n layoutInvalidationEvents: readonly Types.TraceEvents.TraceEventLayoutInvalidationTracking[];\n scheduleStyleInvalidationEvents: readonly Types.TraceEvents.TraceEventScheduleStyleInvalidationTracking[];\n styleRecalcInvalidationEvents: readonly Types.TraceEvents.TraceEventStyleRecalcInvalidationTracking[];\n scoreRecords: readonly ScoreRecord[];\n // TODO(crbug/41484172): should be readonly\n backendNodeIds: Protocol.DOM.BackendNodeId[];\n}\n\n// This represents the maximum #time we will allow a cluster to go before we\n// reset it.\nexport const MAX_CLUSTER_DURATION = Helpers.Timing.millisecondsToMicroseconds(Types.Timing.MilliSeconds(5000));\n\n// This represents the maximum #time we will allow between layout shift events\n// before considering it to be the start of a new cluster.\nexport const MAX_SHIFT_TIME_DELTA = Helpers.Timing.millisecondsToMicroseconds(Types.Timing.MilliSeconds(1000));\n\n// Layout shifts are reported globally to the developer, irrespective of which\n// frame they originated in. However, each process does have its own individual\n// CLS score, so we need to segment by process. This means Layout Shifts from\n// sites with one process (no subframes, or subframes from the same origin)\n// will be reported together. In the case of multiple renderers (frames across\n// different origins), we offer the developer the ability to switch renderer in\n// the UI.\nconst layoutShiftEvents: Types.TraceEvents.TraceEventLayoutShift[] = [];\n\n// These events denote potential node resizings. We store them to link captured\n// layout shifts to the resizing of unsized elements.\nconst layoutInvalidationEvents: Types.TraceEvents.TraceEventLayoutInvalidationTracking[] = [];\nconst scheduleStyleInvalidationEvents: Types.TraceEvents.TraceEventScheduleStyleInvalidationTracking[] = [];\nconst styleRecalcInvalidationEvents: Types.TraceEvents.TraceEventStyleRecalcInvalidationTracking[] = [];\n\nconst backendNodeIds = new Set<Protocol.DOM.BackendNodeId>();\n\n// Layout shifts happen during PrePaint as part of the rendering lifecycle.\n// We determine if a LayoutInvalidation event is a potential root cause of a layout\n// shift if the next PrePaint after the LayoutInvalidation is the parent\n// node of such shift.\nconst prePaintEvents: Types.TraceEvents.TraceEventPrePaint[] = [];\n\nlet sessionMaxScore = 0;\n\nlet clsWindowID = -1;\n\nconst clusters: LayoutShiftCluster[] = [];\n\n// Represents a point in time in which a LS score change\n// was recorded.\ntype ScoreRecord = {\n ts: number,\n score: number,\n};\n\n// The complete timeline of LS score changes in a trace.\n// Includes drops to 0 when session windows end.\nconst scoreRecords: ScoreRecord[] = [];\n\nlet handlerState = HandlerState.UNINITIALIZED;\n\nexport function initialize(): void {\n if (handlerState !== HandlerState.UNINITIALIZED) {\n throw new Error('LayoutShifts Handler was not reset');\n }\n handlerState = HandlerState.INITIALIZED;\n}\n\nexport function reset(): void {\n handlerState = HandlerState.UNINITIALIZED;\n layoutShiftEvents.length = 0;\n layoutInvalidationEvents.length = 0;\n scheduleStyleInvalidationEvents.length = 0;\n styleRecalcInvalidationEvents.length = 0;\n prePaintEvents.length = 0;\n backendNodeIds.clear();\n clusters.length = 0;\n sessionMaxScore = 0;\n scoreRecords.length = 0;\n clsWindowID = -1;\n}\n\nexport function handleEvent(event: Types.TraceEvents.TraceEventData): void {\n if (handlerState !== HandlerState.INITIALIZED) {\n throw new Error('Handler is not initialized');\n }\n\n if (Types.TraceEvents.isTraceEventLayoutShift(event) && !event.args.data?.had_recent_input) {\n layoutShiftEvents.push(event);\n return;\n }\n if (Types.TraceEvents.isTraceEventLayoutInvalidationTracking(event)) {\n layoutInvalidationEvents.push(event);\n return;\n }\n if (Types.TraceEvents.isTraceEventScheduleStyleInvalidationTracking(event)) {\n scheduleStyleInvalidationEvents.push(event);\n }\n if (Types.TraceEvents.isTraceEventStyleRecalcInvalidationTracking(event)) {\n styleRecalcInvalidationEvents.push(event);\n }\n if (Types.TraceEvents.isTraceEventPrePaint(event)) {\n prePaintEvents.push(event);\n return;\n }\n}\n\nfunction traceWindowFromTime(time: Types.Timing.MicroSeconds): Types.Timing.TraceWindowMicroSeconds {\n return {\n min: time,\n max: time,\n range: Types.Timing.MicroSeconds(0),\n };\n}\n\nfunction updateTraceWindowMax(\n traceWindow: Types.Timing.TraceWindowMicroSeconds, newMax: Types.Timing.MicroSeconds): void {\n traceWindow.max = newMax;\n traceWindow.range = Types.Timing.MicroSeconds(traceWindow.max - traceWindow.min);\n}\n\nfunction buildScoreRecords(): void {\n const {traceBounds} = metaHandlerData();\n scoreRecords.push({ts: traceBounds.min, score: 0});\n\n for (const cluster of clusters) {\n let clusterScore = 0;\n if (cluster.events[0].args.data) {\n scoreRecords.push({ts: cluster.clusterWindow.min, score: cluster.events[0].args.data.weighted_score_delta});\n }\n for (let i = 0; i < cluster.events.length; i++) {\n const event = cluster.events[i];\n if (!event.args.data) {\n continue;\n }\n clusterScore += event.args.data.weighted_score_delta;\n scoreRecords.push({ts: event.ts, score: clusterScore});\n }\n scoreRecords.push({ts: cluster.clusterWindow.max, score: 0});\n }\n}\n\n/**\n * Collects backend node ids coming from LayoutShift and LayoutInvalidation\n * events.\n */\nfunction collectNodes(): void {\n backendNodeIds.clear();\n\n // Collect the node ids present in the shifts.\n for (const layoutShift of layoutShiftEvents) {\n if (!layoutShift.args.data?.impacted_nodes) {\n continue;\n }\n for (const node of layoutShift.args.data.impacted_nodes) {\n backendNodeIds.add(node.node_id);\n }\n }\n\n // Collect the node ids present in LayoutInvalidation & scheduleStyleInvalidation events.\n for (const layoutInvalidation of layoutInvalidationEvents) {\n if (!layoutInvalidation.args.data?.nodeId) {\n continue;\n }\n backendNodeIds.add(layoutInvalidation.args.data.nodeId);\n }\n for (const scheduleStyleInvalidation of scheduleStyleInvalidationEvents) {\n if (!scheduleStyleInvalidation.args.data?.nodeId) {\n continue;\n }\n backendNodeIds.add(scheduleStyleInvalidation.args.data.nodeId);\n }\n}\n\nexport async function finalize(): Promise<void> {\n // Ensure the events are sorted by #time ascending.\n layoutShiftEvents.sort((a, b) => a.ts - b.ts);\n prePaintEvents.sort((a, b) => a.ts - b.ts);\n layoutInvalidationEvents.sort((a, b) => a.ts - b.ts);\n\n // Each function transforms the data used by the next, as such the invoke order\n // is important.\n await buildLayoutShiftsClusters();\n buildScoreRecords();\n collectNodes();\n handlerState = HandlerState.FINALIZED;\n}\n\nasync function buildLayoutShiftsClusters(): Promise<void> {\n const {navigationsByFrameId, mainFrameId, traceBounds} = metaHandlerData();\n const navigations = navigationsByFrameId.get(mainFrameId) || [];\n if (layoutShiftEvents.length === 0) {\n return;\n }\n let firstShiftTime = layoutShiftEvents[0].ts;\n let lastShiftTime = layoutShiftEvents[0].ts;\n let lastShiftNavigation = null;\n // Now step through each and create clusters.\n // A cluster is equivalent to a session window (see https://web.dev/cls/#what-is-cls).\n // To make the line chart clear, we explicitly demark the limits of each session window\n // by starting the cumulative score of the window at the time of the first layout shift\n // and ending it (dropping the line back to 0) when the window ends according to the\n // thresholds (MAX_CLUSTER_DURATION, MAX_SHIFT_TIME_DELTA).\n for (const event of layoutShiftEvents) {\n // First detect if either the cluster duration or the #time between this and\n // the last shift has been exceeded.\n const clusterDurationExceeded = event.ts - firstShiftTime > MAX_CLUSTER_DURATION;\n const maxTimeDeltaSinceLastShiftExceeded = event.ts - lastShiftTime > MAX_SHIFT_TIME_DELTA;\n\n // Next take a look at navigations. If between this and the last shift we have navigated,\n // note it.\n const currentShiftNavigation = Platform.ArrayUtilities.nearestIndexFromEnd(navigations, nav => nav.ts < event.ts);\n const hasNavigated = lastShiftNavigation !== currentShiftNavigation && currentShiftNavigation !== null;\n\n // If any of the above criteria are met or if we don't have any cluster yet we should\n // start a new one.\n if (clusterDurationExceeded || maxTimeDeltaSinceLastShiftExceeded || hasNavigated || !clusters.length) {\n // The cluster starts #time should be the timestamp of the first layout shift in it.\n const clusterStartTime = event.ts;\n\n // If the last session window ended because the max delta time between shifts\n // was exceeded set the endtime to MAX_SHIFT_TIME_DELTA microseconds after the\n // last shift in the session.\n const endTimeByMaxSessionDuration = clusterDurationExceeded ? firstShiftTime + MAX_CLUSTER_DURATION : Infinity;\n\n // If the last session window ended because the max session duration was\n // surpassed, set the endtime so that the window length = MAX_CLUSTER_DURATION;\n const endTimeByMaxShiftGap = maxTimeDeltaSinceLastShiftExceeded ? lastShiftTime + MAX_SHIFT_TIME_DELTA : Infinity;\n\n // If there was a navigation during the last window, close it at the time\n // of the navigation.\n const endTimeByNavigation = hasNavigated ? navigations[currentShiftNavigation].ts : Infinity;\n\n // End the previous cluster at the time of the first of the criteria above that was met.\n const previousClusterEndTime = Math.min(endTimeByMaxSessionDuration, endTimeByMaxShiftGap, endTimeByNavigation);\n\n // If there is an existing cluster update its closing time.\n if (clusters.length > 0) {\n const currentCluster = clusters[clusters.length - 1];\n updateTraceWindowMax(currentCluster.clusterWindow, Types.Timing.MicroSeconds(previousClusterEndTime));\n }\n\n clusters.push({\n events: [],\n clusterWindow: traceWindowFromTime(clusterStartTime),\n clusterCumulativeScore: 0,\n scoreWindows: {\n good: traceWindowFromTime(clusterStartTime),\n needsImprovement: null,\n bad: null,\n },\n });\n\n firstShiftTime = clusterStartTime;\n }\n\n // Given the above we should have a cluster available, so pick the most\n // recent one and append the shift, bump its score and window values accordingly.\n const currentCluster = clusters[clusters.length - 1];\n const timeFromNavigation = currentShiftNavigation !== null ?\n Types.Timing.MicroSeconds(event.ts - navigations[currentShiftNavigation].ts) :\n undefined;\n\n currentCluster.clusterCumulativeScore += event.args.data ? event.args.data.weighted_score_delta : 0;\n if (!event.args.data) {\n continue;\n }\n const shift: Types.TraceEvents.SyntheticLayoutShift = {\n rawSourceEvent: event,\n ...event,\n args: {\n frame: event.args.frame,\n data: {\n ...event.args.data,\n rawEvent: event,\n },\n },\n parsedData: {\n timeFromNavigation,\n cumulativeWeightedScoreInWindow: currentCluster.clusterCumulativeScore,\n // The score of the session window is temporarily set to 0 just\n // to initialize it. Since we need to get the score of all shifts\n // in the session window to determine its value, its definite\n // value is set when stepping through the built clusters.\n sessionWindowData: {cumulativeWindowScore: 0, id: clusters.length},\n },\n };\n currentCluster.events.push(shift);\n updateTraceWindowMax(currentCluster.clusterWindow, event.ts);\n\n lastShiftTime = event.ts;\n lastShiftNavigation = currentShiftNavigation;\n }\n\n // Now step through each cluster and set up the times at which the value\n // goes from Good, to needs improvement, to Bad. Note that if there is a\n // large jump we may go from Good to Bad without ever creating a Needs\n // Improvement window at all.\n for (const cluster of clusters) {\n let weightedScore = 0;\n let windowID = -1;\n // If this is the last cluster update its window. The cluster duration is determined\n // by the minimum between: time to next navigation, trace end time, time to maximum\n // cluster duration and time to maximum gap between layout shifts.\n if (cluster === clusters[clusters.length - 1]) {\n const clusterEndByMaxDuration = MAX_CLUSTER_DURATION + cluster.clusterWindow.min;\n const clusterEndByMaxGap = cluster.clusterWindow.max + MAX_SHIFT_TIME_DELTA;\n const nextNavigationIndex =\n Platform.ArrayUtilities.nearestIndexFromBeginning(navigations, nav => nav.ts > cluster.clusterWindow.max);\n const nextNavigationTime = nextNavigationIndex ? navigations[nextNavigationIndex].ts : Infinity;\n const clusterEnd = Math.min(clusterEndByMaxDuration, clusterEndByMaxGap, traceBounds.max, nextNavigationTime);\n updateTraceWindowMax(cluster.clusterWindow, Types.Timing.MicroSeconds(clusterEnd));\n }\n for (const shift of cluster.events) {\n weightedScore += shift.args.data ? shift.args.data.weighted_score_delta : 0;\n windowID = shift.parsedData.sessionWindowData.id;\n const ts = shift.ts;\n // Update the the CLS score of this shift's session window now that\n // we have it.\n shift.parsedData.sessionWindowData.cumulativeWindowScore = cluster.clusterCumulativeScore;\n if (weightedScore < LayoutShiftsThreshold.NEEDS_IMPROVEMENT) {\n // Expand the Good window.\n updateTraceWindowMax(cluster.scoreWindows.good, ts);\n } else if (\n weightedScore >= LayoutShiftsThreshold.NEEDS_IMPROVEMENT && weightedScore < LayoutShiftsThreshold.BAD) {\n if (!cluster.scoreWindows.needsImprovement) {\n // Close the Good window, and open the needs improvement window.\n updateTraceWindowMax(cluster.scoreWindows.good, Types.Timing.MicroSeconds(ts - 1));\n cluster.scoreWindows.needsImprovement = traceWindowFromTime(ts);\n }\n\n // Expand the needs improvement window.\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, ts);\n } else if (weightedScore >= LayoutShiftsThreshold.BAD) {\n if (!cluster.scoreWindows.bad) {\n // We may jump from Good to Bad here, so update whichever window is open.\n if (cluster.scoreWindows.needsImprovement) {\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, Types.Timing.MicroSeconds(ts - 1));\n } else {\n updateTraceWindowMax(cluster.scoreWindows.good, Types.Timing.MicroSeconds(ts - 1));\n }\n\n cluster.scoreWindows.bad = traceWindowFromTime(shift.ts);\n }\n\n // Expand the Bad window.\n updateTraceWindowMax(cluster.scoreWindows.bad, ts);\n }\n\n // At this point the windows are set by the timestamps of the events, but the\n // next cluster begins at the timestamp of its first event. As such we now\n // need to expand the score window to the end of the cluster, and we do so\n // by using the Bad widow if it's there, or the NI window, or finally the\n // Good window.\n if (cluster.scoreWindows.bad) {\n updateTraceWindowMax(cluster.scoreWindows.bad, cluster.clusterWindow.max);\n } else if (cluster.scoreWindows.needsImprovement) {\n updateTraceWindowMax(cluster.scoreWindows.needsImprovement, cluster.clusterWindow.max);\n } else {\n updateTraceWindowMax(cluster.scoreWindows.good, cluster.clusterWindow.max);\n }\n }\n if (weightedScore > sessionMaxScore) {\n clsWindowID = windowID;\n sessionMaxScore = weightedScore;\n }\n }\n}\n\nexport function data(): LayoutShifts {\n if (handlerState !== HandlerState.FINALIZED) {\n throw new Error('Layout Shifts Handler is not finalized');\n }\n\n return {\n clusters,\n sessionMaxScore: sessionMaxScore,\n clsWindowID,\n prePaintEvents,\n layoutInvalidationEvents,\n scheduleStyleInvalidationEvents,\n styleRecalcInvalidationEvents: [],\n scoreRecords,\n // TODO(crbug/41484172): change the type so no need to clone\n backendNodeIds: [...backendNodeIds],\n };\n}\n\nexport function deps(): TraceEventHandlerName[] {\n return ['Screenshots', 'Meta'];\n}\n\nexport function stateForLayoutShiftScore(score: number): ScoreClassification {\n let state = ScoreClassification.GOOD;\n if (score >= LayoutShiftsThreshold.NEEDS_IMPROVEMENT) {\n state = ScoreClassification.OK;\n }\n\n if (score >= LayoutShiftsThreshold.BAD) {\n state = ScoreClassification.BAD;\n }\n\n return state;\n}\n\nexport interface LayoutShiftCluster {\n clusterWindow: Types.Timing.TraceWindowMicroSeconds;\n clusterCumulativeScore: number;\n events: Types.TraceEvents.SyntheticLayoutShift[];\n // For convenience we split apart the cluster into good, NI, and bad windows.\n // Since a cluster may remain in the good window, we mark NI and bad as being\n // possibly null.\n scoreWindows: {\n good: Types.Timing.TraceWindowMicroSeconds,\n needsImprovement: Types.Timing.TraceWindowMicroSeconds|null,\n bad: Types.Timing.TraceWindowMicroSeconds|null,\n };\n}\n\n// Based on https://web.dev/cls/\nexport const enum LayoutShiftsThreshold {\n GOOD = 0,\n NEEDS_IMPROVEMENT = 0.1,\n BAD = 0.25,\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type TraceEventHandlerName } from './types.js';
|
|
2
1
|
import * as Types from '../types/types.js';
|
|
2
|
+
import { type TraceEventHandlerName } from './types.js';
|
|
3
3
|
interface NetworkRequestData {
|
|
4
4
|
byOrigin: Map<string, {
|
|
5
5
|
renderBlocking: Types.TraceEvents.SyntheticNetworkRequest[];
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
// Use of this source code is governed by a BSD-style license that can be
|
|
3
3
|
// found in the LICENSE file.
|
|
4
4
|
import * as Platform from '../../../core/platform/platform.js';
|
|
5
|
-
import { data as metaHandlerData } from './MetaHandler.js';
|
|
6
5
|
import * as Helpers from '../helpers/helpers.js';
|
|
7
6
|
import * as Types from '../types/types.js';
|
|
7
|
+
import { data as metaHandlerData } from './MetaHandler.js';
|
|
8
8
|
const MILLISECONDS_TO_MICROSECONDS = 1000;
|
|
9
9
|
const SECONDS_TO_MICROSECONDS = 1000000;
|
|
10
10
|
const requestMap = new Map();
|
|
@@ -260,11 +260,12 @@ export async function finalize() {
|
|
|
260
260
|
// Finally get some of the general data from the trace events.
|
|
261
261
|
const { frame, url, renderBlocking } = finalSendRequest.args.data;
|
|
262
262
|
const { encodedDataLength, decodedBodyLength } = request.resourceFinish ? request.resourceFinish.args.data : { encodedDataLength: 0, decodedBodyLength: 0 };
|
|
263
|
-
const
|
|
264
|
-
const isHttps = protocol === 'https:';
|
|
263
|
+
const parsedUrl = new URL(url);
|
|
264
|
+
const isHttps = parsedUrl.protocol === 'https:';
|
|
265
265
|
const requestingFrameUrl = Helpers.Trace.activeURLForFrameAtTime(frame, finalSendRequest.ts, rendererProcessesByFrame) || '';
|
|
266
266
|
// Construct a synthetic trace event for this network request.
|
|
267
267
|
const networkEvent = {
|
|
268
|
+
rawSourceEvent: finalSendRequest,
|
|
268
269
|
args: {
|
|
269
270
|
data: {
|
|
270
271
|
// All data we create from trace events should be added to |syntheticData|.
|
|
@@ -296,12 +297,10 @@ export async function finalize() {
|
|
|
296
297
|
frame,
|
|
297
298
|
fromServiceWorker: request.receiveResponse.args.data.fromServiceWorker,
|
|
298
299
|
isLinkPreload: request.receiveResponse.args.data.isLinkPreload || false,
|
|
299
|
-
host,
|
|
300
300
|
mimeType: request.receiveResponse.args.data.mimeType,
|
|
301
|
-
pathname,
|
|
302
301
|
priority: finalPriority,
|
|
303
302
|
initialPriority,
|
|
304
|
-
protocol,
|
|
303
|
+
protocol: request.receiveResponse.args.data.protocol ?? 'unknown',
|
|
305
304
|
redirects,
|
|
306
305
|
// In the event the property isn't set, assume non-blocking.
|
|
307
306
|
renderBlocking: renderBlocking ? renderBlocking : 'non_blocking',
|
|
@@ -309,7 +308,6 @@ export async function finalize() {
|
|
|
309
308
|
requestingFrameUrl,
|
|
310
309
|
requestMethod: finalSendRequest.args.data.requestMethod,
|
|
311
310
|
resourceType: finalSendRequest.args.data.resourceType,
|
|
312
|
-
search,
|
|
313
311
|
statusCode: request.receiveResponse.args.data.statusCode,
|
|
314
312
|
responseHeaders: request.receiveResponse.args.data.headers || [],
|
|
315
313
|
fetchPriorityHint: finalSendRequest.args.data.fetchPriorityHint,
|
|
@@ -333,7 +331,7 @@ export async function finalize() {
|
|
|
333
331
|
pid: finalSendRequest.pid,
|
|
334
332
|
tid: finalSendRequest.tid,
|
|
335
333
|
};
|
|
336
|
-
const requests = Platform.MapUtilities.getWithDefault(requestsByOrigin, host, () => {
|
|
334
|
+
const requests = Platform.MapUtilities.getWithDefault(requestsByOrigin, parsedUrl.host, () => {
|
|
337
335
|
return {
|
|
338
336
|
renderBlocking: [],
|
|
339
337
|
nonRenderBlocking: [],
|