@paulirish/trace_engine 0.0.50 → 0.0.51
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/.tmp/tsbuildinfo/tsconfig.tsbuildinfo +1 -1
- package/core/platform/Constructor.d.ts +2 -2
- package/core/platform/Constructor.js.map +1 -1
- package/core/platform/StringUtilities.d.ts +2 -5
- package/core/platform/StringUtilities.js +0 -3
- package/core/platform/StringUtilities.js.map +1 -1
- package/core/platform/TypescriptUtilities.d.ts +1 -1
- package/core/platform/TypescriptUtilities.js +1 -1
- package/core/platform/TypescriptUtilities.js.map +1 -1
- package/core/platform/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/core/platform/platform-tsconfig.json +2 -3
- package/core/platform/platform.d.ts +1 -2
- package/core/platform/platform.js +1 -2
- package/core/platform/platform.js.map +1 -1
- package/generated/protocol.d.ts +156 -31
- package/locales/af.json +63 -3
- package/locales/am.json +63 -3
- package/locales/ar.json +63 -3
- package/locales/as.json +63 -3
- package/locales/az.json +63 -3
- package/locales/be.json +64 -4
- package/locales/bg.json +62 -2
- package/locales/bn.json +63 -3
- package/locales/bs.json +63 -3
- package/locales/ca.json +62 -2
- package/locales/cs.json +62 -2
- package/locales/cy.json +63 -3
- package/locales/da.json +63 -3
- package/locales/de.json +63 -3
- package/locales/el.json +62 -2
- package/locales/en-GB.json +63 -3
- package/locales/en-US.json +55 -22
- package/locales/en-XL.json +55 -22
- package/locales/es-419.json +63 -3
- package/locales/es.json +64 -4
- package/locales/et.json +64 -4
- package/locales/eu.json +79 -19
- package/locales/fa.json +62 -2
- package/locales/fi.json +63 -3
- package/locales/fil.json +63 -3
- package/locales/fr-CA.json +63 -3
- package/locales/fr.json +63 -3
- package/locales/gl.json +62 -2
- package/locales/gu.json +63 -3
- package/locales/he.json +63 -3
- package/locales/hi.json +62 -2
- package/locales/hr.json +63 -3
- package/locales/hu.json +62 -2
- package/locales/hy.json +63 -3
- package/locales/id.json +62 -2
- package/locales/is.json +64 -4
- package/locales/it.json +64 -4
- package/locales/ja.json +63 -3
- package/locales/ka.json +63 -3
- package/locales/kk.json +62 -2
- package/locales/km.json +62 -2
- package/locales/kn.json +63 -3
- package/locales/ko.json +63 -3
- package/locales/ky.json +63 -3
- package/locales/lo.json +63 -3
- package/locales/lt.json +62 -2
- package/locales/lv.json +62 -2
- package/locales/mk.json +62 -2
- package/locales/ml.json +63 -3
- package/locales/mn.json +63 -3
- package/locales/mr.json +64 -4
- package/locales/ms.json +63 -3
- package/locales/my.json +63 -3
- package/locales/ne.json +64 -4
- package/locales/nl.json +63 -3
- package/locales/no.json +62 -2
- package/locales/or.json +63 -3
- package/locales/pa.json +62 -2
- package/locales/pl.json +62 -2
- package/locales/pt-PT.json +62 -2
- package/locales/pt.json +63 -3
- package/locales/ro.json +63 -3
- package/locales/ru.json +63 -3
- package/locales/si.json +63 -3
- package/locales/sk.json +63 -3
- package/locales/sl.json +62 -2
- package/locales/sq.json +63 -3
- package/locales/sr-Latn.json +62 -2
- package/locales/sr.json +62 -2
- package/locales/sv.json +62 -2
- package/locales/sw.json +63 -3
- package/locales/ta.json +66 -6
- package/locales/te.json +63 -3
- package/locales/th.json +63 -3
- package/locales/tr.json +63 -3
- package/locales/uk.json +63 -3
- package/locales/ur.json +64 -4
- package/locales/uz.json +62 -2
- package/locales/vi.json +62 -2
- package/locales/zh-HK.json +63 -3
- package/locales/zh-TW.json +63 -3
- package/locales/zh.json +62 -2
- package/locales/zu.json +63 -3
- package/models/cpu_profile/CPUProfileDataModel.d.ts +8 -0
- package/models/cpu_profile/CPUProfileDataModel.js.map +1 -1
- package/models/cpu_profile/cpu_profile-tsconfig.json +2 -2
- package/models/cpu_profile/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/Processor.d.ts +1 -1
- package/models/trace/Processor.js +94 -74
- package/models/trace/Processor.js.map +1 -1
- package/models/trace/TracingManager.js.map +1 -1
- package/models/trace/bundle-tsconfig.json +1 -1
- package/models/trace/devtools_entrypoint-bundle-typescript-tsconfig.json +20 -2
- package/models/trace/extras/ScriptDuplication.d.ts +11 -15
- package/models/trace/extras/ScriptDuplication.js +59 -77
- package/models/trace/extras/ScriptDuplication.js.map +1 -1
- package/models/trace/extras/ThirdParties.d.ts +6 -13
- package/models/trace/extras/ThirdParties.js +69 -133
- package/models/trace/extras/ThirdParties.js.map +1 -1
- package/models/trace/extras/TraceTree.d.ts +15 -3
- package/models/trace/extras/TraceTree.js +36 -8
- package/models/trace/extras/TraceTree.js.map +1 -1
- package/models/trace/extras/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/extras/extras-tsconfig.json +2 -2
- package/models/trace/extras/extras.d.ts +880 -787
- package/models/trace/extras/extras.js +880 -787
- package/models/trace/handlers/AsyncJSCallsHandler.js +36 -4
- package/models/trace/handlers/AsyncJSCallsHandler.js.map +1 -1
- package/models/trace/handlers/InvalidationsHandler.js +1 -0
- package/models/trace/handlers/InvalidationsHandler.js.map +1 -1
- package/models/trace/handlers/ModelHandlers.d.ts +0 -1
- package/models/trace/handlers/ModelHandlers.js +0 -1
- package/models/trace/handlers/ModelHandlers.js.map +1 -1
- package/models/trace/handlers/NetworkRequestsHandler.js +1 -1
- package/models/trace/handlers/NetworkRequestsHandler.js.map +1 -1
- package/models/trace/handlers/RendererHandler.d.ts +1 -1
- package/models/trace/handlers/RendererHandler.js +2 -2
- package/models/trace/handlers/RendererHandler.js.map +1 -1
- package/models/trace/handlers/ScreenshotsHandler.js +3 -1
- package/models/trace/handlers/ScreenshotsHandler.js.map +1 -1
- package/models/trace/handlers/ScriptsHandler.d.ts +12 -0
- package/models/trace/handlers/ScriptsHandler.js +93 -1
- package/models/trace/handlers/ScriptsHandler.js.map +1 -1
- package/models/trace/handlers/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/handlers/handlers-tsconfig.json +2 -3
- package/models/trace/helpers/Network.d.ts +5 -0
- package/models/trace/helpers/Network.js +17 -0
- package/models/trace/helpers/Network.js.map +1 -1
- package/models/trace/helpers/SamplesIntegrator.js +19 -23
- package/models/trace/helpers/SamplesIntegrator.js.map +1 -1
- package/models/trace/helpers/SyntheticEvents.d.ts +0 -1
- package/models/trace/helpers/SyntheticEvents.js +0 -4
- package/models/trace/helpers/SyntheticEvents.js.map +1 -1
- package/models/trace/helpers/Trace.d.ts +2 -1
- package/models/trace/helpers/Trace.js +101 -1
- package/models/trace/helpers/Trace.js.map +1 -1
- package/models/trace/helpers/TreeHelpers.d.ts +2 -5
- package/models/trace/helpers/TreeHelpers.js +0 -4
- package/models/trace/helpers/TreeHelpers.js.map +1 -1
- package/models/trace/helpers/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/helpers/helpers-tsconfig.json +2 -2
- package/models/trace/insights/{UseCache.d.ts → Cache.d.ts} +2 -2
- package/models/trace/insights/{UseCache.js → Cache.js} +11 -5
- package/models/trace/insights/Cache.js.map +1 -0
- package/models/trace/insights/Common.d.ts +21 -2
- package/models/trace/insights/Common.js +86 -2
- package/models/trace/insights/Common.js.map +1 -1
- package/models/trace/insights/DocumentLatency.js +2 -8
- package/models/trace/insights/DocumentLatency.js.map +1 -1
- package/models/trace/insights/DuplicatedJavaScript.d.ts +7 -4
- package/models/trace/insights/DuplicatedJavaScript.js +25 -5
- package/models/trace/insights/DuplicatedJavaScript.js.map +1 -1
- package/models/trace/insights/ForcedReflow.d.ts +5 -1
- package/models/trace/insights/ForcedReflow.js +6 -2
- package/models/trace/insights/ForcedReflow.js.map +1 -1
- package/models/trace/insights/InteractionToNextPaint.d.ts +1 -0
- package/models/trace/insights/InteractionToNextPaint.js +3 -0
- package/models/trace/insights/InteractionToNextPaint.js.map +1 -1
- package/models/trace/insights/LegacyJavaScript.d.ts +32 -0
- package/models/trace/insights/LegacyJavaScript.js +77 -0
- package/models/trace/insights/LegacyJavaScript.js.map +1 -0
- package/models/trace/insights/Models.d.ts +3 -1
- package/models/trace/insights/Models.js +3 -1
- package/models/trace/insights/Models.js.map +1 -1
- package/models/trace/insights/ModernHTTP.d.ts +51 -0
- package/models/trace/insights/ModernHTTP.js +187 -0
- package/models/trace/insights/ModernHTTP.js.map +1 -0
- package/models/trace/insights/NetworkDependencyTree.js +1 -1
- package/models/trace/insights/NetworkDependencyTree.js.map +1 -1
- package/models/trace/insights/ThirdParties.d.ts +1 -5
- package/models/trace/insights/ThirdParties.js +8 -21
- package/models/trace/insights/ThirdParties.js.map +1 -1
- package/models/trace/insights/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/insights/insights-tsconfig.json +8 -3
- package/models/trace/insights/types.d.ts +1 -0
- package/models/trace/insights/types.js.map +1 -1
- package/models/trace/lantern/core/core-tsconfig.json +2 -2
- package/models/trace/lantern/core/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/graph/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/graph/graph-tsconfig.json +2 -2
- package/models/trace/lantern/lantern-tsconfig.json +2 -2
- package/models/trace/lantern/metrics/Metric.d.ts +4 -4
- package/models/trace/lantern/metrics/Metric.js +4 -6
- package/models/trace/lantern/metrics/Metric.js.map +1 -1
- package/models/trace/lantern/metrics/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/metrics/metrics-tsconfig.json +2 -2
- package/models/trace/lantern/simulation/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/simulation/simulation-tsconfig.json +2 -2
- package/models/trace/lantern/types/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/lantern/types/types-tsconfig.json +2 -2
- package/models/trace/trace-tsconfig.json +2 -2
- package/models/trace/types/Configuration.d.ts +2 -0
- package/models/trace/types/Configuration.js.map +1 -1
- package/models/trace/types/TraceEvents.d.ts +28 -50
- package/models/trace/types/TraceEvents.js +8 -23
- package/models/trace/types/TraceEvents.js.map +1 -1
- package/models/trace/types/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
- package/models/trace/types/types-tsconfig.json +2 -2
- package/package.json +3 -2
- package/test/test-trace-engine.mjs +19 -17
- package/third_party/legacy-javascript/legacy-javascript.d.ts +1 -0
- package/third_party/legacy-javascript/legacy-javascript.js +1 -0
- package/core/platform/ServerTiming.d.ts +0 -31
- package/core/platform/ServerTiming.js +0 -212
- package/core/platform/ServerTiming.js.map +0 -1
- package/models/trace/handlers/ServerTimingsHandler.d.ts +0 -9
- package/models/trace/handlers/ServerTimingsHandler.js +0 -106
- package/models/trace/handlers/ServerTimingsHandler.js.map +0 -1
- package/models/trace/insights/UseCache.js.map +0 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type * as Platform from '../../../core/platform/platform.js';
|
|
1
2
|
import * as Types from '../types/types.js';
|
|
2
3
|
export declare const makeTraceEntryNodeId: () => TraceEntryNodeId;
|
|
3
4
|
export declare const makeEmptyTraceEntryTree: () => TraceEntryTree;
|
|
@@ -15,10 +16,7 @@ export interface TraceEntryNode {
|
|
|
15
16
|
parent: TraceEntryNode | null;
|
|
16
17
|
children: TraceEntryNode[];
|
|
17
18
|
}
|
|
18
|
-
|
|
19
|
-
#private;
|
|
20
|
-
}
|
|
21
|
-
export type TraceEntryNodeId = number & TraceEntryNodeIdTag;
|
|
19
|
+
export type TraceEntryNodeId = Platform.Brand.Brand<number, 'traceEntryNodeIdTag'>;
|
|
22
20
|
/**
|
|
23
21
|
* Builds a hierarchy of the entries (trace events and profile calls) in
|
|
24
22
|
* a particular thread of a particular process, assuming that they're
|
|
@@ -109,4 +107,3 @@ export declare function walkEntireTree(entryToNode: Map<Types.Events.Event, Trac
|
|
|
109
107
|
* built, for example if none of the events overlap with each other.
|
|
110
108
|
*/
|
|
111
109
|
export declare function canBuildTreesFromEvents(events: readonly Types.Events.Event[]): boolean;
|
|
112
|
-
export {};
|
|
@@ -16,10 +16,6 @@ export const makeEmptyTraceEntryNode = (entry, id) => ({
|
|
|
16
16
|
children: [],
|
|
17
17
|
depth: 0,
|
|
18
18
|
});
|
|
19
|
-
class TraceEntryNodeIdTag {
|
|
20
|
-
/* eslint-disable-next-line no-unused-private-class-members */
|
|
21
|
-
#tag;
|
|
22
|
-
}
|
|
23
19
|
/**
|
|
24
20
|
* Builds a hierarchy of the entries (trace events and profile calls) in
|
|
25
21
|
* a particular thread of a particular process, assuming that they're
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TreeHelpers.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/helpers/TreeHelpers.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,eAAe,EAAC,MAAM,aAAa,CAAC;AAE5C,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAqB,EAAE,CAAC,CAAC,EAAE,WAAW,CAAqB,CAAC;AAEhG,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAmB,EAAE,CAAC,CAAC;IAC5D,KAAK,EAAE,IAAI,GAAG,EAAE;IAChB,QAAQ,EAAE,CAAC;CACZ,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,KAAyB,EAAE,EAAoB,EAAkB,EAAE,CAAC,CAAC;IAC3G,KAAK;IACL,EAAE;IACF,MAAM,EAAE,IAAI;IACZ,QAAQ,EAAE,EAAE;IACZ,KAAK,EAAE,CAAC;CACT,CAAC,CAAC;AAiBH,MAAM,mBAAmB;IACvB,8DAA8D;IACrD,IAAI,CAAqB;CACnC;AAGD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,MAAM,CAAC,OAA6B,EAAE,OAErD;IACC,wEAAwE;IACxE,yEAAyE;IACzE,wCAAwC;IACxC,MAAM,WAAW,GAA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AK,CAAC,EAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,KAAK,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAC5C,IAAI,MAAM,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAClB,SAAS;QACX,CAAC;QACD,IAAI,aAAa,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAClD,iEAAiE;QACjE,wDAAwD;QACxD,OAAO,KAAK,CAAC,MAAM,IAAI,SAAS,IAAI,aAAa,EAAE,CAAC;YAClD,KAAK,CAAC,GAAG,EAAE,CAAC;YACZ,MAAM,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAEtB,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBACzB,MAAM;YACR,CAAC;YACD,aAAa,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAChD,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,OAAO,GAAG,aAAa,EAAE,CAAC;YAC5C,0DAA0D;YAC1D,0DAA0D;YAC1D,UAAU;YACV,OAAO,KAAK,CAAC;QACf,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,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\nimport {eventIsInBounds} from './Timing.js';\n\nlet nodeIdCount = 0;\nexport const makeTraceEntryNodeId = (): TraceEntryNodeId => (++nodeIdCount) as TraceEntryNodeId;\n\nexport const makeEmptyTraceEntryTree = (): TraceEntryTree => ({\n roots: new Set(),\n maxDepth: 0,\n});\n\nexport const makeEmptyTraceEntryNode = (entry: Types.Events.Event, id: TraceEntryNodeId): TraceEntryNode => ({\n entry,\n id,\n parent: null,\n children: [],\n depth: 0,\n});\n\nexport interface TraceEntryTree {\n roots: Set<TraceEntryNode>;\n maxDepth: number;\n}\n\n/** Node in the graph that defines all parent/child relationships. */\nexport interface TraceEntryNode {\n entry: Types.Events.Event;\n depth: number;\n selfTime?: Types.Timing.Micro;\n id: TraceEntryNodeId;\n parent: TraceEntryNode|null;\n children: TraceEntryNode[];\n}\n\nclass TraceEntryNodeIdTag {\n /* eslint-disable-next-line no-unused-private-class-members */\n readonly #tag: (symbol|undefined);\n}\nexport type TraceEntryNodeId = number&TraceEntryNodeIdTag;\n\n/**\n * Builds a hierarchy of the entries (trace events and profile calls) in\n * a particular thread of a particular process, assuming that they're\n * sorted, by iterating through all of the events in order.\n *\n * The approach is analogous to how a parser would be implemented. A\n * stack maintains local context. A scanner peeks and pops from the data\n * stream. Various \"tokens\" (events) are treated as \"whitespace\"\n * (ignored).\n *\n * The tree starts out empty and is populated as the hierarchy is built.\n * The nodes are also assumed to be created empty, with no known parent\n * or children.\n *\n * Complexity: O(n), where n = number of events\n */\nexport function treify(entries: Types.Events.Event[], options?: {\n filter: {has: (name: Types.Events.Name) => boolean},\n}): {tree: TraceEntryTree, entryToNode: Map<Types.Events.Event, TraceEntryNode>} {\n // As we construct the tree, store a map of each entry to its node. This\n // means if you are iterating over a list of RendererEntry events you can\n // easily look up that node in the tree.\n const entryToNode = new Map<Types.Events.Event, TraceEntryNode>();\n\n const stack = [];\n // Reset the node id counter for every new renderer.\n nodeIdCount = -1;\n const tree = makeEmptyTraceEntryTree();\n\n for (let i = 0; i < entries.length; i++) {\n const event = entries[i];\n // If the current event should not be part of the tree, then simply proceed\n // with the next event.\n if (options && !options.filter.has(event.name as Types.Events.Name)) {\n continue;\n }\n\n const duration = event.dur || 0;\n const nodeId = makeTraceEntryNodeId();\n const node = makeEmptyTraceEntryNode(event, nodeId);\n\n // If the parent stack is empty, then the current event is a root. Create a\n // node for it, mark it as a root, then proceed with the next event.\n if (stack.length === 0) {\n tree.roots.add(node);\n node.selfTime = Types.Timing.Micro(duration);\n stack.push(node);\n tree.maxDepth = Math.max(tree.maxDepth, stack.length);\n entryToNode.set(event, node);\n continue;\n }\n\n const parentNode = stack.at(-1);\n if (parentNode === undefined) {\n throw new Error('Impossible: no parent node found in the stack');\n }\n\n const parentEvent = parentNode.entry;\n\n const begin = event.ts;\n const parentBegin = parentEvent.ts;\n const parentDuration = parentEvent.dur || 0;\n const end = begin + duration;\n const parentEnd = parentBegin + parentDuration;\n // Check the relationship between the parent event at the top of the stack,\n // and the current event being processed. There are only 4 distinct\n // possibilities, only 2 of them actually valid, given the assumed sorting:\n // 1. Current event starts before the parent event, ends whenever. (invalid)\n // 2. Current event starts after the parent event, ends whenever. (valid)\n // 3. Current event starts during the parent event, ends after. (invalid)\n // 4. Current event starts and ends during the parent event. (valid)\n\n // 1. If the current event starts before the parent event, then the data is\n // not sorted properly, messed up some way, or this logic is incomplete.\n const startsBeforeParent = begin < parentBegin;\n if (startsBeforeParent) {\n throw new Error('Impossible: current event starts before the parent event');\n }\n\n // 2. If the current event starts after the parent event, then it's a new\n // parent. Pop, then handle current event again.\n const startsAfterParent = begin >= parentEnd;\n if (startsAfterParent) {\n stack.pop();\n i--;\n // The last created node has been discarded, so discard this id.\n nodeIdCount--;\n continue;\n }\n // 3. If the current event starts during the parent event, but ends\n // after it, then the data is messed up some way, for example a\n // profile call was sampled too late after its start, ignore the\n // problematic event.\n const endsAfterParent = end > parentEnd;\n if (endsAfterParent) {\n continue;\n }\n\n // 4. The only remaining case is the common case, where the current event is\n // contained within the parent event. Create a node for the current\n // event, establish the parent/child relationship, then proceed with the\n // next event.\n node.depth = stack.length;\n node.parent = parentNode;\n parentNode.children.push(node);\n node.selfTime = Types.Timing.Micro(duration);\n if (parentNode.selfTime !== undefined) {\n parentNode.selfTime = Types.Timing.Micro(parentNode.selfTime - (event.dur || 0));\n }\n stack.push(node);\n tree.maxDepth = Math.max(tree.maxDepth, stack.length);\n entryToNode.set(event, node);\n }\n return {tree, entryToNode};\n}\n\n/**\n * Iterates events in a tree hierarchically, from top to bottom,\n * calling back on every event's start and end in the order\n * as it traverses down and then up the tree.\n *\n * For example, given this tree, the following callbacks\n * are expected to be made in the following order\n * |---------------A---------------|\n * |------B------||-------D------|\n * |---C---|\n *\n * 1. Start A\n * 3. Start B\n * 4. Start C\n * 5. End C\n * 6. End B\n * 7. Start D\n * 8. End D\n * 9. End A\n *\n */\nexport function walkTreeFromEntry(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n rootEntry: Types.Events.Event,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n ): void {\n const startNode = entryToNode.get(rootEntry);\n if (!startNode) {\n return;\n }\n walkTreeByNode(entryToNode, startNode, onEntryStart, onEntryEnd);\n}\n\n/**\n * Given a Helpers.TreeHelpers.RendererTree, this will iterates events in hierarchically, visiting\n * each root node and working from top to bottom, calling back on every event's\n * start and end in the order as it traverses down and then up the tree.\n *\n * For example, given this tree, the following callbacks\n * are expected to be made in the following order\n * |------------- Task A -------------||-- Task E --|\n * |-- Task B --||-- Task D --|\n * |- Task C -|\n *\n * 1. Start A\n * 3. Start B\n * 4. Start C\n * 5. End C\n * 6. End B\n * 7. Start D\n * 8. End D\n * 9. End A\n * 10. Start E\n * 11. End E\n *\n */\n\nexport function walkEntireTree(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n tree: TraceEntryTree,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n traceWindowToInclude?: Types.Timing.TraceWindowMicro,\n minDuration?: Types.Timing.Micro,\n ): void {\n for (const rootNode of tree.roots) {\n walkTreeByNode(entryToNode, rootNode, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);\n }\n}\n\nfunction walkTreeByNode(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n rootNode: TraceEntryNode,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n traceWindowToInclude?: Types.Timing.TraceWindowMicro,\n minDuration?: Types.Timing.Micro,\n ): void {\n if (traceWindowToInclude && !treeNodeIsInWindow(rootNode, traceWindowToInclude)) {\n // If this node is not within the provided window, we can skip it. We also\n // can skip all its children too, as we know they won't be in the window if\n // their parent is not.\n return;\n }\n\n if (typeof minDuration !== 'undefined') {\n const duration = Types.Timing.Micro(\n rootNode.entry.ts + Types.Timing.Micro(rootNode.entry.dur ?? 0),\n );\n if (duration < minDuration) {\n return;\n }\n }\n\n onEntryStart(rootNode.entry);\n for (const child of rootNode.children) {\n walkTreeByNode(entryToNode, child, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);\n }\n onEntryEnd(rootNode.entry);\n}\n\n/**\n * Returns true if the provided node is partially or fully within the trace\n * window. The entire node does not have to fit inside the window, but it does\n * have to partially intersect it.\n */\nfunction treeNodeIsInWindow(node: TraceEntryNode, traceWindow: Types.Timing.TraceWindowMicro): boolean {\n return eventIsInBounds(node.entry, traceWindow);\n}\n\n/**\n * Determines if the given events, which are assumed to be ordered can\n * be organized into tree structures.\n * This condition is met if there is *not* a pair of async events\n * e1 and e2 where:\n *\n * e1.startTime < e2.startTime && e1.endTime > e2.startTime && e1.endTime < e2.endTime.\n * or, graphically:\n * |------- e1 ------|\n * |------- e2 --------|\n *\n * Because a parent-child relationship cannot be made from the example\n * above, a tree cannot be made from the set of events.\n *\n * Sync events from the same thread are tree-able by definition.\n *\n * Note that this will also return true if multiple trees can be\n * built, for example if none of the events overlap with each other.\n */\nexport function canBuildTreesFromEvents(events: readonly Types.Events.Event[]): boolean {\n const stack: Types.Events.Event[] = [];\n for (const event of events) {\n const startTime = event.ts;\n const endTime = event.ts + (event.dur ?? 0);\n let parent = stack.at(-1);\n if (parent === undefined) {\n stack.push(event);\n continue;\n }\n let parentEndTime = parent.ts + (parent.dur ?? 0);\n // Discard events that are not parents for this event. The parent\n // is one whose end time is after this event start time.\n while (stack.length && startTime >= parentEndTime) {\n stack.pop();\n parent = stack.at(-1);\n\n if (parent === undefined) {\n break;\n }\n parentEndTime = parent.ts + (parent.dur ?? 0);\n }\n if (stack.length && endTime > parentEndTime) {\n // If such an event exists but its end time is before this\n // event's end time, then a tree cannot be made using this\n // events.\n return false;\n }\n stack.push(event);\n }\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"TreeHelpers.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/helpers/TreeHelpers.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAG7B,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,eAAe,EAAC,MAAM,aAAa,CAAC;AAE5C,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAqB,EAAE,CAAC,CAAC,EAAE,WAAW,CAAqB,CAAC;AAEhG,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAmB,EAAE,CAAC,CAAC;IAC5D,KAAK,EAAE,IAAI,GAAG,EAAE;IAChB,QAAQ,EAAE,CAAC;CACZ,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,KAAyB,EAAE,EAAoB,EAAkB,EAAE,CAAC,CAAC;IAC3G,KAAK;IACL,EAAE;IACF,MAAM,EAAE,IAAI;IACZ,QAAQ,EAAE,EAAE;IACZ,KAAK,EAAE,CAAC;CACT,CAAC,CAAC;AAmBH;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,MAAM,CAAC,OAA6B,EAAE,OAErD;IACC,wEAAwE;IACxE,yEAAyE;IACzE,wCAAwC;IACxC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsC,CAAC;IA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AAM,OAAO,GAAG,KAAK,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAC5C,IAAI,MAAM,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAClB,SAAS;QACX,CAAC;QACD,IAAI,aAAa,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAClD,iEAAiE;QACjE,wDAAwD;QACxD,OAAO,KAAK,CAAC,MAAM,IAAI,SAAS,IAAI,aAAa,EAAE,CAAC;YAClD,KAAK,CAAC,GAAG,EAAE,CAAC;YACZ,MAAM,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAEtB,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBACzB,MAAM;YACR,CAAC;YACD,aAAa,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAChD,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,OAAO,GAAG,aAAa,EAAE,CAAC;YAC5C,0DAA0D;YAC1D,0DAA0D;YAC1D,UAAU;YACV,OAAO,KAAK,CAAC;QACf,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,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 type * as Platform from '../../../core/platform/platform.js';\nimport * as Types from '../types/types.js';\n\nimport {eventIsInBounds} from './Timing.js';\n\nlet nodeIdCount = 0;\nexport const makeTraceEntryNodeId = (): TraceEntryNodeId => (++nodeIdCount) as TraceEntryNodeId;\n\nexport const makeEmptyTraceEntryTree = (): TraceEntryTree => ({\n roots: new Set(),\n maxDepth: 0,\n});\n\nexport const makeEmptyTraceEntryNode = (entry: Types.Events.Event, id: TraceEntryNodeId): TraceEntryNode => ({\n entry,\n id,\n parent: null,\n children: [],\n depth: 0,\n});\n\nexport interface TraceEntryTree {\n roots: Set<TraceEntryNode>;\n maxDepth: number;\n}\n\n/** Node in the graph that defines all parent/child relationships. */\nexport interface TraceEntryNode {\n entry: Types.Events.Event;\n depth: number;\n selfTime?: Types.Timing.Micro;\n id: TraceEntryNodeId;\n parent: TraceEntryNode|null;\n children: TraceEntryNode[];\n}\n\nexport type TraceEntryNodeId = Platform.Brand.Brand<number, 'traceEntryNodeIdTag'>;\n\n/**\n * Builds a hierarchy of the entries (trace events and profile calls) in\n * a particular thread of a particular process, assuming that they're\n * sorted, by iterating through all of the events in order.\n *\n * The approach is analogous to how a parser would be implemented. A\n * stack maintains local context. A scanner peeks and pops from the data\n * stream. Various \"tokens\" (events) are treated as \"whitespace\"\n * (ignored).\n *\n * The tree starts out empty and is populated as the hierarchy is built.\n * The nodes are also assumed to be created empty, with no known parent\n * or children.\n *\n * Complexity: O(n), where n = number of events\n */\nexport function treify(entries: Types.Events.Event[], options?: {\n filter: {has: (name: Types.Events.Name) => boolean},\n}): {tree: TraceEntryTree, entryToNode: Map<Types.Events.Event, TraceEntryNode>} {\n // As we construct the tree, store a map of each entry to its node. This\n // means if you are iterating over a list of RendererEntry events you can\n // easily look up that node in the tree.\n const entryToNode = new Map<Types.Events.Event, TraceEntryNode>();\n\n const stack = [];\n // Reset the node id counter for every new renderer.\n nodeIdCount = -1;\n const tree = makeEmptyTraceEntryTree();\n\n for (let i = 0; i < entries.length; i++) {\n const event = entries[i];\n // If the current event should not be part of the tree, then simply proceed\n // with the next event.\n if (options && !options.filter.has(event.name as Types.Events.Name)) {\n continue;\n }\n\n const duration = event.dur || 0;\n const nodeId = makeTraceEntryNodeId();\n const node = makeEmptyTraceEntryNode(event, nodeId);\n\n // If the parent stack is empty, then the current event is a root. Create a\n // node for it, mark it as a root, then proceed with the next event.\n if (stack.length === 0) {\n tree.roots.add(node);\n node.selfTime = Types.Timing.Micro(duration);\n stack.push(node);\n tree.maxDepth = Math.max(tree.maxDepth, stack.length);\n entryToNode.set(event, node);\n continue;\n }\n\n const parentNode = stack.at(-1);\n if (parentNode === undefined) {\n throw new Error('Impossible: no parent node found in the stack');\n }\n\n const parentEvent = parentNode.entry;\n\n const begin = event.ts;\n const parentBegin = parentEvent.ts;\n const parentDuration = parentEvent.dur || 0;\n const end = begin + duration;\n const parentEnd = parentBegin + parentDuration;\n // Check the relationship between the parent event at the top of the stack,\n // and the current event being processed. There are only 4 distinct\n // possibilities, only 2 of them actually valid, given the assumed sorting:\n // 1. Current event starts before the parent event, ends whenever. (invalid)\n // 2. Current event starts after the parent event, ends whenever. (valid)\n // 3. Current event starts during the parent event, ends after. (invalid)\n // 4. Current event starts and ends during the parent event. (valid)\n\n // 1. If the current event starts before the parent event, then the data is\n // not sorted properly, messed up some way, or this logic is incomplete.\n const startsBeforeParent = begin < parentBegin;\n if (startsBeforeParent) {\n throw new Error('Impossible: current event starts before the parent event');\n }\n\n // 2. If the current event starts after the parent event, then it's a new\n // parent. Pop, then handle current event again.\n const startsAfterParent = begin >= parentEnd;\n if (startsAfterParent) {\n stack.pop();\n i--;\n // The last created node has been discarded, so discard this id.\n nodeIdCount--;\n continue;\n }\n // 3. If the current event starts during the parent event, but ends\n // after it, then the data is messed up some way, for example a\n // profile call was sampled too late after its start, ignore the\n // problematic event.\n const endsAfterParent = end > parentEnd;\n if (endsAfterParent) {\n continue;\n }\n\n // 4. The only remaining case is the common case, where the current event is\n // contained within the parent event. Create a node for the current\n // event, establish the parent/child relationship, then proceed with the\n // next event.\n node.depth = stack.length;\n node.parent = parentNode;\n parentNode.children.push(node);\n node.selfTime = Types.Timing.Micro(duration);\n if (parentNode.selfTime !== undefined) {\n parentNode.selfTime = Types.Timing.Micro(parentNode.selfTime - (event.dur || 0));\n }\n stack.push(node);\n tree.maxDepth = Math.max(tree.maxDepth, stack.length);\n entryToNode.set(event, node);\n }\n return {tree, entryToNode};\n}\n\n/**\n * Iterates events in a tree hierarchically, from top to bottom,\n * calling back on every event's start and end in the order\n * as it traverses down and then up the tree.\n *\n * For example, given this tree, the following callbacks\n * are expected to be made in the following order\n * |---------------A---------------|\n * |------B------||-------D------|\n * |---C---|\n *\n * 1. Start A\n * 3. Start B\n * 4. Start C\n * 5. End C\n * 6. End B\n * 7. Start D\n * 8. End D\n * 9. End A\n *\n */\nexport function walkTreeFromEntry(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n rootEntry: Types.Events.Event,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n ): void {\n const startNode = entryToNode.get(rootEntry);\n if (!startNode) {\n return;\n }\n walkTreeByNode(entryToNode, startNode, onEntryStart, onEntryEnd);\n}\n\n/**\n * Given a Helpers.TreeHelpers.RendererTree, this will iterates events in hierarchically, visiting\n * each root node and working from top to bottom, calling back on every event's\n * start and end in the order as it traverses down and then up the tree.\n *\n * For example, given this tree, the following callbacks\n * are expected to be made in the following order\n * |------------- Task A -------------||-- Task E --|\n * |-- Task B --||-- Task D --|\n * |- Task C -|\n *\n * 1. Start A\n * 3. Start B\n * 4. Start C\n * 5. End C\n * 6. End B\n * 7. Start D\n * 8. End D\n * 9. End A\n * 10. Start E\n * 11. End E\n *\n */\n\nexport function walkEntireTree(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n tree: TraceEntryTree,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n traceWindowToInclude?: Types.Timing.TraceWindowMicro,\n minDuration?: Types.Timing.Micro,\n ): void {\n for (const rootNode of tree.roots) {\n walkTreeByNode(entryToNode, rootNode, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);\n }\n}\n\nfunction walkTreeByNode(\n entryToNode: Map<Types.Events.Event, TraceEntryNode>,\n rootNode: TraceEntryNode,\n onEntryStart: (entry: Types.Events.Event) => void,\n onEntryEnd: (entry: Types.Events.Event) => void,\n traceWindowToInclude?: Types.Timing.TraceWindowMicro,\n minDuration?: Types.Timing.Micro,\n ): void {\n if (traceWindowToInclude && !treeNodeIsInWindow(rootNode, traceWindowToInclude)) {\n // If this node is not within the provided window, we can skip it. We also\n // can skip all its children too, as we know they won't be in the window if\n // their parent is not.\n return;\n }\n\n if (typeof minDuration !== 'undefined') {\n const duration = Types.Timing.Micro(\n rootNode.entry.ts + Types.Timing.Micro(rootNode.entry.dur ?? 0),\n );\n if (duration < minDuration) {\n return;\n }\n }\n\n onEntryStart(rootNode.entry);\n for (const child of rootNode.children) {\n walkTreeByNode(entryToNode, child, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);\n }\n onEntryEnd(rootNode.entry);\n}\n\n/**\n * Returns true if the provided node is partially or fully within the trace\n * window. The entire node does not have to fit inside the window, but it does\n * have to partially intersect it.\n */\nfunction treeNodeIsInWindow(node: TraceEntryNode, traceWindow: Types.Timing.TraceWindowMicro): boolean {\n return eventIsInBounds(node.entry, traceWindow);\n}\n\n/**\n * Determines if the given events, which are assumed to be ordered can\n * be organized into tree structures.\n * This condition is met if there is *not* a pair of async events\n * e1 and e2 where:\n *\n * e1.startTime < e2.startTime && e1.endTime > e2.startTime && e1.endTime < e2.endTime.\n * or, graphically:\n * |------- e1 ------|\n * |------- e2 --------|\n *\n * Because a parent-child relationship cannot be made from the example\n * above, a tree cannot be made from the set of events.\n *\n * Sync events from the same thread are tree-able by definition.\n *\n * Note that this will also return true if multiple trees can be\n * built, for example if none of the events overlap with each other.\n */\nexport function canBuildTreesFromEvents(events: readonly Types.Events.Event[]): boolean {\n const stack: Types.Events.Event[] = [];\n for (const event of events) {\n const startTime = event.ts;\n const endTime = event.ts + (event.dur ?? 0);\n let parent = stack.at(-1);\n if (parent === undefined) {\n stack.push(event);\n continue;\n }\n let parentEndTime = parent.ts + (parent.dur ?? 0);\n // Discard events that are not parents for this event. The parent\n // is one whose end time is after this event start time.\n while (stack.length && startTime >= parentEndTime) {\n stack.pop();\n parent = stack.at(-1);\n\n if (parent === undefined) {\n break;\n }\n parentEndTime = parent.ts + (parent.dur ?? 0);\n }\n if (stack.length && endTime > parentEndTime) {\n // If such an event exists but its end time is before this\n // event's end time, then a tree cannot be made using this\n // events.\n return false;\n }\n stack.push(event);\n }\n return true;\n}\n"]}
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"noImplicitOverride": true,
|
|
19
19
|
"noImplicitReturns": true,
|
|
20
20
|
"noUnusedLocals": false,
|
|
21
|
+
"noUnusedParameters": true,
|
|
21
22
|
"outDir": ".",
|
|
22
23
|
"rootDir": "../../../../../../../front_end/models/trace/helpers",
|
|
23
24
|
"skipLibCheck": true,
|
|
@@ -32,8 +33,7 @@
|
|
|
32
33
|
"../../../../../../../front_end/models/trace/helpers/helpers.ts",
|
|
33
34
|
"../../../../../../../front_end/legacy/legacy-defs.d.ts",
|
|
34
35
|
"../../../../../../../front_end/global_typings/global_defs.d.ts",
|
|
35
|
-
"../../../../../../../node_modules/@types/filesystem/index.d.ts"
|
|
36
|
-
"../../../../../../../node_modules/@types/wicg-task-scheduling/index.d.ts"
|
|
36
|
+
"../../../../../../../node_modules/@types/filesystem/index.d.ts"
|
|
37
37
|
],
|
|
38
38
|
"references": [
|
|
39
39
|
{
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"noImplicitOverride": true,
|
|
19
19
|
"noImplicitReturns": true,
|
|
20
20
|
"noUnusedLocals": false,
|
|
21
|
+
"noUnusedParameters": true,
|
|
21
22
|
"outDir": ".",
|
|
22
23
|
"rootDir": "../../../../../../../front_end/models/trace/helpers",
|
|
23
24
|
"skipLibCheck": true,
|
|
@@ -38,8 +39,7 @@
|
|
|
38
39
|
"../../../../../../../front_end/models/trace/helpers/TreeHelpers.ts",
|
|
39
40
|
"../../../../../../../front_end/legacy/legacy-defs.d.ts",
|
|
40
41
|
"../../../../../../../front_end/global_typings/global_defs.d.ts",
|
|
41
|
-
"../../../../../../../node_modules/@types/filesystem/index.d.ts"
|
|
42
|
-
"../../../../../../../node_modules/@types/wicg-task-scheduling/index.d.ts"
|
|
42
|
+
"../../../../../../../node_modules/@types/filesystem/index.d.ts"
|
|
43
43
|
],
|
|
44
44
|
"references": [
|
|
45
45
|
{
|
|
@@ -30,7 +30,7 @@ export declare const UIStrings: {
|
|
|
30
30
|
readonly others: "{PH1} others";
|
|
31
31
|
};
|
|
32
32
|
export declare const i18nString: (id: string, values?: Record<string, string> | undefined) => Record<string, string>;
|
|
33
|
-
export type
|
|
33
|
+
export type CacheInsightModel = InsightModel<typeof UIStrings, {
|
|
34
34
|
requests: Array<{
|
|
35
35
|
request: Types.Events.SyntheticNetworkRequest;
|
|
36
36
|
ttl: number;
|
|
@@ -66,4 +66,4 @@ export interface CacheableRequest {
|
|
|
66
66
|
ttl: number;
|
|
67
67
|
wastedBytes: number;
|
|
68
68
|
}
|
|
69
|
-
export declare function generateInsight(parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext):
|
|
69
|
+
export declare function generateInsight(parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): CacheInsightModel;
|
|
@@ -33,13 +33,13 @@ export const UIStrings = {
|
|
|
33
33
|
*/
|
|
34
34
|
others: '{PH1} others',
|
|
35
35
|
};
|
|
36
|
-
// const str_ = i18n.i18n.registerUIStrings('models/trace/insights/
|
|
36
|
+
// const str_ = i18n.i18n.registerUIStrings('models/trace/insights/Cache.ts', UIStrings);
|
|
37
37
|
export const i18nString = (i18nId, values) => ({i18nId, values}); // i18n.i18n.getLocalizedString.bind(undefined, str_);
|
|
38
38
|
// Threshold for cache hits.
|
|
39
39
|
const IGNORE_THRESHOLD_IN_PERCENT = 0.925;
|
|
40
40
|
function finalize(partialModel) {
|
|
41
41
|
return {
|
|
42
|
-
insightKey: '
|
|
42
|
+
insightKey: 'Cache',
|
|
43
43
|
strings: UIStrings,
|
|
44
44
|
title: i18nString(UIStrings.title),
|
|
45
45
|
description: i18nString(UIStrings.description),
|
|
@@ -143,11 +143,12 @@ export function cachingDisabled(headers, parsedCacheControl) {
|
|
|
143
143
|
return false;
|
|
144
144
|
}
|
|
145
145
|
export function generateInsight(parsedTrace, context) {
|
|
146
|
+
const isWithinContext = (event) => Helpers.Timing.eventIsInBounds(event, context.bounds);
|
|
147
|
+
const contextRequests = parsedTrace.NetworkRequests.byTime.filter(isWithinContext);
|
|
146
148
|
const results = [];
|
|
147
|
-
const allRequests = parsedTrace.NetworkRequests.byTime;
|
|
148
149
|
let totalWastedBytes = 0;
|
|
149
150
|
const wastedBytesByRequestId = new Map();
|
|
150
|
-
for (const req of
|
|
151
|
+
for (const req of contextRequests) {
|
|
151
152
|
if (!isCacheable(req)) {
|
|
152
153
|
continue;
|
|
153
154
|
}
|
|
@@ -164,6 +165,11 @@ export function generateInsight(parsedTrace, context) {
|
|
|
164
165
|
continue;
|
|
165
166
|
}
|
|
166
167
|
ttl = ttl || 0;
|
|
168
|
+
// Ignore >= 30d.
|
|
169
|
+
const ttlDays = ttl / 86400;
|
|
170
|
+
if (ttlDays >= 30) {
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
167
173
|
// If cache lifetime is high enough, let's skip.
|
|
168
174
|
const cacheHitProbability = getCacheHitProbability(ttl);
|
|
169
175
|
if (cacheHitProbability > IGNORE_THRESHOLD_IN_PERCENT) {
|
|
@@ -186,4 +192,4 @@ export function generateInsight(parsedTrace, context) {
|
|
|
186
192
|
totalWastedBytes,
|
|
187
193
|
});
|
|
188
194
|
}
|
|
189
|
-
//# sourceMappingURL=
|
|
195
|
+
//# sourceMappingURL=Cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Cache.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/Cache.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OA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AAG,YAAY,CAAC;QAE7D,sBAAsB,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QACjE,gBAAgB,IAAI,WAAW,CAAC;QAEhC,OAAO,CAAC,IAAI,CAAC,EAAC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,WAAW,EAAC,CAAC,CAAC;IACjD,CAAC;IAED,yBAAyB;IACzB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACpB,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC;IACxG,CAAC,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1C,QAAQ,EAAE,OAAO;QACjB,aAAa,EAAE,2BAA2B,CAAC,sBAAsB,EAAE,OAAO,CAAC;QAC3E,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2025 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 i18n from '../../../core/i18n/i18n.js';\nimport * as Protocol from '../../../generated/protocol.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Types from '../types/types.js';\n\nimport {metricSavingsForWastedBytes} from './Common.js';\nimport {linearInterpolation} from './Statistics.js';\nimport {\n InsightCategory,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that provides information and suggestions of resources that could improve their caching.\n */\n title: 'Use efficient cache lifetimes',\n /**\n * @description Text to tell the user about how caching can help improve performance.\n */\n description:\n 'A long cache lifetime can speed up repeat visits to your page. [Learn more](https://web.dev/uses-long-cache-ttl/).',\n /**\n * @description Column for a font loaded by the page to render text.\n */\n requestColumn: 'Request',\n /**\n * @description Column for a resource cache's Time To Live.\n */\n cacheTTL: 'Cache TTL',\n /**\n * @description Text describing that there were no requests found that need caching.\n */\n noRequestsToCache: 'No requests with inefficient cache policies',\n /**\n * @description Table row value representing the remaining items not shown in the table due to size constraints. This row will always represent at least 2 items.\n * @example {5} PH1\n */\n others: '{PH1} others',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/Cache.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type CacheInsightModel = InsightModel<typeof UIStrings, {\n requests: Array<{\n request: Types.Events.SyntheticNetworkRequest,\n ttl: number,\n wastedBytes: number,\n }>,\n totalWastedBytes: number,\n}>;\n\n// Threshold for cache hits.\nconst IGNORE_THRESHOLD_IN_PERCENT = 0.925;\n\nfunction finalize(partialModel: PartialInsightModel<CacheInsightModel>): CacheInsightModel {\n return {\n insightKey: 'Cache',\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: partialModel.requests.length > 0 ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\n/**\n * Determines if a request is \"cacheable\".\n * A request is \"cacheable\" if it is of the appropriate protocol and resource type\n * (see Helpers.Network.NON_NETWORK_SCHEMES and Helpers.Network.STATIC_RESOURCE_TYPE)\n * and has the appropriate statusCodes.\n */\nexport function isCacheable(request: Types.Events.SyntheticNetworkRequest): boolean {\n // Caching doesn't make sense for requests not loaded over the network.\n if (Helpers.Network.NON_NETWORK_SCHEMES.includes(request.args.data.protocol)) {\n return false;\n }\n return Boolean(\n Helpers.Network.CACHEABLE_STATUS_CODES.has(request.args.data.statusCode) &&\n Helpers.Network.STATIC_RESOURCE_TYPES.has(request.args.data.resourceType || Protocol.Network.ResourceType.Other));\n}\n\n/**\n * Returns max-age if defined, otherwise expires header if defined, and null if not.\n */\nexport function computeCacheLifetimeInSeconds(\n headers: Array<{name: string, value: string}>, cacheControl: Helpers.Network.CacheControl|null): number|null {\n if (cacheControl?.['max-age'] !== undefined) {\n return cacheControl['max-age'];\n }\n\n const expiresHeaders = headers.find(h => h.name === 'expires')?.value ?? null;\n if (expiresHeaders) {\n const expires = new Date(expiresHeaders).getTime();\n // Treat expires values as having already expired.\n if (!expires) {\n return 0;\n }\n return Math.ceil((expires - Date.now()) / 1000);\n }\n return null;\n}\n\n/**\n * Computes the percent likelihood that a return visit will be within the cache lifetime, based on\n * Chrome UMA stats see the note below.\n * See https://github.com/GoogleChrome/lighthouse/blob/aba818f733552189de35121907cb5625a74af640/core/audits/byte-efficiency/uses-long-cache-ttl.js\n * TODO: This Chrome UMA stat is outdated. Using this is fine for now, but update in follow-up.\n */\nfunction getCacheHitProbability(maxAgeInSeconds: number): number {\n // This array contains the hand wavy distribution of the age of a resource in hours at the time of\n // cache hit at 0th, 10th, 20th, 30th, etc percentiles. This is used to compute `wastedMs` since there\n // are clearly diminishing returns to cache duration i.e. 6 months is not 2x better than 3 months.\n // Based on UMA stats for HttpCache.StaleEntry.Validated.Age, see https://www.desmos.com/calculator/7v0qh1nzvh\n // Example: a max-age of 12 hours already covers ~50% of cases, doubling to 24 hours covers ~10% more.\n const RESOURCE_AGE_IN_HOURS_DECILES = [0, 0.2, 1, 3, 8, 12, 24, 48, 72, 168, 8760, Infinity];\n\n const maxAgeInHours = maxAgeInSeconds / 3600;\n const upperDecileIndex = RESOURCE_AGE_IN_HOURS_DECILES.findIndex(decile => decile >= maxAgeInHours);\n\n // Clip the likelihood between 0 and 1\n if (upperDecileIndex === RESOURCE_AGE_IN_HOURS_DECILES.length - 1) {\n return 1;\n }\n if (upperDecileIndex === 0) {\n return 0;\n }\n\n // Use the two closest decile points as control points\n const upperDecileValue = RESOURCE_AGE_IN_HOURS_DECILES[upperDecileIndex];\n const lowerDecileValue = RESOURCE_AGE_IN_HOURS_DECILES[upperDecileIndex - 1];\n const upperDecile = upperDecileIndex / 10;\n const lowerDecile = (upperDecileIndex - 1) / 10;\n\n // Approximate the real likelihood with linear interpolation\n return linearInterpolation(lowerDecileValue, lowerDecile, upperDecileValue, upperDecile, maxAgeInHours);\n}\n\nexport function getCombinedHeaders(responseHeaders: Array<{name: string, value: string}>): Map<string, string> {\n const headers = new Map<string, string>();\n for (const header of responseHeaders) {\n const name = header.name.toLowerCase();\n if (headers.get(name)) {\n headers.set(name, `${headers.get(name)}, ${header.value}`);\n } else {\n headers.set(name, header.value);\n }\n }\n return headers;\n}\n\n/**\n * Returns whether a request contains headers that disable caching.\n * Disabled caching is checked on the 'cache-control' and 'pragma' headers.\n */\nexport function cachingDisabled(\n headers: Map<string, string>|null, parsedCacheControl: Helpers.Network.CacheControl|null): boolean {\n const cacheControl = headers?.get('cache-control') ?? null;\n const pragma = headers?.get('pragma') ?? null;\n\n // The HTTP/1.0 Pragma header can disable caching if cache-control is not set, see https://tools.ietf.org/html/rfc7234#section-5.4\n if (!cacheControl && pragma?.includes('no-cache')) {\n return true;\n }\n\n // If we have any of these, the user intentionally doesn't want to cache.\n if (parsedCacheControl &&\n (parsedCacheControl['must-revalidate'] || parsedCacheControl['no-cache'] || parsedCacheControl['no-store'] ||\n parsedCacheControl['private'])) {\n return true;\n }\n\n return false;\n}\n\nexport interface CacheableRequest {\n request: Types.Events.SyntheticNetworkRequest;\n ttl: number;\n wastedBytes: number;\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): CacheInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => Helpers.Timing.eventIsInBounds(event, context.bounds);\n const contextRequests = parsedTrace.NetworkRequests.byTime.filter(isWithinContext);\n\n const results: CacheableRequest[] = [];\n let totalWastedBytes = 0;\n const wastedBytesByRequestId = new Map<string, number>();\n for (const req of contextRequests) {\n if (!isCacheable(req)) {\n continue;\n }\n\n const headers = getCombinedHeaders(req.args.data.responseHeaders);\n const cacheControl = headers.get('cache-control') ?? null;\n const parsedDirectives = Helpers.Network.parseCacheControl(cacheControl);\n\n // Skip requests that are deliberately avoiding caching.\n if (cachingDisabled(headers, parsedDirectives)) {\n continue;\n }\n\n let ttl = computeCacheLifetimeInSeconds(req.args.data.responseHeaders, parsedDirectives);\n // Ignore if a non-positive number.\n if (ttl !== null && (!Number.isFinite(ttl) || ttl <= 0)) {\n continue;\n }\n ttl = ttl || 0;\n\n // Ignore >= 30d.\n const ttlDays = ttl / 86400;\n if (ttlDays >= 30) {\n continue;\n }\n\n // If cache lifetime is high enough, let's skip.\n const cacheHitProbability = getCacheHitProbability(ttl);\n if (cacheHitProbability > IGNORE_THRESHOLD_IN_PERCENT) {\n continue;\n }\n\n const transferSize = req.args.data.encodedDataLength || 0;\n const wastedBytes = (1 - cacheHitProbability) * transferSize;\n\n wastedBytesByRequestId.set(req.args.data.requestId, wastedBytes);\n totalWastedBytes += wastedBytes;\n\n results.push({request: req, ttl, wastedBytes});\n }\n\n // Sort by transfer size.\n results.sort((a, b) => {\n return b.request.args.data.decodedBodyLength - a.request.args.data.decodedBodyLength || a.ttl - b.ttl;\n });\n\n return finalize({\n relatedEvents: results.map(r => r.request),\n requests: results,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n totalWastedBytes,\n });\n}\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import * as Protocol from '../../../generated/protocol.js';
|
|
1
2
|
// import type * as CrUXManager from '../../crux-manager/crux-manager.js';
|
|
3
|
+
import type * as Handlers from '../handlers/handlers.js';
|
|
2
4
|
import * as Types from '../types/types.js';
|
|
3
5
|
import { type InsightModels, type InsightSet, type InsightSetContext, type MetricSavings, type TraceInsightSets } from './types.js';
|
|
4
6
|
export declare function getInsight<InsightName extends keyof InsightModels>(insightName: InsightName, insights: TraceInsightSets | null, key: string | null): InsightModels[InsightName] | null;
|
|
@@ -14,8 +16,8 @@ export declare function getCLS(insights: TraceInsightSets | null, key: string |
|
|
|
14
16
|
value: number;
|
|
15
17
|
worstClusterEvent: Types.Events.Event | null;
|
|
16
18
|
};
|
|
17
|
-
export declare function evaluateLCPMetricScore(value:
|
|
18
|
-
export declare function evaluateINPMetricScore(value:
|
|
19
|
+
export declare function evaluateLCPMetricScore(value: Types.Timing.Milli): number;
|
|
20
|
+
export declare function evaluateINPMetricScore(value: Types.Timing.Milli): number;
|
|
19
21
|
export declare function evaluateCLSMetricScore(value: number): number;
|
|
20
22
|
export interface CrUXFieldMetricTimingResult {
|
|
21
23
|
value: Types.Timing.Micro;
|
|
@@ -47,3 +49,20 @@ export declare function calculateMetricWeightsForSorting(insightSet: InsightSet,
|
|
|
47
49
|
* Estimates the FCP & LCP savings for wasted bytes in `wastedBytesByRequestId`.
|
|
48
50
|
*/
|
|
49
51
|
export declare function metricSavingsForWastedBytes(wastedBytesByRequestId: Map<string, number>, context: InsightSetContext): MetricSavings | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Returns whether the network request was sent encoded.
|
|
54
|
+
*/
|
|
55
|
+
export declare function isRequestCompressed(request: Types.Events.SyntheticNetworkRequest): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Estimates the number of bytes the content of this network record would have consumed on the network based on the
|
|
58
|
+
* uncompressed size (totalBytes). Uses the actual transfer size from the network record if applicable,
|
|
59
|
+
* minus the size of the response headers.
|
|
60
|
+
*
|
|
61
|
+
* @param totalBytes Uncompressed size of the resource
|
|
62
|
+
*/
|
|
63
|
+
export declare function estimateCompressedContentSize(request: Types.Events.SyntheticNetworkRequest | undefined, totalBytes: number, resourceType: Protocol.Network.ResourceType): number;
|
|
64
|
+
/**
|
|
65
|
+
* Utility function to estimate the ratio of the compression of a script.
|
|
66
|
+
* This excludes the size of the response headers.
|
|
67
|
+
*/
|
|
68
|
+
export declare function estimateCompressionRatioForScript(script: Handlers.ModelHandlers.Scripts.Script): number;
|
|
@@ -137,8 +137,8 @@ export function calculateMetricWeightsForSorting(insightSet, metadata) {
|
|
|
137
137
|
const fieldLcp = fieldMetrics.lcp?.value ?? null;
|
|
138
138
|
const fieldInp = fieldMetrics.inp?.value ?? null;
|
|
139
139
|
const fieldCls = fieldMetrics.cls?.value ?? null;
|
|
140
|
-
const fieldLcpScore = fieldLcp !== null ? evaluateLCPMetricScore(fieldLcp) : 0;
|
|
141
|
-
const fieldInpScore = fieldInp !== null ? evaluateINPMetricScore(fieldInp) : 0;
|
|
140
|
+
const fieldLcpScore = fieldLcp !== null ? evaluateLCPMetricScore(Helpers.Timing.microToMilli(fieldLcp)) : 0;
|
|
141
|
+
const fieldInpScore = fieldInp !== null ? evaluateINPMetricScore(Helpers.Timing.microToMilli(fieldInp)) : 0;
|
|
142
142
|
const fieldClsScore = fieldCls !== null ? evaluateCLSMetricScore(fieldCls) : 0;
|
|
143
143
|
const fieldLcpScoreInverted = 1 - fieldLcpScore;
|
|
144
144
|
const fieldInpScoreInverted = 1 - fieldInpScore;
|
|
@@ -204,4 +204,88 @@ export function metricSavingsForWastedBytes(wastedBytesByRequestId, context) {
|
|
|
204
204
|
LCP: estimateSavingsWithGraphs(wastedBytesByRequestId, simulator, lcpGraph),
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Returns whether the network request was sent encoded.
|
|
209
|
+
*/
|
|
210
|
+
export function isRequestCompressed(request) {
|
|
211
|
+
// FYI: In Lighthouse, older devtools logs (like our test fixtures) seems to be
|
|
212
|
+
// lower case, while modern logs are Cased-Like-This.
|
|
213
|
+
const patterns = [
|
|
214
|
+
/^content-encoding$/i, /^x-content-encoding-over-network$/i,
|
|
215
|
+
/^x-original-content-encoding$/i, // Lightrider.
|
|
216
|
+
];
|
|
217
|
+
const compressionTypes = ['gzip', 'br', 'deflate', 'zstd'];
|
|
218
|
+
return request.args.data.responseHeaders.some(header => patterns.some(p => header.name.match(p)) && compressionTypes.includes(header.value));
|
|
219
|
+
}
|
|
220
|
+
function getRequestSizes(request) {
|
|
221
|
+
const resourceSize = request.args.data.decodedBodyLength;
|
|
222
|
+
const transferSize = request.args.data.encodedDataLength;
|
|
223
|
+
return { resourceSize, transferSize };
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Estimates the number of bytes the content of this network record would have consumed on the network based on the
|
|
227
|
+
* uncompressed size (totalBytes). Uses the actual transfer size from the network record if applicable,
|
|
228
|
+
* minus the size of the response headers.
|
|
229
|
+
*
|
|
230
|
+
* @param totalBytes Uncompressed size of the resource
|
|
231
|
+
*/
|
|
232
|
+
export function estimateCompressedContentSize(request, totalBytes, resourceType) {
|
|
233
|
+
if (!request) {
|
|
234
|
+
// We don't know how many bytes this asset used on the network, but we can guess it was
|
|
235
|
+
// roughly the size of the content gzipped.
|
|
236
|
+
// See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer for specific CSS/Script examples
|
|
237
|
+
// See https://discuss.httparchive.org/t/file-size-and-compression-savings/145 for fallback multipliers
|
|
238
|
+
switch (resourceType) {
|
|
239
|
+
case 'Stylesheet':
|
|
240
|
+
// Stylesheets tend to compress extremely well.
|
|
241
|
+
return Math.round(totalBytes * 0.2);
|
|
242
|
+
case 'Script':
|
|
243
|
+
case 'Document':
|
|
244
|
+
// Scripts and HTML compress fairly well too.
|
|
245
|
+
return Math.round(totalBytes * 0.33);
|
|
246
|
+
default:
|
|
247
|
+
// Otherwise we'll just fallback to the average savings in HTTPArchive
|
|
248
|
+
return Math.round(totalBytes * 0.5);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Get the size of the response body on the network.
|
|
252
|
+
const { transferSize, resourceSize } = getRequestSizes(request);
|
|
253
|
+
let contentTransferSize = transferSize;
|
|
254
|
+
if (!isRequestCompressed(request)) {
|
|
255
|
+
// This is not compressed, so we can use resourceSize directly.
|
|
256
|
+
// This would be equivalent to transfer size minus headers transfer size, but transfer size
|
|
257
|
+
// may also include bytes for SSL connection etc.
|
|
258
|
+
contentTransferSize = resourceSize;
|
|
259
|
+
}
|
|
260
|
+
// TODO(cjamcl): Get "responseHeadersTransferSize" in Network handler.
|
|
261
|
+
// else if (request.responseHeadersTransferSize) {
|
|
262
|
+
// // Subtract the size of the encoded headers.
|
|
263
|
+
// contentTransferSize =
|
|
264
|
+
// Math.max(0, contentTransferSize - request.responseHeadersTransferSize);
|
|
265
|
+
// }
|
|
266
|
+
if (request.args.data.resourceType === resourceType) {
|
|
267
|
+
// This was a regular standalone asset, just use the transfer size.
|
|
268
|
+
return contentTransferSize;
|
|
269
|
+
}
|
|
270
|
+
// This was an asset that was inlined in a different resource type (e.g. HTML document).
|
|
271
|
+
// Use the compression ratio of the resource to estimate the total transferred bytes.
|
|
272
|
+
// Get the compression ratio, if it's an invalid number, assume no compression.
|
|
273
|
+
const compressionRatio = Number.isFinite(resourceSize) && resourceSize > 0 ? (contentTransferSize / resourceSize) : 1;
|
|
274
|
+
return Math.round(totalBytes * compressionRatio);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Utility function to estimate the ratio of the compression of a script.
|
|
278
|
+
* This excludes the size of the response headers.
|
|
279
|
+
*/
|
|
280
|
+
export function estimateCompressionRatioForScript(script) {
|
|
281
|
+
if (!script.request) {
|
|
282
|
+
// Can't find request, so just use 1.
|
|
283
|
+
return 1;
|
|
284
|
+
}
|
|
285
|
+
const request = script.request;
|
|
286
|
+
const contentLength = request.args.data.decodedBodyLength ?? script.content?.length ?? 0;
|
|
287
|
+
const compressedSize = estimateCompressedContentSize(request, contentLength, "Script" /* Protocol.Network.ResourceType.Script */);
|
|
288
|
+
const compressionRatio = compressedSize / contentLength;
|
|
289
|
+
return compressionRatio;
|
|
290
|
+
}
|
|
207
291
|
//# sourceMappingURL=Common.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Common.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/Common.ts"],"names":[],"mappings":"AAAA,4DAA4D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AAM,UAAU,2BAA2B,CACvC,sBAA2C,EAAE,OAA0B;IACzE,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC5C,OAAO;IACT,CAAC;IAED,IAAI,CAAC,sBAAsB,CAAC,IAAI,EAAE,CAAC;QACjC,OAAO,EAAC,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAC,CAAC;IAClE,CAAC;IAED,MAAM,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;IAC5C,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,eAAe,CAAC;IAC9E,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,sBAAsB,CAAC,eAAe,CAAC;IAEhF,OAAO;QACL,GAAG,EAAE,yBAAyB,CAAC,sBAAsB,EAAE,SAAS,EAAE,QAAQ,CAAC;QAC3E,GAAG,EAAE,yBAAyB,CAAC,sBAAsB,EAAE,SAAS,EAAE,QAAQ,CAAC;KAC5E,CAAC;AACJ,CAAC","sourcesContent":["// 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 type * as CrUXManager from '../../crux-manager/crux-manager.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Lantern from '../lantern/lantern.js';\nimport * as Types from '../types/types.js';\n\nimport {getLogNormalScore} from './Statistics.js';\nimport {\n InsightKeys,\n type InsightModels,\n type InsightSet,\n type InsightSetContext,\n type MetricSavings,\n type TraceInsightSets\n} from './types.js';\n\nconst GRAPH_SAVINGS_PRECISION = 50;\n\nexport function getInsight<InsightName extends keyof InsightModels>(\n insightName: InsightName, insights: TraceInsightSets|null, key: string|null): InsightModels[InsightName]|null {\n if (!insights || !key) {\n return null;\n }\n\n const insightSets = insights.get(key);\n if (!insightSets) {\n return null;\n }\n\n const insight = insightSets.model[insightName];\n if (insight instanceof Error) {\n return null;\n }\n\n // For some reason typescript won't narrow the type by removing Error, so do it manually.\n return insight;\n}\n\nexport function getLCP(insights: TraceInsightSets|null, key: string|null):\n {value: Types.Timing.Micro, event: Types.Events.LargestContentfulPaintCandidate}|null {\n const insight = getInsight(InsightKeys.LCP_PHASES, insights, key);\n if (!insight || !insight.lcpMs || !insight.lcpEvent) {\n return null;\n }\n\n const value = Helpers.Timing.milliToMicro(insight.lcpMs);\n return {value, event: insight.lcpEvent};\n}\n\nexport function getINP(insights: TraceInsightSets|null, key: string|null):\n {value: Types.Timing.Micro, event: Types.Events.SyntheticInteractionPair}|null {\n const insight = getInsight(InsightKeys.INTERACTION_TO_NEXT_PAINT, insights, key);\n if (!insight?.longestInteractionEvent?.dur) {\n return null;\n }\n\n const value = insight.longestInteractionEvent.dur;\n return {value, event: insight.longestInteractionEvent};\n}\n\nexport function getCLS(\n insights: TraceInsightSets|null, key: string|null): {value: number, worstClusterEvent: Types.Events.Event|null} {\n const insight = getInsight(InsightKeys.CLS_CULPRITS, insights, key);\n if (!insight) {\n // Unlike the other metrics, there is always a value for CLS even with no data.\n return {value: 0, worstClusterEvent: null};\n }\n\n // TODO(cjamcl): the CLS insight should be doing this for us.\n let maxScore = 0;\n let worstCluster;\n for (const cluster of insight.clusters) {\n if (cluster.clusterCumulativeScore > maxScore) {\n maxScore = cluster.clusterCumulativeScore;\n worstCluster = cluster;\n }\n }\n\n return {value: maxScore, worstClusterEvent: worstCluster ?? null};\n}\n\nexport function evaluateLCPMetricScore(value: number): number {\n return getLogNormalScore({p10: 2500, median: 4000}, value);\n}\n\nexport function evaluateINPMetricScore(value: number): number {\n return getLogNormalScore({p10: 200, median: 500}, value);\n}\n\nexport function evaluateCLSMetricScore(value: number): number {\n return getLogNormalScore({p10: 0.1, median: 0.25}, value);\n}\n\nexport interface CrUXFieldMetricTimingResult {\n value: Types.Timing.Micro;\n pageScope: CrUXManager.PageScope;\n}\nexport interface CrUXFieldMetricNumberResult {\n value: number;\n pageScope: CrUXManager.PageScope;\n}\nexport interface CrUXFieldMetricResults {\n fcp: CrUXFieldMetricTimingResult|null;\n lcp: CrUXFieldMetricTimingResult|null;\n inp: CrUXFieldMetricTimingResult|null;\n cls: CrUXFieldMetricNumberResult|null;\n lcpPhases: {\n ttfb: CrUXFieldMetricTimingResult|null,\n loadDelay: CrUXFieldMetricTimingResult|null,\n loadDuration: CrUXFieldMetricTimingResult|null,\n renderDelay: CrUXFieldMetricTimingResult|null,\n };\n}\n\nfunction getPageResult(\n cruxFieldData: CrUXManager.PageResult[], url: string, origin: string,\n scope: CrUXManager.Scope|null = null): CrUXManager.PageResult|undefined {\n return cruxFieldData.find(result => {\n const key = scope ? result[`${scope.pageScope}-${scope.deviceScope}`]?.record.key :\n (result['url-ALL'] || result['origin-ALL'])?.record.key;\n return (key?.url && key.url === url) || (key?.origin && key.origin === origin);\n });\n}\n\nfunction getMetricResult(\n pageResult: CrUXManager.PageResult, name: CrUXManager.StandardMetricNames,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricNumberResult|null {\n const scopes: Array<{pageScope: CrUXManager.PageScope, deviceScope: CrUXManager.DeviceScope}> = [];\n if (scope) {\n scopes.push(scope);\n } else {\n scopes.push({pageScope: 'url', deviceScope: 'ALL'});\n scopes.push({pageScope: 'origin', deviceScope: 'ALL'});\n }\n\n for (const scope of scopes) {\n const key = `${scope.pageScope}-${scope.deviceScope}` as const;\n let value = pageResult[key]?.record.metrics[name]?.percentiles?.p75;\n if (typeof value === 'string') {\n value = Number(value);\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return {value, pageScope: scope.pageScope};\n }\n }\n\n return null;\n}\n\nfunction getMetricTimingResult(\n pageResult: CrUXManager.PageResult, name: CrUXManager.StandardMetricNames,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricTimingResult|null {\n const result = getMetricResult(pageResult, name, scope);\n if (result) {\n const valueMs = result.value as Types.Timing.Milli;\n return {value: Helpers.Timing.milliToMicro(valueMs), pageScope: result.pageScope};\n }\n\n return null;\n}\n\nexport function getFieldMetricsForInsightSet(\n insightSet: InsightSet, metadata: Types.File.MetaData|null,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricResults|null {\n const cruxFieldData = metadata?.cruxFieldData;\n if (!cruxFieldData) {\n return null;\n }\n\n const pageResult = getPageResult(cruxFieldData, insightSet.url.href, insightSet.url.origin, scope);\n if (!pageResult) {\n return null;\n }\n\n return {\n fcp: getMetricTimingResult(pageResult, 'first_contentful_paint', scope),\n lcp: getMetricTimingResult(pageResult, 'largest_contentful_paint', scope),\n inp: getMetricTimingResult(pageResult, 'interaction_to_next_paint', scope),\n cls: getMetricResult(pageResult, 'cumulative_layout_shift', scope),\n lcpPhases: {\n ttfb: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_time_to_first_byte', scope),\n loadDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_delay', scope),\n loadDuration: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_duration', scope),\n renderDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_element_render_delay', scope),\n }\n };\n}\n\nexport function calculateMetricWeightsForSorting(\n insightSet: InsightSet, metadata: Types.File.MetaData|null): {lcp: number, inp: number, cls: number} {\n const weights = {\n lcp: 1 / 3,\n inp: 1 / 3,\n cls: 1 / 3,\n };\n\n const cruxFieldData = metadata?.cruxFieldData;\n if (!cruxFieldData) {\n return weights;\n }\n\n const fieldMetrics = getFieldMetricsForInsightSet(insightSet, metadata);\n if (!fieldMetrics) {\n return weights;\n }\n\n const fieldLcp = fieldMetrics.lcp?.value ?? null;\n const fieldInp = fieldMetrics.inp?.value ?? null;\n const fieldCls = fieldMetrics.cls?.value ?? null;\n const fieldLcpScore = fieldLcp !== null ? evaluateLCPMetricScore(fieldLcp) : 0;\n const fieldInpScore = fieldInp !== null ? evaluateINPMetricScore(fieldInp) : 0;\n const fieldClsScore = fieldCls !== null ? evaluateCLSMetricScore(fieldCls) : 0;\n const fieldLcpScoreInverted = 1 - fieldLcpScore;\n const fieldInpScoreInverted = 1 - fieldInpScore;\n const fieldClsScoreInverted = 1 - fieldClsScore;\n const invertedSum = fieldLcpScoreInverted + fieldInpScoreInverted + fieldClsScoreInverted;\n if (!invertedSum) {\n return weights;\n }\n\n weights.lcp = fieldLcpScoreInverted / invertedSum;\n weights.inp = fieldInpScoreInverted / invertedSum;\n weights.cls = fieldClsScoreInverted / invertedSum;\n\n return weights;\n}\n\n/**\n * Simulates the provided graph before and after the byte savings from `wastedBytesByRequestId` are applied.\n */\nfunction estimateSavingsWithGraphs(\n wastedBytesByRequestId: Map<string, number>, simulator: Lantern.Simulation.Simulator,\n graph: Lantern.Graph.Node): Types.Timing.Milli {\n const simulationBeforeChanges = simulator.simulate(graph);\n\n const originalTransferSizes = new Map<string, number>();\n graph.traverse(node => {\n if (node.type !== 'network') {\n return;\n }\n const wastedBytes = wastedBytesByRequestId.get(node.request.requestId);\n if (!wastedBytes) {\n return;\n }\n\n const original = node.request.transferSize;\n originalTransferSizes.set(node.request.requestId, original);\n\n node.request.transferSize = Math.max(original - wastedBytes, 0);\n });\n\n const simulationAfterChanges = simulator.simulate(graph);\n\n // Restore the original transfer size after we've done our simulation\n graph.traverse(node => {\n if (node.type !== 'network') {\n return;\n }\n const originalTransferSize = originalTransferSizes.get(node.request.requestId);\n if (originalTransferSize === undefined) {\n return;\n }\n node.request.transferSize = originalTransferSize;\n });\n\n let savings = simulationBeforeChanges.timeInMs - simulationAfterChanges.timeInMs;\n savings = Math.round(savings / GRAPH_SAVINGS_PRECISION) * GRAPH_SAVINGS_PRECISION;\n return Types.Timing.Milli(savings);\n}\n\n/**\n * Estimates the FCP & LCP savings for wasted bytes in `wastedBytesByRequestId`.\n */\nexport function metricSavingsForWastedBytes(\n wastedBytesByRequestId: Map<string, number>, context: InsightSetContext): MetricSavings|undefined {\n if (!context.navigation || !context.lantern) {\n return;\n }\n\n if (!wastedBytesByRequestId.size) {\n return {FCP: Types.Timing.Milli(0), LCP: Types.Timing.Milli(0)};\n }\n\n const simulator = context.lantern.simulator;\n const fcpGraph = context.lantern.metrics.firstContentfulPaint.optimisticGraph;\n const lcpGraph = context.lantern.metrics.largestContentfulPaint.optimisticGraph;\n\n return {\n FCP: estimateSavingsWithGraphs(wastedBytesByRequestId, simulator, fcpGraph),\n LCP: estimateSavingsWithGraphs(wastedBytesByRequestId, simulator, lcpGraph),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Common.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/Common.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAK7B,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAEjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,iBAAiB,EAAC,MAAM,iBAAiB,CAAC;AAUlD,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAEnC,MAAM,UAAU,UAAU,CACtB,WAAwB,EAAE,QAA+B,EAAE,GAAgB;IAC7E,IAAI,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,WAAW,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACtC,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,OAAO,GAAG,WAAW,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAC/C,IAAI,OAAO,YAAY,KAAK,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,yFAAyF;IACzF,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,QAA+B,EAAE,GAAgB;IAEtE,MAAM,OA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I,CAAC,IAAI,CAAC,iBAAiB,IAAI,MAAM,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC;IACzF,MAAM,cAAc,GAAG,6BAA6B,CAAC,OAAO,EAAE,aAAa,sDAAuC,CAAC;IACnH,MAAM,gBAAgB,GAAG,cAAc,GAAG,aAAa,CAAC;IACxD,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["// 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 Protocol from '../../../generated/protocol.js';\nimport type * as CrUXManager from '../../crux-manager/crux-manager.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Lantern from '../lantern/lantern.js';\nimport * as Types from '../types/types.js';\n\nimport {getLogNormalScore} from './Statistics.js';\nimport {\n InsightKeys,\n type InsightModels,\n type InsightSet,\n type InsightSetContext,\n type MetricSavings,\n type TraceInsightSets\n} from './types.js';\n\nconst GRAPH_SAVINGS_PRECISION = 50;\n\nexport function getInsight<InsightName extends keyof InsightModels>(\n insightName: InsightName, insights: TraceInsightSets|null, key: string|null): InsightModels[InsightName]|null {\n if (!insights || !key) {\n return null;\n }\n\n const insightSets = insights.get(key);\n if (!insightSets) {\n return null;\n }\n\n const insight = insightSets.model[insightName];\n if (insight instanceof Error) {\n return null;\n }\n\n // For some reason typescript won't narrow the type by removing Error, so do it manually.\n return insight;\n}\n\nexport function getLCP(insights: TraceInsightSets|null, key: string|null):\n {value: Types.Timing.Micro, event: Types.Events.LargestContentfulPaintCandidate}|null {\n const insight = getInsight(InsightKeys.LCP_PHASES, insights, key);\n if (!insight || !insight.lcpMs || !insight.lcpEvent) {\n return null;\n }\n\n const value = Helpers.Timing.milliToMicro(insight.lcpMs);\n return {value, event: insight.lcpEvent};\n}\n\nexport function getINP(insights: TraceInsightSets|null, key: string|null):\n {value: Types.Timing.Micro, event: Types.Events.SyntheticInteractionPair}|null {\n const insight = getInsight(InsightKeys.INTERACTION_TO_NEXT_PAINT, insights, key);\n if (!insight?.longestInteractionEvent?.dur) {\n return null;\n }\n\n const value = insight.longestInteractionEvent.dur;\n return {value, event: insight.longestInteractionEvent};\n}\n\nexport function getCLS(\n insights: TraceInsightSets|null, key: string|null): {value: number, worstClusterEvent: Types.Events.Event|null} {\n const insight = getInsight(InsightKeys.CLS_CULPRITS, insights, key);\n if (!insight) {\n // Unlike the other metrics, there is always a value for CLS even with no data.\n return {value: 0, worstClusterEvent: null};\n }\n\n // TODO(cjamcl): the CLS insight should be doing this for us.\n let maxScore = 0;\n let worstCluster;\n for (const cluster of insight.clusters) {\n if (cluster.clusterCumulativeScore > maxScore) {\n maxScore = cluster.clusterCumulativeScore;\n worstCluster = cluster;\n }\n }\n\n return {value: maxScore, worstClusterEvent: worstCluster ?? null};\n}\n\nexport function evaluateLCPMetricScore(value: Types.Timing.Milli): number {\n return getLogNormalScore({p10: 2500, median: 4000}, value);\n}\n\nexport function evaluateINPMetricScore(value: Types.Timing.Milli): number {\n return getLogNormalScore({p10: 200, median: 500}, value);\n}\n\nexport function evaluateCLSMetricScore(value: number): number {\n return getLogNormalScore({p10: 0.1, median: 0.25}, value);\n}\n\nexport interface CrUXFieldMetricTimingResult {\n value: Types.Timing.Micro;\n pageScope: CrUXManager.PageScope;\n}\nexport interface CrUXFieldMetricNumberResult {\n value: number;\n pageScope: CrUXManager.PageScope;\n}\nexport interface CrUXFieldMetricResults {\n fcp: CrUXFieldMetricTimingResult|null;\n lcp: CrUXFieldMetricTimingResult|null;\n inp: CrUXFieldMetricTimingResult|null;\n cls: CrUXFieldMetricNumberResult|null;\n lcpPhases: {\n ttfb: CrUXFieldMetricTimingResult|null,\n loadDelay: CrUXFieldMetricTimingResult|null,\n loadDuration: CrUXFieldMetricTimingResult|null,\n renderDelay: CrUXFieldMetricTimingResult|null,\n };\n}\n\nfunction getPageResult(\n cruxFieldData: CrUXManager.PageResult[], url: string, origin: string,\n scope: CrUXManager.Scope|null = null): CrUXManager.PageResult|undefined {\n return cruxFieldData.find(result => {\n const key = scope ? result[`${scope.pageScope}-${scope.deviceScope}`]?.record.key :\n (result['url-ALL'] || result['origin-ALL'])?.record.key;\n return (key?.url && key.url === url) || (key?.origin && key.origin === origin);\n });\n}\n\nfunction getMetricResult(\n pageResult: CrUXManager.PageResult, name: CrUXManager.StandardMetricNames,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricNumberResult|null {\n const scopes: Array<{pageScope: CrUXManager.PageScope, deviceScope: CrUXManager.DeviceScope}> = [];\n if (scope) {\n scopes.push(scope);\n } else {\n scopes.push({pageScope: 'url', deviceScope: 'ALL'});\n scopes.push({pageScope: 'origin', deviceScope: 'ALL'});\n }\n\n for (const scope of scopes) {\n const key = `${scope.pageScope}-${scope.deviceScope}` as const;\n let value = pageResult[key]?.record.metrics[name]?.percentiles?.p75;\n if (typeof value === 'string') {\n value = Number(value);\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return {value, pageScope: scope.pageScope};\n }\n }\n\n return null;\n}\n\nfunction getMetricTimingResult(\n pageResult: CrUXManager.PageResult, name: CrUXManager.StandardMetricNames,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricTimingResult|null {\n const result = getMetricResult(pageResult, name, scope);\n if (result) {\n const valueMs = result.value as Types.Timing.Milli;\n return {value: Helpers.Timing.milliToMicro(valueMs), pageScope: result.pageScope};\n }\n\n return null;\n}\n\nexport function getFieldMetricsForInsightSet(\n insightSet: InsightSet, metadata: Types.File.MetaData|null,\n scope: CrUXManager.Scope|null = null): CrUXFieldMetricResults|null {\n const cruxFieldData = metadata?.cruxFieldData;\n if (!cruxFieldData) {\n return null;\n }\n\n const pageResult = getPageResult(cruxFieldData, insightSet.url.href, insightSet.url.origin, scope);\n if (!pageResult) {\n return null;\n }\n\n return {\n fcp: getMetricTimingResult(pageResult, 'first_contentful_paint', scope),\n lcp: getMetricTimingResult(pageResult, 'largest_contentful_paint', scope),\n inp: getMetricTimingResult(pageResult, 'interaction_to_next_paint', scope),\n cls: getMetricResult(pageResult, 'cumulative_layout_shift', scope),\n lcpPhases: {\n ttfb: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_time_to_first_byte', scope),\n loadDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_delay', scope),\n loadDuration: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_duration', scope),\n renderDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_element_render_delay', scope),\n }\n };\n}\n\nexport function calculateMetricWeightsForSorting(\n insightSet: InsightSet, metadata: Types.File.MetaData|null): {lcp: number, inp: number, cls: number} {\n const weights = {\n lcp: 1 / 3,\n inp: 1 / 3,\n cls: 1 / 3,\n };\n\n const cruxFieldData = metadata?.cruxFieldData;\n if (!cruxFieldData) {\n return weights;\n }\n\n const fieldMetrics = getFieldMetricsForInsightSet(insightSet, metadata);\n if (!fieldMetrics) {\n return weights;\n }\n\n const fieldLcp = fieldMetrics.lcp?.value ?? null;\n const fieldInp = fieldMetrics.inp?.value ?? null;\n const fieldCls = fieldMetrics.cls?.value ?? null;\n const fieldLcpScore = fieldLcp !== null ? evaluateLCPMetricScore(Helpers.Timing.microToMilli(fieldLcp)) : 0;\n const fieldInpScore = fieldInp !== null ? evaluateINPMetricScore(Helpers.Timing.microToMilli(fieldInp)) : 0;\n const fieldClsScore = fieldCls !== null ? evaluateCLSMetricScore(fieldCls) : 0;\n const fieldLcpScoreInverted = 1 - fieldLcpScore;\n const fieldInpScoreInverted = 1 - fieldInpScore;\n const fieldClsScoreInverted = 1 - fieldClsScore;\n const invertedSum = fieldLcpScoreInverted + fieldInpScoreInverted + fieldClsScoreInverted;\n if (!invertedSum) {\n return weights;\n }\n\n weights.lcp = fieldLcpScoreInverted / invertedSum;\n weights.inp = fieldInpScoreInverted / invertedSum;\n weights.cls = fieldClsScoreInverted / invertedSum;\n\n return weights;\n}\n\n/**\n * Simulates the provided graph before and after the byte savings from `wastedBytesByRequestId` are applied.\n */\nfunction estimateSavingsWithGraphs(\n wastedBytesByRequestId: Map<string, number>, simulator: Lantern.Simulation.Simulator,\n graph: Lantern.Graph.Node): Types.Timing.Milli {\n const simulationBeforeChanges = simulator.simulate(graph);\n\n const originalTransferSizes = new Map<string, number>();\n graph.traverse(node => {\n if (node.type !== 'network') {\n return;\n }\n const wastedBytes = wastedBytesByRequestId.get(node.request.requestId);\n if (!wastedBytes) {\n return;\n }\n\n const original = node.request.transferSize;\n originalTransferSizes.set(node.request.requestId, original);\n\n node.request.transferSize = Math.max(original - wastedBytes, 0);\n });\n\n const simulationAfterChanges = simulator.simulate(graph);\n\n // Restore the original transfer size after we've done our simulation\n graph.traverse(node => {\n if (node.type !== 'network') {\n return;\n }\n const originalTransferSize = originalTransferSizes.get(node.request.requestId);\n if (originalTransferSize === undefined) {\n return;\n }\n node.request.transferSize = originalTransferSize;\n });\n\n let savings = simulationBeforeChanges.timeInMs - simulationAfterChanges.timeInMs;\n savings = Math.round(savings / GRAPH_SAVINGS_PRECISION) * GRAPH_SAVINGS_PRECISION;\n return Types.Timing.Milli(savings);\n}\n\n/**\n * Estimates the FCP & LCP savings for wasted bytes in `wastedBytesByRequestId`.\n */\nexport function metricSavingsForWastedBytes(\n wastedBytesByRequestId: Map<string, number>, context: InsightSetContext): MetricSavings|undefined {\n if (!context.navigation || !context.lantern) {\n return;\n }\n\n if (!wastedBytesByRequestId.size) {\n return {FCP: Types.Timing.Milli(0), LCP: Types.Timing.Milli(0)};\n }\n\n const simulator = context.lantern.simulator;\n const fcpGraph = context.lantern.metrics.firstContentfulPaint.optimisticGraph;\n const lcpGraph = context.lantern.metrics.largestContentfulPaint.optimisticGraph;\n\n return {\n FCP: estimateSavingsWithGraphs(wastedBytesByRequestId, simulator, fcpGraph),\n LCP: estimateSavingsWithGraphs(wastedBytesByRequestId, simulator, lcpGraph),\n };\n}\n\n/**\n * Returns whether the network request was sent encoded.\n */\nexport function isRequestCompressed(request: Types.Events.SyntheticNetworkRequest): boolean {\n // FYI: In Lighthouse, older devtools logs (like our test fixtures) seems to be\n // lower case, while modern logs are Cased-Like-This.\n const patterns = [\n /^content-encoding$/i, /^x-content-encoding-over-network$/i,\n /^x-original-content-encoding$/i, // Lightrider.\n ];\n const compressionTypes = ['gzip', 'br', 'deflate', 'zstd'];\n return request.args.data.responseHeaders.some(\n header => patterns.some(p => header.name.match(p)) && compressionTypes.includes(header.value));\n}\n\nfunction getRequestSizes(request: Types.Events.SyntheticNetworkRequest): {resourceSize: number, transferSize: number} {\n const resourceSize = request.args.data.decodedBodyLength;\n const transferSize = request.args.data.encodedDataLength;\n return {resourceSize, transferSize};\n}\n\n/**\n * Estimates the number of bytes the content of this network record would have consumed on the network based on the\n * uncompressed size (totalBytes). Uses the actual transfer size from the network record if applicable,\n * minus the size of the response headers.\n *\n * @param totalBytes Uncompressed size of the resource\n */\nexport function estimateCompressedContentSize(\n request: Types.Events.SyntheticNetworkRequest|undefined, totalBytes: number,\n resourceType: Protocol.Network.ResourceType): number {\n if (!request) {\n // We don't know how many bytes this asset used on the network, but we can guess it was\n // roughly the size of the content gzipped.\n // See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer for specific CSS/Script examples\n // See https://discuss.httparchive.org/t/file-size-and-compression-savings/145 for fallback multipliers\n switch (resourceType) {\n case 'Stylesheet':\n // Stylesheets tend to compress extremely well.\n return Math.round(totalBytes * 0.2);\n case 'Script':\n case 'Document':\n // Scripts and HTML compress fairly well too.\n return Math.round(totalBytes * 0.33);\n default:\n // Otherwise we'll just fallback to the average savings in HTTPArchive\n return Math.round(totalBytes * 0.5);\n }\n }\n\n // Get the size of the response body on the network.\n const {transferSize, resourceSize} = getRequestSizes(request);\n let contentTransferSize = transferSize;\n if (!isRequestCompressed(request)) {\n // This is not compressed, so we can use resourceSize directly.\n // This would be equivalent to transfer size minus headers transfer size, but transfer size\n // may also include bytes for SSL connection etc.\n contentTransferSize = resourceSize;\n }\n // TODO(cjamcl): Get \"responseHeadersTransferSize\" in Network handler.\n // else if (request.responseHeadersTransferSize) {\n // // Subtract the size of the encoded headers.\n // contentTransferSize =\n // Math.max(0, contentTransferSize - request.responseHeadersTransferSize);\n // }\n\n if (request.args.data.resourceType === resourceType) {\n // This was a regular standalone asset, just use the transfer size.\n return contentTransferSize;\n }\n\n // This was an asset that was inlined in a different resource type (e.g. HTML document).\n // Use the compression ratio of the resource to estimate the total transferred bytes.\n // Get the compression ratio, if it's an invalid number, assume no compression.\n const compressionRatio = Number.isFinite(resourceSize) && resourceSize > 0 ? (contentTransferSize / resourceSize) : 1;\n return Math.round(totalBytes * compressionRatio);\n}\n\n/**\n * Utility function to estimate the ratio of the compression of a script.\n * This excludes the size of the response headers.\n */\nexport function estimateCompressionRatioForScript(script: Handlers.ModelHandlers.Scripts.Script): number {\n if (!script.request) {\n // Can't find request, so just use 1.\n return 1;\n }\n\n const request = script.request;\n const contentLength = request.args.data.decodedBodyLength ?? script.content?.length ?? 0;\n const compressedSize = estimateCompressedContentSize(request, contentLength, Protocol.Network.ResourceType.Script);\n const compressionRatio = compressedSize / contentLength;\n return compressionRatio;\n}\n"]}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// import * as i18n from '../../../core/i18n/i18n.js';
|
|
5
5
|
import * as Helpers from '../helpers/helpers.js';
|
|
6
6
|
import * as Types from '../types/types.js';
|
|
7
|
+
import { isRequestCompressed } from './Common.js';
|
|
7
8
|
import { InsightCategory, InsightWarning, } from './types.js';
|
|
8
9
|
export const UIStrings = {
|
|
9
10
|
/**
|
|
@@ -71,14 +72,7 @@ function getServerResponseTime(request) {
|
|
|
71
72
|
return Math.round(ms);
|
|
72
73
|
}
|
|
73
74
|
function getCompressionSavings(request) {
|
|
74
|
-
|
|
75
|
-
// Older devtools logs are lower case, while modern logs are Cased-Like-This.
|
|
76
|
-
const patterns = [
|
|
77
|
-
/^content-encoding$/i,
|
|
78
|
-
/^x-content-encoding-over-network$/i,
|
|
79
|
-
];
|
|
80
|
-
const compressionTypes = ['gzip', 'br', 'deflate', 'zstd'];
|
|
81
|
-
const isCompressed = request.args.data.responseHeaders.some(header => patterns.some(p => header.name.match(p)) && compressionTypes.includes(header.value));
|
|
75
|
+
const isCompressed = isRequestCompressed(request);
|
|
82
76
|
if (isCompressed) {
|
|
83
77
|
return 0;
|
|
84
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DocumentLatency.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/DocumentLatency.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AAEnD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAEL,eAAe,EAIf,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,0BAA0B;IACjC;;OAEG;IACH,WAAW,EACP,8JAA8J;IAClK;;OAEG;IACH,gBAAgB,EAAE,kBAAkB;IACpC;;OAEG;IACH,eAAe,EAAE,eAAe;IAChC;;OAEG;IACH,yBAAyB,EAAE,yBAAyB;IACpD;;OAEG;IACH,wBAAwB,EAAE,yBAAyB;IACnD;;OAEG;IACH,sBAAsB,EAAE,0BAA0B;IAClD;;OAEG;IACH,qBAAqB,EAAE,wBAAwB;IAC/C;;OAEG;IACH,cAAc,EAAE,WAAW;IAC3B;;OAEG;IACH,uBAAuB,EAAE,sBAAsB;IAC/C;;OAEG;IACH,oBAAoB,EAAE,uBAAuB;CACrC,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,0CAA0C,EAAE,SAAS,CAAC,CAAC;AAChG,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB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CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,eAAe,CAAC;oBACnG,KAAK,EAAE,WAAW;iBACnB;gBACD,oBAAoB,EAAE;oBACpB,KAAK,EAAE,oBAAoB,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,yBAAyB,CAAC,CAAC,CAAC;wBACjD,UAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC;oBAC5E,KAAK,EAAE,oBAAoB;iBAC5B;gBACD,eAAe,EAAE;oBACf,KAAK,EAAE,eAAe,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC,CAAC;wBAC9C,UAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC;oBACpE,KAAK,EAAE,eAAe;iBACvB;aACF;SACF;QACD,aAAa;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["// 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 i18n from '../../../core/i18n/i18n.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {\n type Checklist,\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n *@description Title of an insight that provides a breakdown for how long it took to download the main document.\n */\n title: 'Document request latency',\n /**\n *@description Description of an insight that provides a breakdown for how long it took to download the main document.\n */\n description:\n 'Your first network request is the most important. Reduce its latency by avoiding redirects, ensuring a fast server response, and enabling text compression.',\n /**\n * @description Text to tell the user that the document request does not have redirects.\n */\n passingRedirects: 'Avoids redirects',\n /**\n * @description Text to tell the user that the document request had redirects.\n */\n failedRedirects: 'Had redirects',\n /**\n * @description Text to tell the user that the time starting the document request to when the server started responding is acceptable.\n */\n passingServerResponseTime: 'Server responds quickly',\n /**\n * @description Text to tell the user that the time starting the document request to when the server started responding is not acceptable.\n */\n failedServerResponseTime: 'Server responded slowly',\n /**\n * @description Text to tell the user that text compression (like gzip) was applied.\n */\n passingTextCompression: 'Applies text compression',\n /**\n * @description Text to tell the user that text compression (like gzip) was not applied.\n */\n failedTextCompression: 'No compression applied',\n /**\n * @description Text for a label describing a network request event as having redirects.\n */\n redirectsLabel: 'Redirects',\n /**\n * @description Text for a label describing a network request event as taking too long to start delivery by the server.\n */\n serverResponseTimeLabel: 'Server response time',\n /**\n * @description Text for a label describing a network request event as taking longer to download because it wasn't compressed.\n */\n uncompressedDownload: 'Uncompressed download',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/DocumentLatency.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n// Due to the way that DevTools throttling works we cannot see if server response took less than ~570ms.\n// We set our failure threshold to 600ms to avoid those false positives but we want devs to shoot for 100ms.\nconst TOO_SLOW_THRESHOLD_MS = 600;\nconst TARGET_MS = 100;\n\n// Threshold for compression savings.\nconst IGNORE_THRESHOLD_IN_BYTES = 1400;\n\nexport function isDocumentLatency(x: InsightModel): x is DocumentLatencyInsightModel {\n return x.insightKey === 'DocumentLatency';\n}\n\nexport type DocumentLatencyInsightModel = InsightModel<typeof UIStrings, {\n data?: {\n serverResponseTime: Types.Timing.Milli,\n redirectDuration: Types.Timing.Milli,\n uncompressedResponseBytes: number,\n checklist: Checklist<'noRedirects'|'serverResponseIsFast'|'usesCompression'>,\n documentRequest?: Types.Events.SyntheticNetworkRequest,\n },\n}>;\n\nfunction getServerResponseTime(request: Types.Events.SyntheticNetworkRequest): Types.Timing.Milli|null {\n const timing = request.args.data.timing;\n if (!timing) {\n return null;\n }\n\n const ms = Helpers.Timing.microToMilli(request.args.data.syntheticData.waiting);\n return Math.round(ms) as Types.Timing.Milli;\n}\n\nfunction getCompressionSavings(request: Types.Events.SyntheticNetworkRequest): number {\n // Check from headers if compression was already applied.\n // Older devtools logs are lower case, while modern logs are Cased-Like-This.\n const patterns = [\n /^content-encoding$/i,\n /^x-content-encoding-over-network$/i,\n ];\n const compressionTypes = ['gzip', 'br', 'deflate', 'zstd'];\n const isCompressed = request.args.data.responseHeaders.some(\n header => patterns.some(p => header.name.match(p)) && compressionTypes.includes(header.value));\n if (isCompressed) {\n return 0;\n }\n\n // We don't know how many bytes this asset used on the network, but we can guess it was\n // roughly the size of the content gzipped.\n // See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer for specific CSS/Script examples\n // See https://discuss.httparchive.org/t/file-size-and-compression-savings/145 for fallback multipliers\n // See https://letstalkaboutwebperf.com/en/gzip-brotli-server-config/ for MIME types to compress\n const originalSize = request.args.data.decodedBodyLength;\n let estimatedSavings = 0;\n switch (request.args.data.mimeType) {\n case 'text/css':\n // Stylesheets tend to compress extremely well.\n estimatedSavings = Math.round(originalSize * 0.8);\n break;\n case 'text/html':\n case 'text/javascript':\n // Scripts and HTML compress fairly well too.\n estimatedSavings = Math.round(originalSize * 0.67);\n break;\n case 'text/plain':\n case 'text/xml':\n case 'text/x-component':\n case 'application/javascript':\n case 'application/json':\n case 'application/manifest+json':\n case 'application/vnd.api+json':\n case 'application/xml':\n case 'application/xhtml+xml':\n case 'application/rss+xml':\n case 'application/atom+xml':\n case 'application/vnd.ms-fontobject':\n case 'application/x-font-ttf':\n case 'application/x-font-opentype':\n case 'application/x-font-truetype':\n case 'image/svg+xml':\n case 'image/x-icon':\n case 'image/vnd.microsoft.icon':\n case 'font/ttf':\n case 'font/eot':\n case 'font/otf':\n case 'font/opentype':\n // Use the average savings in HTTPArchive.\n estimatedSavings = Math.round(originalSize * 0.5);\n break;\n default: // Any other MIME types are likely already compressed.\n }\n // Check if the estimated savings are greater than the byte ignore threshold.\n // Note that the estimated gzip savings are always more than 10%, so there is\n // no percent threshold.\n return estimatedSavings < IGNORE_THRESHOLD_IN_BYTES ? 0 : estimatedSavings;\n}\n\nfunction finalize(partialModel: PartialInsightModel<DocumentLatencyInsightModel>): DocumentLatencyInsightModel {\n let hasFailure = false;\n if (partialModel.data) {\n hasFailure = !partialModel.data.checklist.usesCompression.value ||\n !partialModel.data.checklist.serverResponseIsFast.value || !partialModel.data.checklist.noRedirects.value;\n }\n\n return {\n insightKey: InsightKeys.DOCUMENT_LATENCY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: hasFailure ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): DocumentLatencyInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const documentRequest =\n parsedTrace.NetworkRequests.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!documentRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const serverResponseTime = getServerResponseTime(documentRequest);\n if (serverResponseTime === null) {\n throw new Error('missing document request timing');\n }\n\n const serverResponseTooSlow = serverResponseTime > TOO_SLOW_THRESHOLD_MS;\n\n let overallSavingsMs = 0;\n if (serverResponseTime > TOO_SLOW_THRESHOLD_MS) {\n overallSavingsMs = Math.max(serverResponseTime - TARGET_MS, 0);\n }\n\n const redirectDuration = Math.round(documentRequest.args.data.syntheticData.redirectionDuration / 1000);\n overallSavingsMs += redirectDuration;\n\n const metricSavings = {\n FCP: overallSavingsMs as Types.Timing.Milli,\n LCP: overallSavingsMs as Types.Timing.Milli,\n };\n\n const uncompressedResponseBytes = getCompressionSavings(documentRequest);\n\n const noRedirects = redirectDuration === 0;\n const serverResponseIsFast = !serverResponseTooSlow;\n const usesCompression = uncompressedResponseBytes === 0;\n\n return finalize({\n relatedEvents: [documentRequest],\n data: {\n serverResponseTime,\n redirectDuration: Types.Timing.Milli(redirectDuration),\n uncompressedResponseBytes,\n documentRequest,\n checklist: {\n noRedirects: {\n label: noRedirects ? i18nString(UIStrings.passingRedirects) : i18nString(UIStrings.failedRedirects),\n value: noRedirects\n },\n serverResponseIsFast: {\n label: serverResponseIsFast ? i18nString(UIStrings.passingServerResponseTime) :\n i18nString(UIStrings.failedServerResponseTime),\n value: serverResponseIsFast\n },\n usesCompression: {\n label: usesCompression ? i18nString(UIStrings.passingTextCompression) :\n i18nString(UIStrings.failedTextCompression),\n value: usesCompression\n },\n },\n },\n metricSavings,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DocumentLatency.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/DocumentLatency.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AAEnD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,mBAAmB,EAAC,MAAM,aAAa,CAAC;AAChD,OAAO,EAEL,eAAe,EAIf,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,0BAA0B;IACjC;;OAEG;IACH,WAAW,EACP,8JAA8J;IAClK;;OAEG;IACH,gBAAgB,EAAE,kBAAkB;IACpC;;OAEG;IACH,eAAe,EAAE,eAAe;IAChC;;OAEG;IACH,yBAAyB,EAAE,yBAAyB;IACpD;;OAEG;IACH,wBAAwB,EAAE,yBAAyB;IACnD;;OAEG;IACH,sBAAsB,EAAE,0BAA0B;IAClD;;OAEG;IACH,qBAAqB,EAAE,wBAAwB;IAC/C;;OAEG;IACH,cAAc,EAAE,WAAW;IAC3B;;OAEG;IACH,uBAAuB,EAAE,sBAAsB;IAC/C;;OAEG;IACH,oBAAoB,EAAE,uBAAuB;CACrC,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,0CAA0C,EAAE,SAAS,CAAC,CAAC;AAChG,MAAM,CAAC,MAAM,U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CAAC,sBAAsB,CAAC,CAAC,CAAC;wBAC9C,UAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC;oBACpE,KAAK,EAAE,eAAe;iBACvB;aACF;SACF;QACD,aAAa;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["// 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 i18n from '../../../core/i18n/i18n.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {isRequestCompressed} from './Common.js';\nimport {\n type Checklist,\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n *@description Title of an insight that provides a breakdown for how long it took to download the main document.\n */\n title: 'Document request latency',\n /**\n *@description Description of an insight that provides a breakdown for how long it took to download the main document.\n */\n description:\n 'Your first network request is the most important. Reduce its latency by avoiding redirects, ensuring a fast server response, and enabling text compression.',\n /**\n * @description Text to tell the user that the document request does not have redirects.\n */\n passingRedirects: 'Avoids redirects',\n /**\n * @description Text to tell the user that the document request had redirects.\n */\n failedRedirects: 'Had redirects',\n /**\n * @description Text to tell the user that the time starting the document request to when the server started responding is acceptable.\n */\n passingServerResponseTime: 'Server responds quickly',\n /**\n * @description Text to tell the user that the time starting the document request to when the server started responding is not acceptable.\n */\n failedServerResponseTime: 'Server responded slowly',\n /**\n * @description Text to tell the user that text compression (like gzip) was applied.\n */\n passingTextCompression: 'Applies text compression',\n /**\n * @description Text to tell the user that text compression (like gzip) was not applied.\n */\n failedTextCompression: 'No compression applied',\n /**\n * @description Text for a label describing a network request event as having redirects.\n */\n redirectsLabel: 'Redirects',\n /**\n * @description Text for a label describing a network request event as taking too long to start delivery by the server.\n */\n serverResponseTimeLabel: 'Server response time',\n /**\n * @description Text for a label describing a network request event as taking longer to download because it wasn't compressed.\n */\n uncompressedDownload: 'Uncompressed download',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/DocumentLatency.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n// Due to the way that DevTools throttling works we cannot see if server response took less than ~570ms.\n// We set our failure threshold to 600ms to avoid those false positives but we want devs to shoot for 100ms.\nconst TOO_SLOW_THRESHOLD_MS = 600;\nconst TARGET_MS = 100;\n\n// Threshold for compression savings.\nconst IGNORE_THRESHOLD_IN_BYTES = 1400;\n\nexport function isDocumentLatency(x: InsightModel): x is DocumentLatencyInsightModel {\n return x.insightKey === 'DocumentLatency';\n}\n\nexport type DocumentLatencyInsightModel = InsightModel<typeof UIStrings, {\n data?: {\n serverResponseTime: Types.Timing.Milli,\n redirectDuration: Types.Timing.Milli,\n uncompressedResponseBytes: number,\n checklist: Checklist<'noRedirects'|'serverResponseIsFast'|'usesCompression'>,\n documentRequest?: Types.Events.SyntheticNetworkRequest,\n },\n}>;\n\nfunction getServerResponseTime(request: Types.Events.SyntheticNetworkRequest): Types.Timing.Milli|null {\n const timing = request.args.data.timing;\n if (!timing) {\n return null;\n }\n\n const ms = Helpers.Timing.microToMilli(request.args.data.syntheticData.waiting);\n return Math.round(ms) as Types.Timing.Milli;\n}\n\nfunction getCompressionSavings(request: Types.Events.SyntheticNetworkRequest): number {\n const isCompressed = isRequestCompressed(request);\n if (isCompressed) {\n return 0;\n }\n\n // We don't know how many bytes this asset used on the network, but we can guess it was\n // roughly the size of the content gzipped.\n // See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer for specific CSS/Script examples\n // See https://discuss.httparchive.org/t/file-size-and-compression-savings/145 for fallback multipliers\n // See https://letstalkaboutwebperf.com/en/gzip-brotli-server-config/ for MIME types to compress\n const originalSize = request.args.data.decodedBodyLength;\n let estimatedSavings = 0;\n switch (request.args.data.mimeType) {\n case 'text/css':\n // Stylesheets tend to compress extremely well.\n estimatedSavings = Math.round(originalSize * 0.8);\n break;\n case 'text/html':\n case 'text/javascript':\n // Scripts and HTML compress fairly well too.\n estimatedSavings = Math.round(originalSize * 0.67);\n break;\n case 'text/plain':\n case 'text/xml':\n case 'text/x-component':\n case 'application/javascript':\n case 'application/json':\n case 'application/manifest+json':\n case 'application/vnd.api+json':\n case 'application/xml':\n case 'application/xhtml+xml':\n case 'application/rss+xml':\n case 'application/atom+xml':\n case 'application/vnd.ms-fontobject':\n case 'application/x-font-ttf':\n case 'application/x-font-opentype':\n case 'application/x-font-truetype':\n case 'image/svg+xml':\n case 'image/x-icon':\n case 'image/vnd.microsoft.icon':\n case 'font/ttf':\n case 'font/eot':\n case 'font/otf':\n case 'font/opentype':\n // Use the average savings in HTTPArchive.\n estimatedSavings = Math.round(originalSize * 0.5);\n break;\n default: // Any other MIME types are likely already compressed.\n }\n // Check if the estimated savings are greater than the byte ignore threshold.\n // Note that the estimated gzip savings are always more than 10%, so there is\n // no percent threshold.\n return estimatedSavings < IGNORE_THRESHOLD_IN_BYTES ? 0 : estimatedSavings;\n}\n\nfunction finalize(partialModel: PartialInsightModel<DocumentLatencyInsightModel>): DocumentLatencyInsightModel {\n let hasFailure = false;\n if (partialModel.data) {\n hasFailure = !partialModel.data.checklist.usesCompression.value ||\n !partialModel.data.checklist.serverResponseIsFast.value || !partialModel.data.checklist.noRedirects.value;\n }\n\n return {\n insightKey: InsightKeys.DOCUMENT_LATENCY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: hasFailure ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): DocumentLatencyInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const documentRequest =\n parsedTrace.NetworkRequests.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!documentRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const serverResponseTime = getServerResponseTime(documentRequest);\n if (serverResponseTime === null) {\n throw new Error('missing document request timing');\n }\n\n const serverResponseTooSlow = serverResponseTime > TOO_SLOW_THRESHOLD_MS;\n\n let overallSavingsMs = 0;\n if (serverResponseTime > TOO_SLOW_THRESHOLD_MS) {\n overallSavingsMs = Math.max(serverResponseTime - TARGET_MS, 0);\n }\n\n const redirectDuration = Math.round(documentRequest.args.data.syntheticData.redirectionDuration / 1000);\n overallSavingsMs += redirectDuration;\n\n const metricSavings = {\n FCP: overallSavingsMs as Types.Timing.Milli,\n LCP: overallSavingsMs as Types.Timing.Milli,\n };\n\n const uncompressedResponseBytes = getCompressionSavings(documentRequest);\n\n const noRedirects = redirectDuration === 0;\n const serverResponseIsFast = !serverResponseTooSlow;\n const usesCompression = uncompressedResponseBytes === 0;\n\n return finalize({\n relatedEvents: [documentRequest],\n data: {\n serverResponseTime,\n redirectDuration: Types.Timing.Milli(redirectDuration),\n uncompressedResponseBytes,\n documentRequest,\n checklist: {\n noRedirects: {\n label: noRedirects ? i18nString(UIStrings.passingRedirects) : i18nString(UIStrings.failedRedirects),\n value: noRedirects\n },\n serverResponseIsFast: {\n label: serverResponseIsFast ? i18nString(UIStrings.passingServerResponseTime) :\n i18nString(UIStrings.failedServerResponseTime),\n value: serverResponseIsFast\n },\n usesCompression: {\n label: usesCompression ? i18nString(UIStrings.passingTextCompression) :\n i18nString(UIStrings.failedTextCompression),\n value: usesCompression\n },\n },\n },\n metricSavings,\n });\n}\n"]}
|