Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core(tsc): make CPUNode and NetworkNode a discriminated union #5548

Merged
merged 5 commits into from
Jun 26, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@

const Audit = require('../audit');
const linearInterpolation = require('../../lib/statistics').linearInterpolation;
const Interactive = require('../../gather/computed/metrics/lantern-interactive'); // eslint-disable-line max-len
const Simulator = require('../../lib/dependency-graph/simulator/simulator'); // eslint-disable-line no-unused-vars
const Node = require('../../lib/dependency-graph/node.js'); // eslint-disable-line no-unused-vars
const Interactive = require('../../gather/computed/metrics/lantern-interactive');

const NetworkNode = require('../../lib/dependency-graph/network-node.js'); // eslint-disable-line no-unused-vars
/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */
/** @typedef {import('../../lib/dependency-graph/node.js').NodeType} NodeType */

const KB_IN_BYTES = 1024;

Expand Down Expand Up @@ -126,7 +125,7 @@ class UnusedBytes extends Audit {
* - (if includeLoad is true or not provided) end time of the last node in the graph
*
* @param {Array<LH.Audit.ByteEfficiencyItem>} results The array of byte savings results per resource
* @param {Node} graph
* @param {NodeType} graph
* @param {Simulator} simulator
* @param {{includeLoad?: boolean, label?: string}=} options
* @return {number}
Expand All @@ -148,26 +147,24 @@ class UnusedBytes extends Audit {
const originalTransferSizes = new Map();
graph.traverse(node => {
if (node.type !== 'network') return;
const networkNode = /** @type {NetworkNode} */ (node);
const result = resultsByUrl.get(networkNode.record.url);
const result = resultsByUrl.get(node.record.url);
if (!result) return;

const original = networkNode.record.transferSize;
originalTransferSizes.set(networkNode.record.requestId, original);
const original = node.record.transferSize;
originalTransferSizes.set(node.record.requestId, original);

const wastedBytes = result.wastedBytes;
networkNode.record.transferSize = Math.max(original - wastedBytes, 0);
node.record.transferSize = Math.max(original - wastedBytes, 0);
});

const simulationAfterChanges = simulator.simulate(graph, {label: afterLabel});

// Restore the original transfer size after we've done our simulation
graph.traverse(node => {
if (node.type !== 'network') return;
const networkNode = /** @type {NetworkNode} */ (node);
const originalTransferSize = originalTransferSizes.get(networkNode.record.requestId);
const originalTransferSize = originalTransferSizes.get(node.record.requestId);
if (originalTransferSize === undefined) return;
networkNode.record.transferSize = originalTransferSize;
node.record.transferSize = originalTransferSize;
});

const savingsOnOverallLoad = simulationBeforeChanges.timeInMs - simulationAfterChanges.timeInMs;
Expand All @@ -183,7 +180,7 @@ class UnusedBytes extends Audit {

/**
* @param {ByteEfficiencyProduct} result
* @param {Node} graph
* @param {NodeType} graph
* @param {Simulator} simulator
* @return {LH.Audit.Product}
*/
Expand Down
22 changes: 10 additions & 12 deletions lighthouse-core/audits/byte-efficiency/render-blocking-resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ const ByteEfficiencyAudit = require('./byte-efficiency-audit');
const UnusedCSS = require('./unused-css-rules');
const WebInspector = require('../../lib/web-inspector');

const Simulator = require('../../lib/dependency-graph/simulator/simulator'); // eslint-disable-line no-unused-vars
const NetworkNode = require('../../lib/dependency-graph/network-node.js'); // eslint-disable-line no-unused-vars
/** @typedef {import('../../lib/dependency-graph/simulator/simulator')} Simulator */
/** @typedef {import('../../lib/dependency-graph/node.js').NodeType} NodeType */
/** @typedef {import('../../lib/dependency-graph/network-node.js')} NetworkNode */

// Because of the way we detect blocking stylesheets, asynchronously loaded
// CSS with link[rel=preload] and an onload handler (see https://github.com/filamentgroup/loadCSS)
Expand All @@ -27,19 +28,18 @@ const MINIMUM_WASTED_MS = 50;
/**
* Given a simulation's nodeTimings, return an object with the nodes/timing keyed by network URL
* @param {LH.Gatherer.Simulation.Result['nodeTimings']} nodeTimings
* @return {Object<string, {node: Node, nodeTiming: LH.Gatherer.Simulation.NodeTiming}>}
* @return {Object<string, {node: NodeType, nodeTiming: LH.Gatherer.Simulation.NodeTiming}>}
*/
function getNodesAndTimingByUrl(nodeTimings) {
/** @type {Object<string, {node: Node, nodeTiming: LH.Gatherer.Simulation.NodeTiming}>} */
/** @type {Object<string, {node: NodeType, nodeTiming: LH.Gatherer.Simulation.NodeTiming}>} */
const urlMap = {};
const nodes = Array.from(nodeTimings.keys());
nodes.forEach(node => {
if (node.type !== 'network') return;
const networkNode = /** @type {NetworkNode} */ (node);
const nodeTiming = nodeTimings.get(node);
if (!nodeTiming) return;

urlMap[networkNode.record.url] = {node, nodeTiming};
urlMap[node.record.url] = {node, nodeTiming};
});

return urlMap;
Expand Down Expand Up @@ -137,7 +137,7 @@ class RenderBlockingResources extends Audit {
* thing.
*
* @param {Simulator} simulator
* @param {Node} fcpGraph
* @param {NodeType} fcpGraph
* @param {Set<string>} deferredIds
* @param {Map<string, number>} wastedCssBytesByUrl
* @return {number}
Expand All @@ -151,14 +151,12 @@ class RenderBlockingResources extends Audit {
const canDeferRequest = deferredIds.has(node.id);
if (node.type !== Node.TYPES.NETWORK) return !canDeferRequest;

const networkNode = /** @type {NetworkNode} */ (node);

const isStylesheet =
networkNode.record._resourceType === WebInspector.resourceTypes.Stylesheet;
node.record._resourceType === WebInspector.resourceTypes.Stylesheet;
if (canDeferRequest && isStylesheet) {
// We'll inline the used bytes of the stylesheet and assume the rest can be deferred
const wastedBytes = wastedCssBytesByUrl.get(networkNode.record.url) || 0;
totalChildNetworkBytes += (networkNode.record.transferSize || 0) - wastedBytes;
const wastedBytes = wastedCssBytesByUrl.get(node.record.url) || 0;
totalChildNetworkBytes += (node.record.transferSize || 0) - wastedBytes;
}
return !canDeferRequest;
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const LanternMetricArtifact = require('./lantern-metric');
const Node = require('../../../lib/dependency-graph/node');
const EstimatedInputLatency = require('./estimated-input-latency');

/** @typedef {Node.NodeType} NodeType */

class LanternEstimatedInputLatency extends LanternMetricArtifact {
get name() {
return 'LanternEstimatedInputLatency';
Expand All @@ -26,16 +28,16 @@ class LanternEstimatedInputLatency extends LanternMetricArtifact {
}

/**
* @param {Node} dependencyGraph
* @return {Node}
* @param {NodeType} dependencyGraph
* @return {NodeType}
*/
getOptimisticGraph(dependencyGraph) {
return dependencyGraph;
}

/**
* @param {Node} dependencyGraph
* @return {Node}
* @param {NodeType} dependencyGraph
* @return {NodeType}
*/
getPessimisticGraph(dependencyGraph) {
return dependencyGraph;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

const MetricArtifact = require('./lantern-metric');
const Node = require('../../../lib/dependency-graph/node');
const CPUNode = require('../../../lib/dependency-graph/cpu-node'); // eslint-disable-line no-unused-vars
const NetworkNode = require('../../../lib/dependency-graph/network-node'); // eslint-disable-line no-unused-vars

/** @typedef {Node.NodeType} NodeType */
Copy link
Collaborator

Choose a reason for hiding this comment

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

is this a necessary thing, or just prefer it over Node.NodeType everywhere?

Copy link
Member Author

Choose a reason for hiding this comment

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

I guess I prefer it over Node.NodeType, but honestly it had become rote c/p by this file so I didn't really think of that possibility when both are needed in a file :)


class FirstContentfulPaint extends MetricArtifact {
get name() {
Expand All @@ -27,9 +27,9 @@ class FirstContentfulPaint extends MetricArtifact {
}

/**
* @param {Node} dependencyGraph
* @param {NodeType} dependencyGraph
* @param {LH.Artifacts.TraceOfTab} traceOfTab
* @return {Node}
* @return {NodeType}
*/
getOptimisticGraph(dependencyGraph, traceOfTab) {
const fcp = traceOfTab.timestamps.firstContentfulPaint;
Expand All @@ -43,19 +43,18 @@ class FirstContentfulPaint extends MetricArtifact {
if (node.endTime > fcp && !node.isMainDocument()) return false;
// Include EvaluateScript tasks for blocking scripts
if (node.type === Node.TYPES.CPU) {
return /** @type {CPUNode} */ (node).isEvaluateScriptFor(blockingScriptUrls);
return node.isEvaluateScriptFor(blockingScriptUrls);
}

const asNetworkNode = /** @type {NetworkNode} */ (node);
// Include non-script-initiated network requests with a render-blocking priority
return asNetworkNode.hasRenderBlockingPriority() && asNetworkNode.initiatorType !== 'script';
return node.hasRenderBlockingPriority() && node.initiatorType !== 'script';
});
}

/**
* @param {Node} dependencyGraph
* @param {NodeType} dependencyGraph
* @param {LH.Artifacts.TraceOfTab} traceOfTab
* @return {Node}
* @return {NodeType}
*/
getPessimisticGraph(dependencyGraph, traceOfTab) {
const fcp = traceOfTab.timestamps.firstContentfulPaint;
Expand All @@ -67,11 +66,11 @@ class FirstContentfulPaint extends MetricArtifact {
if (node.endTime > fcp && !node.isMainDocument()) return false;
// Include EvaluateScript tasks for blocking scripts
if (node.type === Node.TYPES.CPU) {
return /** @type {CPUNode} */ (node).isEvaluateScriptFor(blockingScriptUrls);
return node.isEvaluateScriptFor(blockingScriptUrls);
}

// Include non-script-initiated network requests with a render-blocking priority
return /** @type {NetworkNode} */ (node).hasRenderBlockingPriority();
return node.hasRenderBlockingPriority();
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
'use strict';

const Node = require('../../../lib/dependency-graph/node');
const CPUNode = require('../../../lib/dependency-graph/cpu-node'); // eslint-disable-line no-unused-vars
const NetworkNode = require('../../../lib/dependency-graph/network-node'); // eslint-disable-line no-unused-vars

const FirstCPUIdle = require('./first-cpu-idle');
const LanternInteractive = require('./lantern-interactive');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

const MetricArtifact = require('./lantern-metric');
const Node = require('../../../lib/dependency-graph/node');
const CPUNode = require('../../../lib/dependency-graph/cpu-node'); // eslint-disable-line no-unused-vars
const NetworkNode = require('../../../lib/dependency-graph/network-node'); // eslint-disable-line no-unused-vars

/** @typedef {Node.NodeType} NodeType */

class FirstMeaningfulPaint extends MetricArtifact {
get name() {
Expand All @@ -27,9 +27,9 @@ class FirstMeaningfulPaint extends MetricArtifact {
}

/**
* @param {Node} dependencyGraph
* @param {NodeType} dependencyGraph
* @param {LH.Artifacts.TraceOfTab} traceOfTab
* @return {Node}
* @return {NodeType}
*/
getOptimisticGraph(dependencyGraph, traceOfTab) {
const fmp = traceOfTab.timestamps.firstMeaningfulPaint;
Expand All @@ -43,19 +43,18 @@ class FirstMeaningfulPaint extends MetricArtifact {
if (node.endTime > fmp && !node.isMainDocument()) return false;
// Include EvaluateScript tasks for blocking scripts
if (node.type === Node.TYPES.CPU) {
return /** @type {CPUNode} */ (node).isEvaluateScriptFor(blockingScriptUrls);
return node.isEvaluateScriptFor(blockingScriptUrls);
}

const asNetworkNode = /** @type {NetworkNode} */ (node);
// Include non-script-initiated network requests with a render-blocking priority
return asNetworkNode.hasRenderBlockingPriority() && asNetworkNode.initiatorType !== 'script';
return node.hasRenderBlockingPriority() && node.initiatorType !== 'script';
});
}

/**
* @param {Node} dependencyGraph
* @param {NodeType} dependencyGraph
* @param {LH.Artifacts.TraceOfTab} traceOfTab
* @return {Node}
* @return {NodeType}
*/
getPessimisticGraph(dependencyGraph, traceOfTab) {
const fmp = traceOfTab.timestamps.firstMeaningfulPaint;
Expand All @@ -68,12 +67,11 @@ class FirstMeaningfulPaint extends MetricArtifact {

// Include CPU tasks that performed a layout or were evaluations of required scripts
if (node.type === Node.TYPES.CPU) {
const asCpuNode = /** @type {CPUNode} */ (node);
return asCpuNode.didPerformLayout() || asCpuNode.isEvaluateScriptFor(requiredScriptUrls);
return node.didPerformLayout() || node.isEvaluateScriptFor(requiredScriptUrls);
}

// Include all network requests that had render-blocking priority (even script-initiated)
return /** @type {NetworkNode} */ (node).hasRenderBlockingPriority();
return node.hasRenderBlockingPriority();
});
}

Expand Down
23 changes: 11 additions & 12 deletions lighthouse-core/gather/computed/metrics/lantern-interactive.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@

const MetricArtifact = require('./lantern-metric');
const Node = require('../../../lib/dependency-graph/node');
const CPUNode = require('../../../lib/dependency-graph/cpu-node'); // eslint-disable-line no-unused-vars
const NetworkNode = require('../../../lib/dependency-graph/network-node'); // eslint-disable-line no-unused-vars
const WebInspector = require('../../../lib/web-inspector');

/** @typedef {Node.NodeType} NodeType */

// Any CPU task of 20 ms or more will end up being a critical long task on mobile
const CRITICAL_LONG_TASK_THRESHOLD = 20;

Expand All @@ -31,8 +31,8 @@ class Interactive extends MetricArtifact {
}

/**
* @param {Node} dependencyGraph
* @return {Node}
* @param {NodeType} dependencyGraph
* @return {NodeType}
*/
getOptimisticGraph(dependencyGraph) {
// Adjust the critical long task threshold for microseconds
Expand All @@ -41,25 +41,24 @@ class Interactive extends MetricArtifact {
return dependencyGraph.cloneWithRelationships(node => {
// Include everything that might be a long task
if (node.type === Node.TYPES.CPU) {
return /** @type {CPUNode} */ (node).event.dur > minimumCpuTaskDuration;
return node.event.dur > minimumCpuTaskDuration;
}

const asNetworkNode = /** @type {NetworkNode} */ (node);
// Include all scripts and high priority requests, exclude all images
const isImage = asNetworkNode.record._resourceType === WebInspector.resourceTypes.Image;
const isScript = asNetworkNode.record._resourceType === WebInspector.resourceTypes.Script;
const isImage = node.record._resourceType === WebInspector.resourceTypes.Image;
const isScript = node.record._resourceType === WebInspector.resourceTypes.Script;
return (
!isImage &&
(isScript ||
asNetworkNode.record.priority() === 'High' ||
asNetworkNode.record.priority() === 'VeryHigh')
node.record.priority() === 'High' ||
node.record.priority() === 'VeryHigh')
);
});
}

/**
* @param {Node} dependencyGraph
* @return {Node}
* @param {NodeType} dependencyGraph
* @return {NodeType}
*/
getPessimisticGraph(dependencyGraph) {
return dependencyGraph;
Expand Down
Loading