Title: [204976] trunk
Revision
204976
Author
achristen...@apple.com
Date
2016-08-25 11:22:25 -0700 (Thu, 25 Aug 2016)

Log Message

Update the Resource Timing implementation
https://bugs.webkit.org/show_bug.cgi?id=161068

Patch by Johan K. Jensen <johan_jen...@apple.com> on 2016-08-25
Reviewed by Alex Christensen.

LayoutTests/imported/w3c:

Added W3C Web Platform Tests for Resource Timing.

* web-platform-tests/resource-timing/OWNERS: Added.
* web-platform-tests/resource-timing/SyntheticResponse.py: Added.
(main):
* web-platform-tests/resource-timing/iframe-setdomain.sub.html: Added.
* web-platform-tests/resource-timing/resource-timing.html: Added.
* web-platform-tests/resource-timing/resource-timing.js: Added.
(testCases.test):
(test):
(runNextCase):
(assertInvariants):
(assertResourceEntryInvariants):
(canonicalize):
(createUniqueQueryArgument):
(getSyntheticUrl):
(initiateFetch):
(window.onload):
* web-platform-tests/resource-timing/resources/resource_timing_test0.css: Added.
(div#resource_link_css):
* web-platform-tests/resource-timing/resources/resource_timing_test0.html: Added.
* web-platform-tests/resource-timing/resources/resource_timing_test0.js: Added.
* web-platform-tests/resource-timing/resources/resource_timing_test0.png: Added.
* web-platform-tests/resource-timing/resources/resource_timing_test0.xml: Added.
* web-platform-tests/resource-timing/resources/webperftestharness.js: Added.
(wp_test):
(test_namespace):
(test_timing_order):
(test_timing_equals):
(sleep_milliseconds):
(test_true):
(test_equals):
(test_greater_than):
(test_greater_or_equals):
* web-platform-tests/resource-timing/test_resource_timing.html: Added.
* web-platform-tests/resource-timing/test_resource_timing.js: Added.
(setup):
(resolve):
(switch.):
(switch.case.string_appeared_here.xmlhttp.onload):
(switch.default.element.onload):
(onload):
(poll_for_stylesheet_load.inner):
(poll_for_stylesheet_load):
(resource_load):

Source/WebCore:

Tests: imported/w3c/web-platform-tests/resource-timing/resource-timing.html
       imported/w3c/web-platform-tests/resource-timing/test_resource_timing.html

Update the Resource Timing implementation for better compatibility with the Resource Timing API spec.
Use LoadTiming for general timing information about a resources load timeline.
Mark timestamps for newly loaded resources as well as cached resources.

* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::startLoadingMainResource):
StartTime and fetchStart should be equal initially.

* loader/LoadTiming.cpp:
(WebCore::LoadTiming::LoadTiming): Moved member initialization out. Removed constructor.
* loader/LoadTiming.h:
(WebCore::LoadTiming::markStartTimeAndFetchStart):
Mark startTime and fetchStart simultaneously.

* loader/ResourceLoader.cpp:
(WebCore::ResourceLoader::init):
Mark the start time of resources.

* loader/ResourceLoader.h:
(WebCore::ResourceLoader::loadTiming):
Add LoadTiming info to handle a resources load timing.

* loader/ResourceTimingInformation.cpp:
(WebCore::ResourceTimingInformation::addResourceTiming):
* loader/ResourceTimingInformation.h:
Only pass in the URL from the ResourceRequest.
Pass LoadTiming instead of timestamps.

* loader/SubresourceLoader.cpp:
(WebCore::SubresourceLoader::willSendRequestInternal):
Mark redirects.

(WebCore::SubresourceLoader::didFinishLoading):
Mark the responseEnd timestamp.
Add the ResourceEntry to the timeline before notifyDone is called.

* loader/cache/CachedResourceLoader.cpp:
(WebCore::CachedResourceLoader::requestResource):
(WebCore::CachedResourceLoader::revalidateResource):
(WebCore::CachedResourceLoader::loadDone):
Mark timestamps for cached resources and use them instead of a cached LoadTiming.

* loader/cache/CachedResourceLoader.h:
(WebCore::CachedResourceLoader::resourceTimingInformation):
Add ResourceTimingInformation getter so SubresourceLoader.cpp can add entries before callbacks.

* page/Performance.cpp:
(WebCore::Performance::addResourceTiming):
* page/Performance.h:
Update signature: URLs and LoadTiming instead of timestamps.

* page/PerformanceResourceTiming.cpp:
(WebCore::PerformanceResourceTiming::PerformanceResourceTiming):
(WebCore::PerformanceResourceTiming::redirectStart):
(WebCore::PerformanceResourceTiming::redirectEnd):
(WebCore::PerformanceResourceTiming::fetchStart):
(WebCore::PerformanceResourceTiming::domainLookupStart):
(WebCore::PerformanceResourceTiming::domainLookupEnd):
(WebCore::PerformanceResourceTiming::connectStart):
(WebCore::PerformanceResourceTiming::connectEnd):
(WebCore::PerformanceResourceTiming::requestStart):
(WebCore::PerformanceResourceTiming::responseStart):
(WebCore::PerformanceResourceTiming::responseEnd):
(WebCore::PerformanceResourceTiming::resourceTimeToDocumentMilliseconds):
* page/PerformanceResourceTiming.h:
Update signatures and properties to use LoadTiming.
Use LoadTiming’s redirectStart/End, fetchStart, responseStart/End.
Make sure dns and connection timestamps are in increasing order, even when cached.

* page/PerformanceResourceTiming.idl:
Add responseStart.

LayoutTests:

* TestExpectations:
Skip resource outside of resource-folder.
Mark one test as flaky (see bug 161088).

* resources/testharnessreport.js:
(self.testRunner.add_completion_callback):
Updated completion callback to wait for any other completion callbacks
before finishing, so the Resource Timing tests can cleanup first.
Enabled the ResourceTiming runtime flag.

Modified Paths

Added Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (204975 => 204976)


--- trunk/LayoutTests/ChangeLog	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/LayoutTests/ChangeLog	2016-08-25 18:22:25 UTC (rev 204976)
@@ -1,3 +1,20 @@
+2016-08-25  Johan K. Jensen  <johan_jen...@apple.com>
+
+        Update the Resource Timing implementation
+        https://bugs.webkit.org/show_bug.cgi?id=161068
+
+        Reviewed by Alex Christensen.
+
+        * TestExpectations:
+        Skip resource outside of resource-folder.
+        Mark one test as flaky (see bug 161088).
+
+        * resources/testharnessreport.js:
+        (self.testRunner.add_completion_callback):
+        Updated completion callback to wait for any other completion callbacks
+        before finishing, so the Resource Timing tests can cleanup first.
+        Enabled the ResourceTiming runtime flag.
+
 2016-08-25  Jiewen Tan  <jiewen_...@apple.com>
 
         Unreviewed, rebase iOS simulator WK1 fast/multicol tests

Modified: trunk/LayoutTests/TestExpectations (204975 => 204976)


--- trunk/LayoutTests/TestExpectations	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/LayoutTests/TestExpectations	2016-08-25 18:22:25 UTC (rev 204976)
@@ -449,6 +449,7 @@
 imported/w3c/web-platform-tests/html/semantics/grouping-content/the-ol-element/reversed-1c.html [ Skip ]
 imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/script-not-executed-after-shutdown-child.html [ Skip ]
 imported/w3c/web-platform-tests/html/semantics/selectors/pseudo-classes/focus-iframe.html [ Skip ]
+imported/w3c/web-platform-tests/resource-timing/iframe-setdomain.sub.html [ Skip ]
 
 imported/w3c/web-platform-tests/service-workers [ Skip ]
 
@@ -1242,3 +1243,5 @@
 webkit.org/b/159755 fast/text/emoji-gender.html [ ImageOnlyFailure ]
 
 webkit.org/b/160017 js/regress-139548.html [ Slow ]
+
+webkit.org/b/161088 imported/w3c/web-platform-tests/resource-timing/resource-timing.html [ Pass Failure ]

Modified: trunk/LayoutTests/imported/w3c/ChangeLog (204975 => 204976)


--- trunk/LayoutTests/imported/w3c/ChangeLog	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/LayoutTests/imported/w3c/ChangeLog	2016-08-25 18:22:25 UTC (rev 204976)
@@ -1,3 +1,56 @@
+2016-08-25  Johan K. Jensen  <johan_jen...@apple.com>
+
+        Update the Resource Timing implementation
+        https://bugs.webkit.org/show_bug.cgi?id=161068
+
+        Reviewed by Alex Christensen.
+
+        Added W3C Web Platform Tests for Resource Timing.
+
+        * web-platform-tests/resource-timing/OWNERS: Added.
+        * web-platform-tests/resource-timing/SyntheticResponse.py: Added.
+        (main):
+        * web-platform-tests/resource-timing/iframe-setdomain.sub.html: Added.
+        * web-platform-tests/resource-timing/resource-timing.html: Added.
+        * web-platform-tests/resource-timing/resource-timing.js: Added.
+        (testCases.test):
+        (test):
+        (runNextCase):
+        (assertInvariants):
+        (assertResourceEntryInvariants):
+        (canonicalize):
+        (createUniqueQueryArgument):
+        (getSyntheticUrl):
+        (initiateFetch):
+        (window.onload):
+        * web-platform-tests/resource-timing/resources/resource_timing_test0.css: Added.
+        (div#resource_link_css):
+        * web-platform-tests/resource-timing/resources/resource_timing_test0.html: Added.
+        * web-platform-tests/resource-timing/resources/resource_timing_test0.js: Added.
+        * web-platform-tests/resource-timing/resources/resource_timing_test0.png: Added.
+        * web-platform-tests/resource-timing/resources/resource_timing_test0.xml: Added.
+        * web-platform-tests/resource-timing/resources/webperftestharness.js: Added.
+        (wp_test):
+        (test_namespace):
+        (test_timing_order):
+        (test_timing_equals):
+        (sleep_milliseconds):
+        (test_true):
+        (test_equals):
+        (test_greater_than):
+        (test_greater_or_equals):
+        * web-platform-tests/resource-timing/test_resource_timing.html: Added.
+        * web-platform-tests/resource-timing/test_resource_timing.js: Added.
+        (setup):
+        (resolve):
+        (switch.):
+        (switch.case.string_appeared_here.xmlhttp.onload):
+        (switch.default.element.onload):
+        (onload):
+        (poll_for_stylesheet_load.inner):
+        (poll_for_stylesheet_load):
+        (resource_load):
+
 2016-08-24  Alex Christensen  <achristen...@webkit.org>
 
         Import w3c URL tests

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/OWNERS (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/OWNERS	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/OWNERS	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,6 @@
+@haoxli
+@plehegar
+@zqzhang
+@igrigorik
+@toddreifsteck
+@yoavweiss

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/SyntheticResponse.py (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/SyntheticResponse.py	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/SyntheticResponse.py	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,25 @@
+import urllib
+import time
+
+def main(request, response):
+    index = request.request_path.index("?")
+    args = request.request_path[index+1:].split("&")
+    headersSent = 0
+    for arg in args:
+        if arg.startswith("ignored"):
+            continue
+        elif arg.endswith("ms"):
+            time.sleep(float(arg[0:-2]) / 1E3);
+        elif arg.startswith("redirect:"):
+            return (302, "WEBPERF MARKETING"), [("Location", urllib.unquote(arg[9:]))], "TEST"
+        elif arg.startswith("mime:"):
+            response.headers.set("Content-Type", urllib.unquote(arg[5:]))
+        elif arg.startswith("send:"):
+            text = urllib.unquote(arg[5:])
+            if headersSent == 0:
+                response.write_status_headers()
+                headersSent = 1
+
+            response.writer.write(text)
+#        else:
+#            error "  INVALID ARGUMENT %s" % arg

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/iframe-setdomain.sub.html (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/iframe-setdomain.sub.html	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/iframe-setdomain.sub.html	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>domain: {{domains[www]}}</title>
+</head>
+<body>
+  <script>
+    // The purpose of this IFrame is to change the 'document.domain'
+    document.domain = "{{domains[www]}}";
+  </script>
+  The resource-timings.html test loads this document into an IFrame to vet that setting
+  'document.domain' does not effect the timing allowed.
+</body>
+</html>

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing-expected.txt (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing-expected.txt	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing-expected.txt	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,21 @@
+CONSOLE MESSAGE: line 9: SecurityError (DOM Exception 18): The operation is insecure.
+
+PASS No timeline entry for about:blank
+PASS Setting 'document.domain' does not effect same-origin checks
+PASS 'iframe (Populate cache): The initial request populates the cache (if appropriate).
+PASS 'iframe (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).
+PASS 'xmlhttprequest (Populate cache): The initial request populates the cache (if appropriate).
+PASS 'xmlhttprequest (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).
+PASS 'script (Populate cache): The initial request populates the cache (if appropriate).
+PASS 'script (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).
+PASS 'link (Populate cache): The initial request populates the cache (if appropriate).
+PASS 'link (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).
+PASS 'iframe: 1 second delay before 'responseStart', another 1 second delay before 'responseEnd'.
+PASS 'xmlhttprequest: 1 second delay before 'responseStart', another 1 second delay before 'responseEnd'.
+PASS 'script: 1 second delay before 'responseStart', another 1 second delay before 'responseEnd'.
+PASS 'link: 1 second delay before 'responseStart', another 1 second delay before 'responseEnd'.
+PASS 'iframe (Redirected): 1 second delay before 'redirectEnd', another 1 second delay before 'responseStart'.
+PASS 'xmlhttprequest (Redirected): 1 second delay before 'redirectEnd', another 1 second delay before 'responseStart'.
+PASS 'script (Redirected): 1 second delay before 'redirectEnd', another 1 second delay before 'responseStart'.
+PASS 'link (Redirected): 1 second delay before 'redirectEnd', another 1 second delay before 'responseStart'.
+Show details

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.html (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.html	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.html	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Resource-Timing Level 1</title>
+  <!-- To aid debugability, explicitly link the testharness's CSS to avoid demand
+       loading it while the test executes. -->
+  <script src=""
+  <script src=""
+
+  <link rel="author" title="Microsoft" href=""
+  <link rel="help" href=""
+</head>
+<body>
+  <div id="log"></div>
+  <pre id="output"></pre>
+  <script src=""
+</body>
+</html>

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.js (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.js	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resource-timing.js	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,465 @@
+"use strict";
+
+window._onload_ =
+    function () {
+        setup({ explicit_timeout: true });
+
+        /** Number of milliseconds to delay when the server injects pauses into the response.
+
+            This should be large enough that we can distinguish it from noise with high confidence,
+            but small enough that tests complete quickly. */
+        var serverStepDelay = 250;
+
+        var mimeHtml    = "text/html";
+        var mimeText    = "text/plain";
+        var mimePng     = "image/png";
+        var mimeScript  = "application/_javascript_";
+        var mimeCss     = "text/css";
+
+        /** Hex encoding of a a 150x50px green PNG. */
+        var greenPng = "0x89504E470D0A1A0A0000000D494844520000006400000032010300000090FBECFD00000003504C544500FF00345EC0A80000000F49444154281563601805A36068020002BC00011BDDE3900000000049454E44AE426082";
+
+        /** Array containing test cases to run.  Initially, it contains the one-off 'about:blank" test,
+            but additional cases are pushed below by expanding templates. */
+        var testCases = [
+            {
+                description: "No timeline entry for about:blank",
+                test:
+                    function (test) {
+                        // Insert an empty IFrame.
+                        var frame = document.createElement("iframe");
+
+                        // Wait for the IFrame to load and ensure there is no resource entry for it on the timeline.
+                        //
+                        // We use the 'createOnloadCallbackFn()' helper which is normally invoked by 'initiateFetch()'
+                        // to avoid setting the IFrame's src.  It registers a test step for us, finds our entry on the
+                        // resource timeline, and wraps our callback function to automatically vet invariants.
+                        frame._onload_ = createOnloadCallbackFn(test, frame, "about:blank",
+                            function (initiator, entry) {
+                                assert_equals(entry, undefined, "Inserting an IFrame with a src of 'about:blank' must not add an entry to the timeline.");
+                                assertInvariants(
+                                    test,
+                                    function () {
+                                        test.done();
+                                    });
+                            });
+
+                        document.body.appendChild(frame);
+
+                        // Paranoid check that the new IFrame has loaded about:blank.
+                        assert_equals(
+                            frame.contentWindow.location.href,
+                            "about:blank",
+                            "'Src' of new <iframe> must be 'about:blank'.");
+                    }
+            },
+            {
+                description: "Setting 'document.domain' does not effect same-origin checks",
+                test:
+                    function (test) {
+                        initiateFetch(
+                            test,
+                            "iframe",
+                            canonicalize("iframe-setdomain.sub.html"),
+                            function (initiator, entry) {
+                                // Ensure that the script inside the IFrame has successfully changed the IFrame's domain.
+                                assert_throws(
+                                    null,
+                                    function () {
+                                        assert_not_equals(frame.contentWindow.document, null);
+                                    },
+                                    "Test Error: IFrame is not recognized as cross-domain.");
+
+                                // To verify that setting 'document.domain' did not change the results of the timing allow check,
+                                // verify that the following non-zero properties return their value.
+                                ["domainLookupStart", "domainLookupEnd", "connectStart", "connectEnd"]
+                                    .forEach(function(property) {
+                                        assert_greater_than(entry.connectEnd, 0,
+                                            "Property should be non-zero because timing allow check ignores 'document.domain'.");
+                                    });
+                                test.done();
+                            });
+                    }
+            }
+        ];
+
+        // Create cached/uncached tests from the following array of templates.  For each template entry,
+        // we add two identical test cases to 'testCases'.  The first case initiates a fetch to populate the
+        // cache.  The second request initiates a fetch with the same URL to cover the case where we hit
+        // the cache (if the caching policy permits caching).
+        [
+            { initiator: "iframe",         response: "(done)",      mime: mimeHtml },
+            { initiator: "xmlhttprequest", response: "(done)",      mime: mimeText },
+            // Multiple browsers seem to cheat a bit and race onLoad of images.  Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187
+            // { initiator: "img",            response: greenPng,      mime: mimePng },
+            { initiator: "script",         response: '"";',         mime: mimeScript },
+            { initiator: "link",           response: ".unused{}",   mime: mimeCss },
+        ]
+        .forEach(function (template) {
+            testCases.push({
+                description: "'" + template.initiator + " (Populate cache): The initial request populates the cache (if appropriate).",
+                test: function (test) {
+                    initiateFetch(
+                        test,
+                        template.initiator,
+                        getSyntheticUrl(
+                            "mime:" + encodeURIComponent(template.mime)
+                                + "&send:" + encodeURIComponent(template.response),
+                            /* allowCaching = */ true),
+                        function (initiator, entry) {
+                            test.done();
+                        });
+                    }
+                });
+
+            testCases.push({
+                description: "'" + template.initiator + " (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).",
+                test: function (test) {
+                    initiateFetch(
+                        test,
+                        template.initiator,
+                        getSyntheticUrl(
+                            "mime:" + encodeURIComponent(template.mime)
+                                + "&send:" + encodeURIComponent(template.response),
+                            /* allowCaching = */ true),
+                        function (initiator, entry) {
+                            test.done();
+                        });
+                    }
+                });
+            });
+
+        // Create responseStart/responseEnd tests from the following array of templates.  In this test, the server delays before
+        // responding with responsePart1, then delays again before completing with responsePart2.  The test looks for the expected
+        // pauses before responeStart and responseEnd.
+        [
+            { initiator: "iframe",         responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)",                                                      mime: mimeHtml },
+            { initiator: "xmlhttprequest", responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)",                                                      mime: mimeText },
+            // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd.  Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187
+            // { initiator: "img",            responsePart1: greenPng.substring(0, greenPng.length / 2), responsePart2: "0x" + greenPng.substring(greenPng.length / 2, greenPng.length),       mime: mimePng },
+            { initiator: "script",         responsePart1: '"', responsePart2: '";',                                                                                                         mime: mimeScript },
+            { initiator: "link",           responsePart1: ".unused{", responsePart2: "}",                                                                                                   mime: mimeCss },
+        ]
+        .forEach(function (template) {
+            testCases.push({
+                description: "'" + template.initiator + ": 1 second delay before 'responseStart', another 1 second delay before 'responseEnd'.",
+                test: function (test) {
+                    initiateFetch(
+                        test,
+                        template.initiator,
+                        getSyntheticUrl(serverStepDelay + "ms"                          // Wait, then echo back responsePart1
+                            + "&mime:" + encodeURIComponent(template.mime)
+                            + "&send:" + encodeURIComponent(template.responsePart1)
+                            + "&" + serverStepDelay + "ms"                              // Wait, then echo back responsePart2
+                            + "&send:" + encodeURIComponent(template.responsePart2)),
+
+                        function (initiator, entry) {
+                            // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:
+                            // If no redirects (or equivalent) occur, this redirectStart/End must return zero.
+                            assert_equals(entry.redirectStart, 0, "When no redirect occurs, redirectStart must be 0.");
+                            assert_equals(entry.redirectEnd, 0, "When no redirect occurs, redirectEnd must be 0.");
+
+                            // Server creates a gap between 'requestStart' and 'responseStart'.
+                            assert_greater_than_equal(
+                                entry.responseStart,
+                                entry.requestStart + serverStepDelay,
+                                "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");
+
+                            // Server creates a gap between 'responseStart' and 'responseEnd'.
+                            assert_greater_than_equal(
+                                entry.responseEnd,
+                                entry.responseStart + serverStepDelay,
+                                "'responseEnd' must be " + serverStepDelay + "ms later than 'responseStart'.");
+
+                            test.done();
+                        });
+                    }
+                });
+            });
+
+        // Create redirectEnd/responseStart tests from the following array of templates.  In this test, the server delays before
+        // redirecting to a new synthetic response, then delays again before responding with 'response'.  The test looks for the
+        // expected pauses before redirectEnd and responseStart.
+        [
+            { initiator: "iframe",         response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)",        mime: mimeHtml },
+            { initiator: "xmlhttprequest", response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)",        mime: mimeText },
+            // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd.  Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187
+            // { initiator: "img",            response: greenPng,                                                                      mime: mimePng },
+            { initiator: "script",         response: '"";',                                                                         mime: mimeScript },
+            { initiator: "link",           response: ".unused{}",                                                                   mime: mimeCss },
+        ]
+        .forEach(function (template) {
+            testCases.push({
+                description: "'" + template.initiator + " (Redirected): 1 second delay before 'redirectEnd', another 1 second delay before 'responseStart'.",
+                test: function (test) {
+                    initiateFetch(
+                        test,
+                        template.initiator,
+                        getSyntheticUrl(serverStepDelay + "ms"      // Wait, then redirect to a second page that waits
+                            + "&redirect:"                          // before echoing back the response.
+                                + encodeURIComponent(
+                                    getSyntheticUrl(serverStepDelay + "ms"
+                                        + "&mime:" + encodeURIComponent(template.mime)
+                                        + "&send:" + encodeURIComponent(template.response)))),
+                        function (initiator, entry) {
+                            // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:
+                            //      "[If redirected, startTime] MUST return the same value as redirectStart.
+                            assert_equals(entry.startTime, entry.redirectStart, "startTime must be equal to redirectStart.");
+
+                            // Server creates a gap between 'redirectStart' and 'redirectEnd'.
+                            assert_greater_than_equal(
+                                entry.redirectEnd,
+                                entry.redirectStart + serverStepDelay,
+                                "'redirectEnd' must be " + serverStepDelay + "ms later than 'redirectStart'.");
+
+                            // Server creates a gap between 'requestStart' and 'responseStart'.
+                            assert_greater_than_equal(
+                                entry.responseStart,
+                                entry.requestStart + serverStepDelay,
+                                "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");
+
+                            test.done();
+                        });
+                    }
+                });
+            });
+
+        // Function to run the next case in the queue.
+        var currentTestIndex = -1;
+        function runNextCase() {
+            var testCase = testCases[++currentTestIndex];
+            if (testCase !== undefined) {
+                async_test(testCase.test, testCase.description);
+            }
+        }
+
+        // When a test completes, run the next case in the queue.
+        add_result_callback(runNextCase);
+
+        // Start the first test.
+        runNextCase();
+
+        /** Iterates through all resource entries on the timeline, vetting all invariants. */
+        function assertInvariants(test, done) {
+            // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd.  Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187
+            // Yield for 100ms to workaround a suspected race where window.onload fires before
+            //     script visible side-effects from the wininet/urlmon thread have finished.
+            window.setTimeout(
+                test.step_func(
+                    function () {
+                        performance
+                            .getEntriesByType("resource")
+                            .forEach(
+                                function (entry, index, entries) {
+                                    assertResourceEntryInvariants(entry);
+                                });
+
+                        done();
+                    }),
+                    100);
+        }
+
+        /** Assets the invariants for a resource timeline entry. */
+        function assertResourceEntryInvariants(actual) {
+            // Example from http://w3c.github.io/resource-timing/#resources-included:
+            //     "If an HTML IFRAME element is added via markup without specifying a src attribute,
+            //      the user agent may load the about:blank document for the IFRAME. If at a later time
+            //      the src attribute is changed dynamically via script, the user agent may fetch the new
+            //      URL resource for the IFRAME. In this case, only the fetch of the new URL would be
+            //      included as a PerformanceResourceTiming object in the Performance Timeline."
+            assert_not_equals(
+                actual.name,
+                "about:blank",
+                "Fetch for 'about:blank' must not appear in timeline.");
+
+            assert_not_equals(actual.startTime, 0, "startTime");
+
+            // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:
+            //      "[If redirected, startTime] MUST return the same value as redirectStart. Otherwise,
+            //      [startTime] MUST return the same value as fetchStart."
+            assert_true(actual.startTime == actual.redirectStart || actual.startTime == actual.fetchStart,
+                "startTime must be equal to redirectStart or fetchStart.");
+
+            // redirectStart <= redirectEnd <= fetchStart <= domainLookupStart <= domainLookupEnd <= connectStart
+            assert_less_than_equal(actual.redirectStart, actual.redirectEnd, "redirectStart <= redirectEnd");
+            assert_less_than_equal(actual.redirectEnd, actual.fetchStart, "redirectEnd <= fetchStart");
+            assert_less_than_equal(actual.fetchStart, actual.domainLookupStart, "fetchStart <= domainLookupStart");
+            assert_less_than_equal(actual.domainLookupStart, actual.domainLookupEnd, "domainLookupStart <= domainLookupEnd");
+            assert_less_than_equal(actual.domainLookupEnd, actual.connectStart, "domainLookupEnd <= connectStart");
+
+            // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:
+            //      "This attribute is optional. User agents that don't have this attribute available MUST set it
+            //      as undefined.  [...]  If the secureConnectionStart attribute is available but HTTPS is not used,
+            //      this attribute MUST return zero."
+            assert_true(actual.secureConnectionStart == undefined ||
+                        actual.secureConnectionStart == 0 ||
+                        actual.secureConnectionStart >= actual.connectEnd, "secureConnectionStart time");
+
+            // connectStart <= connectEnd <= requestStart <= responseStart <= responseEnd
+            assert_less_than_equal(actual.connectStart, actual.connectEnd, "connectStart <= connectEnd");
+            assert_less_than_equal(actual.connectEnd, actual.requestStart, "connectEnd <= requestStart");
+            assert_less_than_equal(actual.requestStart, actual.responseStart, "requestStart <= responseStart");
+            assert_less_than_equal(actual.responseStart, actual.responseEnd, "responseStart <= responseEnd");
+        }
+
+        /** Helper function to resolve a relative URL */
+        function canonicalize(url) {
+            var div = document.createElement('div');
+            div.innerHTML = "<a></a>";
+            div.firstChild.href = ""
+            div.innerHTML = div.innerHTML;
+            return div.firstChild.href;
+        }
+
+        /** Generates a unique string, used by getSyntheticUrl() to avoid hitting the cache. */
+        function createUniqueQueryArgument() {
+            var result =
+                "ignored_"
+                    + Date.now()
+                    + "-"
+                    + ((Math.random() * 0xFFFFFFFF) >>> 0)
+                    + "-"
+                    + syntheticRequestCount;
+
+            return result;
+        }
+
+        /** Count of the calls to getSyntheticUrl().  Used by createUniqueQueryArgument() to generate unique strings. */
+        var syntheticRequestCount = 0;
+
+        /** Return a URL to a server that will synthesize an HTTP response using the given
+            commands. (See SyntheticResponse.aspx). */
+        function getSyntheticUrl(commands, allowCache) {
+            syntheticRequestCount++;
+
+            var url =
+                canonicalize("./SyntheticResponse.py")    // ASP.NET page that will synthesize the response.
+                    + "?" + commands;                       // Commands that will be used.
+
+            if (allowCache !== true) {                      // If caching is disallowed, append a unique argument
+                url += "&" + createUniqueQueryArgument();   // to the URL's query string.
+            }
+
+            return url;
+        }
+
+        /** Given an 'initiatorType' (e.g., "img") , it triggers the appropriate type of fetch for the specified
+            url and invokes 'onloadCallback' when the fetch completes.  If the fetch caused an entry to be created
+            on the resource timeline, the entry is passed to the callback. */
+        function initiateFetch(test, initiatorType, url, onloadCallback) {
+            assertInvariants(
+                test,
+                function () {
+                    log("--- Begin: " + url);
+
+                    switch (initiatorType) {
+                        case "script":
+                        case "img":
+                        case "iframe": {
+                            var element = document.createElement(initiatorType);
+                            document.body.appendChild(element);
+                            element._onload_ = createOnloadCallbackFn(test, element, url, onloadCallback);
+                            element.src = ""
+                            break;
+                        }
+                        case "link": {
+                            var element = document.createElement(initiatorType);
+                            element.rel = "stylesheet";
+                            document.body.appendChild(element);
+                            element._onload_ = createOnloadCallbackFn(test, element, url, onloadCallback);
+                            element.href = ""
+                            break;
+                        }
+                        case "xmlhttprequest": {
+                            var xhr = new XMLHttpRequest();
+                            xhr.open('GET', url, true);
+                            xhr._onreadystatechange_ = createOnloadCallbackFn(test, xhr, url, onloadCallback);
+                            xhr.send();
+                            break;
+                        }
+                        default:
+                            assert_unreached("Unsupported initiatorType '" + initiatorType + "'.");
+                            break;
+                    }});
+        }
+
+        /** Used by 'initiateFetch' to register a test step for the asynchronous callback, vet invariants,
+            find the matching resource timeline entry (if any), and pass it to the given 'onloadCallback'
+            when invoked. */
+        function createOnloadCallbackFn(test, initiator, url, onloadCallback) {
+            // Remember the number of entries on the timeline prior to initiating the fetch:
+            var beforeEntryCount = performance.getEntries().length;
+
+            return test.step_func(
+                function() {
+                    // If the fetch was initiated by XHR, we're subscribed to the 'onreadystatechange' event.
+                    // Ignore intermediate callbacks and wait for the XHR to complete.
+                    if (Object.getPrototypeOf(initiator) === XMLHttpRequest.prototype) {
+                        if (initiator.readyState != 4) {
+                            return;
+                        }
+                    }
+
+                    var entries = performance.getEntries();
+                    var candidateEntry = entries[entries.length - 1];
+
+                    switch (entries.length - beforeEntryCount)
+                    {
+                        case 0:
+                            candidateEntry = undefined;
+                            break;
+                        case 1:
+                            // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:
+                            //     "This attribute MUST return the resolved URL of the requested resource. This attribute
+                            //      MUST NOT change even if the fetch redirected to a different URL."
+                            assert_equals(candidateEntry.name, url, "'name' did not match expected 'url'.");
+                            logResourceEntry(candidateEntry);
+                            break;
+                        default:
+                            assert_unreached("At most, 1 entry should be added to the performance timeline during a fetch.");
+                            break;
+                    }
+
+                    assertInvariants(
+                        test,
+                        function () {
+                            onloadCallback(initiator, candidateEntry);
+                        });
+                });
+        }
+
+        /** Log the given text to the document element with id='output' */
+        function log(text) {
+            var output = document.getElementById("output");
+            output.textContent += text + "\r\n";
+        }
+
+        add_completion_callback(function () {
+            var output = document.getElementById("output");
+            var button = document.createElement('button');
+            output.parentNode.insertBefore(button, output);
+            button._onclick_ = function () {
+                var showButton = output.style.display == 'none';
+                output.style.display = showButton ? null : 'none';
+                button.textContent = showButton ? 'Hide details' : 'Show details';
+            }
+            button.onclick();
+            var iframes = document.querySelectorAll('iframe');
+            for (var i = 0; i < iframes.length; i++)
+                iframes[i].parentNode.removeChild(iframes[i]);
+        });
+
+        /** pretty print a resource timeline entry. */
+        function logResourceEntry(entry) {
+            log("[" + entry.entryType + "] " + entry.name);
+
+            ["startTime", "redirectStart", "redirectEnd", "fetchStart", "domainLookupStart", "domainLookupEnd", "connectStart", "secureConnectionStart", "connectEnd", "requestStart", "responseStart", "responseEnd"]
+                .forEach(
+                    function (property, index, array) {
+                        var value = entry[property];
+                        log(property + ":\t" + value);
+                    });
+
+            log("\r\n");
+        }
+    };

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.css (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.css	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.css	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,4 @@
+div#resource_link_css
+{
+    color:hotpink;
+}
\ No newline at end of file

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.html (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.html	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.html	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>
+        Child Frame
+        </title>
+    </head>
+    <body style="background-color: #C0C0C0">
+
+        <h1>
+        Child Document
+        </h1>
+
+    </body>
+</html>
\ No newline at end of file

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.js (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.js	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.js	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,3 @@
+// This is a test script for purposes of testing the
+// script initiator type in the Resource Timing feature
+var testDummyValue = 0;

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.png


(Binary files differ)
Index: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.png =================================================================== --- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.png 2016-08-25 18:21:16 UTC (rev 204975) +++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.png 2016-08-25 18:22:25 UTC (rev 204976) Property changes on: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.png ___________________________________________________________________

Added: svn:mime-type

+application/octet-stream \ No newline at end of property

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.xml (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.xml	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/resource_timing_test0.xml	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<TESTDATA>
+    <ITEM>
+        <DATA>Test XML Data</DATA>
+    </ITEM>
+</TESTDATA>

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/webperftestharness.js (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/webperftestharness.js	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/resources/webperftestharness.js	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,145 @@
+//
+// Helper Functions for NavigationTiming W3C tests
+//
+
+var performanceNamespace = window.performance;
+var timingAttributes = [
+    'connectEnd',
+    'connectStart',
+    'domComplete',
+    'domContentLoadedEventEnd',
+    'domContentLoadedEventStart',
+    'domInteractive',
+    'domLoading',
+    'domainLookupEnd',
+    'domainLookupStart',
+    'fetchStart',
+    'loadEventEnd',
+    'loadEventStart',
+    'navigationStart',
+    'redirectEnd',
+    'redirectStart',
+    'requestStart',
+    'responseEnd',
+    'responseStart',
+    'unloadEventEnd',
+    'unloadEventStart'
+];
+
+var namespace_check = false;
+
+//
+// All test() functions in the WebPerf test suite should use wp_test() instead.
+//
+// wp_test() validates the window.performance namespace exists prior to running tests and
+// immediately shows a single failure if it does not.
+//
+
+function wp_test(func, msg, properties)
+{
+    // only run the namespace check once
+    if (!namespace_check)
+    {
+        namespace_check = true;
+
+        if (performanceNamespace === undefined || performanceNamespace == null)
+        {
+            // show a single error that window.performance is undefined
+            test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null.", {author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "});
+        }
+    }
+
+    test(func, msg, properties);
+}
+
+function test_namespace(child_name, skip_root)
+{
+    if (skip_root === undefined) {
+        var msg = 'window.performance is defined';
+        wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "});
+    }
+
+    if (child_name !== undefined) {
+        var msg2 = 'window.performance.' + child_name + ' is defined';
+        wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "});
+    }
+}
+
+function test_attribute_exists(parent_name, attribute_name, properties)
+{
+    var msg = 'window.performance.' + parent_name + '.' + attribute_name + ' is defined.';
+    wp_test(function() { assert_true(performanceNamespace[parent_name][attribute_name] !== undefined, msg); }, msg, properties);
+}
+
+function test_enum(parent_name, enum_name, value, properties)
+{
+    var msg = 'window.performance.' + parent_name + '.' + enum_name + ' is defined.';
+    wp_test(function() { assert_true(performanceNamespace[parent_name][enum_name] !== undefined, msg); }, msg, properties);
+
+    msg = 'window.performance.' + parent_name + '.' + enum_name + ' = ' + value;
+    wp_test(function() { assert_equals(performanceNamespace[parent_name][enum_name], value, msg); }, msg, properties);
+}
+
+function test_timing_order(attribute_name, greater_than_attribute, properties)
+{
+    // ensure it's not 0 first
+    var msg = "window.performance.timing." + attribute_name + " > 0";
+    wp_test(function() { assert_true(performanceNamespace.timing[attribute_name] > 0, msg); }, msg, properties);
+
+    // ensure it's in the right order
+    msg = "window.performance.timing." + attribute_name + " >= window.performance.timing." + greater_than_attribute;
+    wp_test(function() { assert_true(performanceNamespace.timing[attribute_name] >= performanceNamespace.timing[greater_than_attribute], msg); }, msg, properties);
+}
+
+function test_timing_greater_than(attribute_name, greater_than, properties)
+{
+    var msg = "window.performance.timing." + attribute_name + " > " + greater_than;
+    test_greater_than(performanceNamespace.timing[attribute_name], greater_than, msg, properties);
+}
+
+function test_timing_equals(attribute_name, equals, msg, properties)
+{
+    var test_msg = msg || "window.performance.timing." + attribute_name + " == " + equals;
+    test_equals(performanceNamespace.timing[attribute_name], equals, test_msg, properties);
+}
+
+//
+// Non-test related helper functions
+//
+
+function sleep_milliseconds(n)
+{
+    var start = new Date().getTime();
+    while (true) {
+        if ((new Date().getTime() - start) >= n) break;
+    }
+}
+
+//
+// Common helper functions
+//
+
+function test_true(value, msg, properties)
+{
+    wp_test(function () { assert_true(value, msg); }, msg, properties);
+}
+
+function test_equals(value, equals, msg, properties)
+{
+    wp_test(function () { assert_equals(value, equals, msg); }, msg, properties);
+}
+
+function test_greater_than(value, greater_than, msg, properties)
+{
+    wp_test(function () { assert_true(value > greater_than, msg); }, msg, properties);
+}
+
+function test_greater_or_equals(value, greater_than, msg, properties)
+{
+    wp_test(function () { assert_true(value >= greater_than, msg); }, msg, properties);
+}
+
+function test_not_equals(value, notequals, msg, properties)
+{
+    wp_test(function() { assert_true(value !== notequals, msg); }, msg, properties);
+}

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing-expected.txt (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing-expected.txt	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing-expected.txt	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,24 @@
+Description
+
+NOTE: Due to caching behavior in the browser, it is possible that when revisiting this page, some resources may not have to be fetched from the network. As a result, the performance timeline will not contain entries for these resources. This test will fail if any entries are missing to ensure that all resources are fetched from the network and entries for these resources exist in the Performance Timeline. If revisiting this page, please either perform a full reload of the page or clear the cache between visits.
+
+
+PASS window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (iframe) 
+PASS PerformanceEntry has correct name, initiatorType, startTime, and duration (iframe) 
+PASS PerformanceEntry has correct order of timing attributes (iframe) 
+PASS window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (img) 
+PASS PerformanceEntry has correct name, initiatorType, startTime, and duration (img) 
+PASS PerformanceEntry has correct order of timing attributes (img) 
+PASS window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (link) 
+PASS PerformanceEntry has correct name, initiatorType, startTime, and duration (link) 
+PASS PerformanceEntry has correct order of timing attributes (link) 
+PASS window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (script) 
+PASS PerformanceEntry has correct name, initiatorType, startTime, and duration (script) 
+PASS PerformanceEntry has correct order of timing attributes (script) 
+PASS window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (xmlhttprequest) 
+PASS PerformanceEntry has correct name, initiatorType, startTime, and duration (xmlhttprequest) 
+PASS PerformanceEntry has correct order of timing attributes (xmlhttprequest) 
+PASS window.performance Resource Timing Entries exist 
+PASS window.performance Resource Timing Entries exist 1 
+PASS window.performance Resource Timing Entries exist 2 
+

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.html (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.html	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.html	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset="UTF-8" />
+        <title>window.performance Resource Timing Entries exist</title>
+        <link rel="author" title="Microsoft" href="" />
+        <link rel="help" href=""
+        <script src=""
+        <script src=""
+        <script src=""
+    </head>
+    <body>
+        <h1>Description</h1>
+        <p>
+           NOTE: Due to caching behavior in the browser, it is possible that when revisiting this page, some resources
+           may not have to be fetched from the network.  As a result, the performance timeline will not contain entries
+           for these resources. This test will fail if any entries are missing to ensure that all resources are fetched
+           from the network and entries for these resources exist in the Performance Timeline.  If revisiting this page,
+           please either perform a full reload of the page or clear the cache between visits.
+        </p>
+
+        <div id="log"></div>
+    </body>
+</html>

Added: trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.js (0 => 204976)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.js	                        (rev 0)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/resource-timing/test_resource_timing.js	2016-08-25 18:22:25 UTC (rev 204976)
@@ -0,0 +1,186 @@
+var TEST_ALLOWED_TIMING_DELTA = 20;
+
+var waitTimer;
+var expectedEntries = {};
+
+var initiatorTypes = ["iframe", "img", "link", "script", "xmlhttprequest"];
+
+var tests = {};
+setup(function() {
+    for (var i in initiatorTypes) {
+        var type = initiatorTypes[i];
+        tests[type] = {
+            "entry": async_test("window.performance.getEntriesByName() and window.performance.getEntriesByNameType() return same data (" + type + ")"),
+            "simple_attrs": async_test("PerformanceEntry has correct name, initiatorType, startTime, and duration (" + type + ")"),
+            "timing_attrs": async_test("PerformanceEntry has correct order of timing attributes (" + type + ")")
+        };
+    }
+});
+
+function resolve(path) {
+    var a = document.createElement("a");
+    a.href = ""
+    return a.href;
+}
+
+_onload_ = function()
+{
+    // check that the Performance Timeline API exists
+    test(function() {
+        assert_idl_attribute(window.performance, "getEntriesByName",
+                             "window.performance.getEntriesByName() is defined");
+    });
+    test(function() {
+        assert_idl_attribute(window.performance, "getEntriesByType",
+                             "window.performance.getEntriesByType() is defined");
+    });
+    test(function() {
+        assert_idl_attribute(window.performance, "getEntries",
+                             "window.performance.getEntries() is defined");
+    });
+
+    var expected_entry;
+    var url;
+    var type;
+    var startTime;
+    var element;
+    for (var i in initiatorTypes) {
+        startTime = window.performance.now();
+        type = initiatorTypes[i];
+        if (type != "xmlhttprequest") {
+            element = document.createElement(type);
+        } else {
+            element = null;
+        }
+        switch (type) {
+        case "iframe":
+            url = ""
+            element.src = ""
+            break;
+        case "img":
+            url = ""
+            element.src = ""
+            break;
+        case "link":
+            element.rel = "stylesheet";
+            url = ""
+            element.href = ""
+            break;
+        case "script":
+            element.type = "text/_javascript_";
+            url = ""
+            element.src = ""
+            break;
+        case "xmlhttprequest":
+            var xmlhttp = new XMLHttpRequest();
+            url = ""
+            xmlhttp.open('GET', url, true);
+            xmlhttp.send();
+            break;
+        }
+
+        expected_entry = {name:url,
+                          startTime: startTime,
+                          initiatorType: type};
+
+        switch (type) {
+        case "link":
+            poll_for_stylesheet_load(expected_entry);
+            document.body.appendChild(element);
+            break;
+        case "xmlhttprequest":
+            xmlhttp._onload_ = (function(entry) {
+                return function (event) {
+                    resource_load(entry);
+                };
+            })(expected_entry);
+            break;
+        default:
+            element._onload_ = (function(entry) {
+                return function (event) {
+                    resource_load(entry);
+                };
+            })(expected_entry);
+            document.body.appendChild(element);
+        }
+
+    }
+};
+
+function poll_for_stylesheet_load(expected_entry) {
+    function inner() {
+        for(var i=0; i<document.styleSheets.length; i++) {
+            var sheet = document.styleSheets[i];
+            if (sheet.href ="" expected_entry.name) {
+                try {
+                    // try/catch avoids throwing if sheet object exists before it is loaded,
+                    // which is a bug, but not what we are trying to test here.
+                    var hasRules = sheet.cssRules.length > 0;
+                } catch(e) {
+                    hasRules = false;
+                }
+                if (hasRules) {
+                    setTimeout(function() {
+                        resource_load(expected_entry);
+                    }, 200);
+                    return;
+                }
+            }
+        }
+        setTimeout(inner, 100);
+    }
+    inner();
+}
+
+function resource_load(expected)
+{
+    var t = tests[expected.initiatorType];
+
+    t["entry"].step(function() {
+        var entries_by_name = window.performance.getEntriesByName(expected.name);
+        assert_equals(entries_by_name.length, 1, "should have a single entry for each resource (without type)");
+        var entries_by_name_type = window.performance.getEntriesByName(expected.name, "resource");
+        assert_equals(entries_by_name_type.length, 1, "should have a single entry for each resource (with type)");
+        assert_not_equals(entries_by_name, entries_by_name_type, "values should be copies");
+        for (p in entries_by_name[0]) {
+            assert_equals(entries_by_name[0][p], entries_by_name_type[0][p], "Property " + p + " should match");
+        }
+        this.done();
+    });
+
+    t["simple_attrs"].step(function() {
+        var actual = window.performance.getEntriesByName(expected.name)[0];
+        var expected_type = expected.initiatorType;
+        assert_equals(actual.name, expected.name);
+        assert_equals(actual.initiatorType, expected_type);
+        assert_equals(actual.entryType, "resource");
+        assert_greater_than_equal(actual.startTime, expected.startTime, "startTime is after the script to initiate the load ran");
+        assert_equals(actual.duration, (actual.responseEnd - actual.startTime));
+        this.done();
+    });
+
+    t["timing_attrs"].step(function test() {
+        var actual = window.performance.getEntriesByName(expected.name)[0];
+
+        // Debugging bug 1263428
+        // Feel free to remove/overwrite this piece of code
+        if (actual.connectStart < actual.domainLookupEnd) {
+            assert_true(false, "actual: "+JSON.stringify(actual));
+        }
+
+        assert_equals(actual.redirectStart, 0, "redirectStart time");
+        assert_equals(actual.redirectEnd, 0, "redirectEnd time");
+        assert_true(actual.secureConnectionStart == undefined ||
+                    actual.secureConnectionStart == 0, "secureConnectionStart time");
+        assert_equals(actual.fetchStart, actual.startTime, "fetchStart is equal to startTime");
+        assert_greater_than_equal(actual.domainLookupStart, actual.fetchStart, "domainLookupStart after fetchStart");
+        assert_greater_than_equal(actual.domainLookupEnd, actual.domainLookupStart, "domainLookupEnd after domainLookupStart");
+        assert_greater_than_equal(actual.connectStart, actual.domainLookupEnd, "connectStart after domainLookupEnd");
+        assert_greater_than_equal(actual.connectEnd, actual.connectStart, "connectEnd after connectStart");
+        assert_greater_than_equal(actual.requestStart, actual.connectEnd, "requestStart after connectEnd");
+        assert_greater_than_equal(actual.responseStart, actual.requestStart, "responseStart after requestStart");
+        assert_greater_than_equal(actual.responseEnd, actual.responseStart, "responseEnd after responseStart");
+        this.done();
+    });
+
+}

Modified: trunk/LayoutTests/resources/testharnessreport.js (204975 => 204976)


--- trunk/LayoutTests/resources/testharnessreport.js	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/LayoutTests/resources/testharnessreport.js	2016-08-25 18:22:25 UTC (rev 204976)
@@ -50,31 +50,37 @@
     *   manner that allows dumpAsText to produce readable test results
     */
     add_completion_callback(function (tests, harness_status) {
-        var results = document.createElement("pre");
-        var resultStr = "\n";
+        // Wait for any other completion callbacks
+        setTimeout(function() {
+            var results = document.createElement("pre");
+            var resultStr = "\n";
 
-        if(harness_status.status != 0)
-            resultStr += "Harness Error (" + convertResult(harness_status.status) + "), message = " + harness_status.message + "\n\n";
+            if(harness_status.status != 0)
+                resultStr += "Harness Error (" + convertResult(harness_status.status) + "), message = " + harness_status.message + "\n\n";
 
-        for (var i = 0; i < tests.length; i++) {
-            var message = (tests[i].message != null) ? tests[i].message : "";
-            if (tests[i].status == 1 && !tests[i].dumpStack) {
-                // Remove stack for failed tests for proper string comparison without file paths.
-                // For a test to dump the stack set its dumpStack attribute to true.
-                var stackIndex = message.indexOf("(stack:");
-                if (stackIndex > 0)
-                    message = message.substr(0, stackIndex);
+            for (var i = 0; i < tests.length; i++) {
+                var message = (tests[i].message != null) ? tests[i].message : "";
+                if (tests[i].status == 1 && !tests[i].dumpStack) {
+                    // Remove stack for failed tests for proper string comparison without file paths.
+                    // For a test to dump the stack set its dumpStack attribute to true.
+                    var stackIndex = message.indexOf("(stack:");
+                    if (stackIndex > 0)
+                        message = message.substr(0, stackIndex);
+                }
+                resultStr += convertResult(tests[i].status) + " " +  (tests[i].name != null ? tests[i].name : "") + " " + message + "\n";
             }
-            resultStr += convertResult(tests[i].status) + " " +  (tests[i].name != null ? tests[i].name : "") + " " + message + "\n";
-        }
 
-        results.innerText = resultStr;
-        var log = document.getElementById("log");
-        if (log)
-            log.appendChild(results);
-        else
-            document.body.appendChild(results);
+            results.innerText = resultStr;
+            var log = document.getElementById("log");
+            if (log)
+                log.appendChild(results);
+            else
+                document.body.appendChild(results);
 
-        testRunner.notifyDone();
+            testRunner.notifyDone();
+        }, 0);
     });
+
+    if (window.internals)
+        window.internals.setResourceTimingSupport(true);
 }

Modified: trunk/Source/WebCore/ChangeLog (204975 => 204976)


--- trunk/Source/WebCore/ChangeLog	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/ChangeLog	2016-08-25 18:22:25 UTC (rev 204976)
@@ -1,3 +1,85 @@
+2016-08-25  Johan K. Jensen  <johan_jen...@apple.com>
+
+        Update the Resource Timing implementation
+        https://bugs.webkit.org/show_bug.cgi?id=161068
+
+        Reviewed by Alex Christensen.
+
+        Tests: imported/w3c/web-platform-tests/resource-timing/resource-timing.html
+               imported/w3c/web-platform-tests/resource-timing/test_resource_timing.html
+
+        Update the Resource Timing implementation for better compatibility with the Resource Timing API spec.
+        Use LoadTiming for general timing information about a resources load timeline.
+        Mark timestamps for newly loaded resources as well as cached resources.
+
+        * loader/DocumentLoader.cpp:
+        (WebCore::DocumentLoader::startLoadingMainResource):
+        StartTime and fetchStart should be equal initially.
+
+        * loader/LoadTiming.cpp:
+        (WebCore::LoadTiming::LoadTiming): Moved member initialization out. Removed constructor.
+        * loader/LoadTiming.h:
+        (WebCore::LoadTiming::markStartTimeAndFetchStart):
+        Mark startTime and fetchStart simultaneously.
+
+        * loader/ResourceLoader.cpp:
+        (WebCore::ResourceLoader::init):
+        Mark the start time of resources.
+
+        * loader/ResourceLoader.h:
+        (WebCore::ResourceLoader::loadTiming):
+        Add LoadTiming info to handle a resources load timing.
+
+        * loader/ResourceTimingInformation.cpp:
+        (WebCore::ResourceTimingInformation::addResourceTiming):
+        * loader/ResourceTimingInformation.h:
+        Only pass in the URL from the ResourceRequest.
+        Pass LoadTiming instead of timestamps.
+
+        * loader/SubresourceLoader.cpp:
+        (WebCore::SubresourceLoader::willSendRequestInternal):
+        Mark redirects.
+
+        (WebCore::SubresourceLoader::didFinishLoading):
+        Mark the responseEnd timestamp.
+        Add the ResourceEntry to the timeline before notifyDone is called.
+
+        * loader/cache/CachedResourceLoader.cpp:
+        (WebCore::CachedResourceLoader::requestResource):
+        (WebCore::CachedResourceLoader::revalidateResource):
+        (WebCore::CachedResourceLoader::loadDone):
+        Mark timestamps for cached resources and use them instead of a cached LoadTiming.
+
+        * loader/cache/CachedResourceLoader.h:
+        (WebCore::CachedResourceLoader::resourceTimingInformation):
+        Add ResourceTimingInformation getter so SubresourceLoader.cpp can add entries before callbacks.
+
+        * page/Performance.cpp:
+        (WebCore::Performance::addResourceTiming):
+        * page/Performance.h:
+        Update signature: URLs and LoadTiming instead of timestamps.
+
+        * page/PerformanceResourceTiming.cpp:
+        (WebCore::PerformanceResourceTiming::PerformanceResourceTiming):
+        (WebCore::PerformanceResourceTiming::redirectStart):
+        (WebCore::PerformanceResourceTiming::redirectEnd):
+        (WebCore::PerformanceResourceTiming::fetchStart):
+        (WebCore::PerformanceResourceTiming::domainLookupStart):
+        (WebCore::PerformanceResourceTiming::domainLookupEnd):
+        (WebCore::PerformanceResourceTiming::connectStart):
+        (WebCore::PerformanceResourceTiming::connectEnd):
+        (WebCore::PerformanceResourceTiming::requestStart):
+        (WebCore::PerformanceResourceTiming::responseStart):
+        (WebCore::PerformanceResourceTiming::responseEnd):
+        (WebCore::PerformanceResourceTiming::resourceTimeToDocumentMilliseconds):
+        * page/PerformanceResourceTiming.h:
+        Update signatures and properties to use LoadTiming.
+        Use LoadTiming’s redirectStart/End, fetchStart, responseStart/End.
+        Make sure dns and connection timestamps are in increasing order, even when cached.
+
+        * page/PerformanceResourceTiming.idl:
+        Add responseStart.
+
 2016-08-24  Anders Carlsson  <ander...@apple.com>
 
         Simplify createMouseEvent in DragController

Modified: trunk/Source/WebCore/loader/DocumentLoader.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/DocumentLoader.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/DocumentLoader.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -1466,7 +1466,7 @@
 void DocumentLoader::startLoadingMainResource()
 {
     m_mainDocumentError = ResourceError();
-    timing().markStartTime();
+    timing().markStartTimeAndFetchStart();
     ASSERT(!m_mainResource);
     ASSERT(!m_loadingMainResource);
     m_loadingMainResource = true;
@@ -1485,8 +1485,7 @@
     frameLoader()->addExtraFieldsToMainResourceRequest(m_request);
 
     ASSERT(timing().startTime());
-    ASSERT(!timing().fetchStart());
-    timing().markFetchStart();
+    ASSERT(timing().fetchStart());
 
     Ref<DocumentLoader> protectedThis(*this); // willSendRequest() may deallocate the provisional loader (which may be us) if it cancels the load.
     willSendRequest(m_request, ResourceResponse());

Modified: trunk/Source/WebCore/loader/LoadTiming.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/LoadTiming.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/LoadTiming.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -36,24 +36,6 @@
 
 namespace WebCore {
 
-LoadTiming::LoadTiming()
-    : m_referenceMonotonicTime(0.0)
-    , m_referenceWallTime(0.0)
-    , m_startTime(0.0)
-    , m_unloadEventStart(0.0)
-    , m_unloadEventEnd(0.0)
-    , m_redirectStart(0.0)
-    , m_redirectEnd(0.0)
-    , m_redirectCount(0)
-    , m_fetchStart(0.0)
-    , m_responseEnd(0.0)
-    , m_loadEventStart(0.0)
-    , m_loadEventEnd(0.0)
-    , m_hasCrossOriginRedirect(false)
-    , m_hasSameOriginAsPreviousDocument(false)
-{
-}
-
 double LoadTiming::monotonicTimeToZeroBasedDocumentTime(double monotonicTime) const
 {
     if (!monotonicTime)

Modified: trunk/Source/WebCore/loader/LoadTiming.h (204975 => 204976)


--- trunk/Source/WebCore/loader/LoadTiming.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/LoadTiming.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -34,7 +34,6 @@
 
 class LoadTiming {
 public:
-    LoadTiming();
 
     double monotonicTimeToZeroBasedDocumentTime(double) const;
     double monotonicTimeToPseudoWallTime(double) const;
@@ -42,6 +41,8 @@
     void markStartTime();
     void addRedirect(const URL& redirectingUrl, const URL& redirectedUrl);
 
+    void markStartTimeAndFetchStart() { markStartTime(); m_fetchStart = m_startTime; }
+
     void markUnloadEventStart() { m_unloadEventStart = monotonicallyIncreasingTime(); }
     void markUnloadEventEnd() { m_unloadEventEnd = monotonicallyIncreasingTime(); }
     void markRedirectStart() { m_redirectStart = monotonicallyIncreasingTime(); }
@@ -70,20 +71,20 @@
     double referenceWallTime() const { return m_referenceWallTime; }
 
 private:
-    double m_referenceMonotonicTime;
-    double m_referenceWallTime;
-    double m_startTime;
-    double m_unloadEventStart;
-    double m_unloadEventEnd;
-    double m_redirectStart;
-    double m_redirectEnd;
-    short m_redirectCount;
-    double m_fetchStart;
-    double m_responseEnd;
-    double m_loadEventStart;
-    double m_loadEventEnd;
-    bool m_hasCrossOriginRedirect;
-    bool m_hasSameOriginAsPreviousDocument;
+    double m_referenceMonotonicTime { 0.0 };
+    double m_referenceWallTime { 0.0 };
+    double m_startTime { 0.0 };
+    double m_unloadEventStart { 0.0 };
+    double m_unloadEventEnd { 0.0 };
+    double m_redirectStart { 0.0 };
+    double m_redirectEnd { 0.0 };
+    short m_redirectCount { 0 };
+    double m_fetchStart { 0.0 };
+    double m_responseEnd { 0.0 };
+    double m_loadEventStart { 0.0 };
+    double m_loadEventEnd { 0.0 };
+    bool m_hasCrossOriginRedirect { false };
+    bool m_hasSameOriginAsPreviousDocument { false };
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/loader/ResourceLoader.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/ResourceLoader.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/ResourceLoader.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -116,6 +116,8 @@
     
     ResourceRequest clientRequest(r);
 
+    m_loadTiming.markStartTimeAndFetchStart();
+
 #if PLATFORM(IOS)
     // If the documentLoader was detached while this ResourceLoader was waiting its turn
     // in ResourceLoadScheduler queue, don't continue.

Modified: trunk/Source/WebCore/loader/ResourceLoader.h (204975 => 204976)


--- trunk/Source/WebCore/loader/ResourceLoader.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/ResourceLoader.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -29,6 +29,7 @@
 #ifndef ResourceLoader_h
 #define ResourceLoader_h
 
+#include "LoadTiming.h"
 #include "ResourceHandleClient.h"
 #include "ResourceLoaderOptions.h"
 #include "ResourceLoaderTypes.h"
@@ -140,6 +141,8 @@
 
     void willSwitchToSubstituteResource();
 
+    const LoadTiming& loadTiming() { return m_loadTiming; }
+
 #if PLATFORM(COCOA) && !USE(CFNETWORK)
     void schedule(WTF::SchedulePair&);
     void unschedule(WTF::SchedulePair&);
@@ -172,7 +175,8 @@
     RefPtr<Frame> m_frame;
     RefPtr<DocumentLoader> m_documentLoader;
     ResourceResponse m_response;
-    
+    LoadTiming m_loadTiming;
+
 private:
     virtual void willCancel(const ResourceError&) = 0;
     virtual void didCancel(const ResourceError&) = 0;

Modified: trunk/Source/WebCore/loader/ResourceTimingInformation.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/ResourceTimingInformation.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/ResourceTimingInformation.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -33,12 +33,13 @@
 #include "Document.h"
 #include "Frame.h"
 #include "HTMLFrameOwnerElement.h"
+#include "LoadTiming.h"
 #include "Performance.h"
 #include "RuntimeEnabledFeatures.h"
 
 namespace WebCore {
 
-void ResourceTimingInformation::addResourceTiming(CachedResource* resource, Document& document)
+void ResourceTimingInformation::addResourceTiming(CachedResource* resource, Document& document, const LoadTiming& loadTiming)
 {
     ASSERT(RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled());
     if (resource && resource->resourceRequest().url().protocolIsInHTTPFamily()
@@ -52,7 +53,7 @@
             ASSERT(initiatorDocument->domWindow());
             ASSERT(initiatorDocument->domWindow()->performance());
             const InitiatorInfo& info = initiatorIt->value;
-            initiatorDocument->domWindow()->performance()->addResourceTiming(info.name, initiatorDocument, resource->resourceRequest(), resource->response(), info.startTime, resource->loadFinishTime());
+            initiatorDocument->domWindow()->performance()->addResourceTiming(info.name, initiatorDocument, resource->resourceRequest().url(), resource->response(), loadTiming);
             initiatorIt->value.added = Added;
         }
     }

Modified: trunk/Source/WebCore/loader/ResourceTimingInformation.h (204975 => 204976)


--- trunk/Source/WebCore/loader/ResourceTimingInformation.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/ResourceTimingInformation.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -37,11 +37,12 @@
 class CachedResourceRequest;
 class Document;
 class Frame;
+class LoadTiming;
 
 class ResourceTimingInformation {
 public:
 
-    void addResourceTiming(CachedResource*, Document&);
+    void addResourceTiming(CachedResource*, Document&, const LoadTiming&);
     void storeResourceTimingInitiatorInformation(const CachedResourceHandle<CachedResource>&, const CachedResourceRequest&, Frame*);
 
 private:

Modified: trunk/Source/WebCore/loader/SubresourceLoader.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/SubresourceLoader.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/SubresourceLoader.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -42,6 +42,7 @@
 #include "MemoryCache.h"
 #include "Page.h"
 #include "ResourceLoadObserver.h"
+#include "RuntimeEnabledFeatures.h"
 #include "Settings.h"
 #include <wtf/Ref.h>
 #include <wtf/RefCountedLeakCounter.h>
@@ -216,6 +217,7 @@
             cancel();
             return;
         }
+        m_loadTiming.addRedirect(redirectResponse.url(), newRequest.url());
         m_resource->redirectReceived(newRequest, redirectResponse);
     }
 
@@ -458,6 +460,12 @@
     Ref<SubresourceLoader> protectedThis(*this);
     CachedResourceHandle<CachedResource> protectResource(m_resource);
 
+    finishTime = monotonicallyIncreasingTime();
+    m_loadTiming.setResponseEnd(finishTime);
+
+    if (m_documentLoader->cachedResourceLoader().document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
+        m_documentLoader->cachedResourceLoader().resourceTimingInformation().addResourceTiming(m_resource, *m_documentLoader->cachedResourceLoader().document(), m_resource->loader()->loadTiming());
+
     m_state = Finishing;
     m_resource->setLoadFinishTime(finishTime);
     m_resource->finishLoading(resourceData());

Modified: trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp (204975 => 204976)


--- trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -68,6 +68,7 @@
 #include "SessionID.h"
 #include "Settings.h"
 #include "StyleSheetContents.h"
+#include "SubresourceLoader.h"
 #include "UserContentController.h"
 #include "UserStyleSheet.h"
 #include <wtf/text/CString.h>
@@ -595,6 +596,11 @@
     }
 #endif
 
+#if ENABLE(WEB_TIMING)
+    LoadTiming loadTiming;
+    loadTiming.markStartTimeAndFetchStart();
+#endif
+
     auto& memoryCache = MemoryCache::singleton();
     if (request.allowsCaching() && memoryCache.disabled()) {
         DocumentResourceMap::iterator it = m_documentResources.find(url.string());
@@ -638,8 +644,11 @@
         memoryCache.resourceAccessed(*resource);
 #if ENABLE(WEB_TIMING)
         if (document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled()) {
+            // FIXME (161170): The networkLoadTiming shouldn't be stored on the ResourceResponse.
+            resource->response().networkLoadTiming().reset();
+            loadTiming.setResponseEnd(monotonicallyIncreasingTime());
             m_resourceTimingInfo.storeResourceTimingInitiatorInformation(resource, request, frame());
-            m_resourceTimingInfo.addResourceTiming(resource.get(), *document());
+            m_resourceTimingInfo.addResourceTiming(resource.get(), *document(), loadTiming);
         }
 #endif
         break;
@@ -695,7 +704,7 @@
     memoryCache.add(*newResource);
 #if ENABLE(WEB_TIMING)
     if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
-        m_resourceTimingInfo.storeResourceTimingInitiatorInformation(resource, request, frame());
+        m_resourceTimingInfo.storeResourceTimingInitiatorInformation(newResource, request, frame());
 #else
     UNUSED_PARAM(request);
 #endif
@@ -988,8 +997,8 @@
     RefPtr<Document> protectDocument(m_document);
 
 #if ENABLE(WEB_TIMING)
-    if (document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
-        m_resourceTimingInfo.addResourceTiming(resource, *document());
+    if (resource && document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
+        m_resourceTimingInfo.addResourceTiming(resource, *document(), resource->loader()->loadTiming());
 #else
     UNUSED_PARAM(resource);
 #endif

Modified: trunk/Source/WebCore/loader/cache/CachedResourceLoader.h (204975 => 204976)


--- trunk/Source/WebCore/loader/cache/CachedResourceLoader.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/loader/cache/CachedResourceLoader.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -140,6 +140,8 @@
 
     void documentDidFinishLoadEvent();
 
+    ResourceTimingInformation& resourceTimingInformation() { return m_resourceTimingInfo; }
+
 private:
     explicit CachedResourceLoader(DocumentLoader*);
 

Modified: trunk/Source/WebCore/page/Performance.cpp (204975 => 204976)


--- trunk/Source/WebCore/page/Performance.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/page/Performance.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -164,12 +164,12 @@
         dispatchEvent(Event::create(eventNames().resourcetimingbufferfullEvent, false, false));
 }
 
-void Performance::addResourceTiming(const String& initiatorName, Document* initiatorDocument, const ResourceRequest& request, const ResourceResponse& response, double initiationTime, double finishTime)
+void Performance::addResourceTiming(const String& initiatorName, Document* initiatorDocument, const URL& originalURL, const ResourceResponse& response, LoadTiming loadTiming)
 {
     if (isResourceTimingBufferFull())
         return;
 
-    RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(initiatorName, request, response, initiationTime, finishTime, initiatorDocument);
+    RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(initiatorName, originalURL, response, loadTiming, initiatorDocument);
 
     m_resourceTimingBuffer.append(entry);
 

Modified: trunk/Source/WebCore/page/Performance.h (204975 => 204976)


--- trunk/Source/WebCore/page/Performance.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/page/Performance.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -46,10 +46,12 @@
 namespace WebCore {
 
 class Document;
+class LoadTiming;
 class PerformanceEntry;
 class ResourceRequest;
 class ResourceResponse;
 class UserTiming;
+class URL;
 
 class Performance final : public RefCounted<Performance>, public DOMWindowProperty, public EventTargetWithInlineData {
 public:
@@ -70,7 +72,7 @@
     void clearResourceTimings();
     void setResourceTimingBufferSize(unsigned);
 
-    void addResourceTiming(const String& initiatorName, Document*, const ResourceRequest&, const ResourceResponse&, double initiationTime, double finishTime);
+    void addResourceTiming(const String& initiatorName, Document*, const URL& originalURL, const ResourceResponse&, LoadTiming);
 
     using RefCounted<Performance>::ref;
     using RefCounted<Performance>::deref;

Modified: trunk/Source/WebCore/page/PerformanceResourceTiming.cpp (204975 => 204976)


--- trunk/Source/WebCore/page/PerformanceResourceTiming.cpp	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/page/PerformanceResourceTiming.cpp	2016-08-25 18:22:25 UTC (rev 204976)
@@ -76,11 +76,11 @@
     return false;
 }
 
-PerformanceResourceTiming::PerformanceResourceTiming(const AtomicString& initiatorType, const ResourceRequest& request, const ResourceResponse& response, double initiationTime, double finishTime, Document* requestingDocument)
-    : PerformanceEntry(request.url().string(), "resource", monotonicTimeToDocumentMilliseconds(requestingDocument, initiationTime), monotonicTimeToDocumentMilliseconds(requestingDocument, finishTime))
+PerformanceResourceTiming::PerformanceResourceTiming(const AtomicString& initiatorType, const URL& originalURL, const ResourceResponse& response, LoadTiming loadTiming, Document* requestingDocument)
+    : PerformanceEntry(originalURL.string(), "resource", monotonicTimeToDocumentMilliseconds(requestingDocument, loadTiming.startTime()), monotonicTimeToDocumentMilliseconds(requestingDocument, loadTiming.responseEnd()))
     , m_initiatorType(initiatorType)
     , m_timing(response.networkLoadTiming())
-    , m_finishTime(finishTime)
+    , m_loadTiming(loadTiming)
     , m_shouldReportDetails(passesTimingAllowCheck(response, requestingDocument))
     , m_requestingDocument(requestingDocument)
 {
@@ -97,10 +97,10 @@
 
 double PerformanceResourceTiming::redirectStart() const
 {
-    // FIXME: Need to track and report redirects for resources.
     if (!m_shouldReportDetails)
         return 0.0;
-    return 0;
+
+    return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_loadTiming.redirectStart());
 }
 
 double PerformanceResourceTiming::redirectEnd() const
@@ -107,13 +107,13 @@
 {
     if (!m_shouldReportDetails)
         return 0.0;
-    return 0;
+
+    return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_loadTiming.redirectEnd());
 }
 
 double PerformanceResourceTiming::fetchStart() const
 {
-    // FIXME: This should be different depending on redirects.
-    return (startTime());
+    return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_loadTiming.fetchStart());
 }
 
 double PerformanceResourceTiming::domainLookupStart() const
@@ -121,7 +121,7 @@
     if (!m_shouldReportDetails)
         return 0.0;
 
-    if (m_timing.domainLookupStart < 0)
+    if (m_timing.domainLookupStart <= 0)
         return fetchStart();
 
     return resourceTimeToDocumentMilliseconds(m_timing.domainLookupStart);
@@ -132,7 +132,7 @@
     if (!m_shouldReportDetails)
         return 0.0;
 
-    if (m_timing.domainLookupEnd < 0)
+    if (m_timing.domainLookupEnd <= 0)
         return domainLookupStart();
 
     return resourceTimeToDocumentMilliseconds(m_timing.domainLookupEnd);
@@ -144,7 +144,7 @@
         return 0.0;
 
     // connectStart will be -1 when a network request is not made.
-    if (m_timing.connectStart < 0)
+    if (m_timing.connectStart <= 0)
         return domainLookupEnd();
 
     // connectStart includes any DNS time, so we may need to trim that off.
@@ -161,7 +161,7 @@
         return 0.0;
 
     // connectStart will be -1 when a network request is not made.
-    if (m_timing.connectEnd < 0)
+    if (m_timing.connectEnd <= 0)
         return connectStart();
 
     return resourceTimeToDocumentMilliseconds(m_timing.connectEnd);
@@ -186,9 +186,20 @@
     return resourceTimeToDocumentMilliseconds(m_timing.requestStart);
 }
 
+double PerformanceResourceTiming::responseStart() const
+{
+    if (!m_shouldReportDetails)
+        return 0.0;
+
+    return resourceTimeToDocumentMilliseconds(m_timing.responseStart);
+}
+
 double PerformanceResourceTiming::responseEnd() const
 {
-    return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_finishTime);
+    if (!m_shouldReportDetails)
+        return 0.0;
+
+    return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_loadTiming.responseEnd());
 }
 
 double PerformanceResourceTiming::resourceTimeToDocumentMilliseconds(double deltaMilliseconds) const
@@ -195,7 +206,7 @@
 {
     if (!deltaMilliseconds)
         return 0.0;
-    double documentStartTime = m_requestingDocument->loader()->timing().monotonicTimeToZeroBasedDocumentTime(m_requestingDocument->loader()->timing().startTime()) * 1000.0;
+    double documentStartTime = m_requestingDocument->loader()->timing().monotonicTimeToZeroBasedDocumentTime(m_loadTiming.fetchStart()) * 1000.0;
     double resourceTimeSeconds = (documentStartTime + deltaMilliseconds) / 1000.0;
     return 1000.0 * Performance::reduceTimeResolution(resourceTimeSeconds);
 }

Modified: trunk/Source/WebCore/page/PerformanceResourceTiming.h (204975 => 204976)


--- trunk/Source/WebCore/page/PerformanceResourceTiming.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/page/PerformanceResourceTiming.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -34,6 +34,7 @@
 
 #if ENABLE(WEB_TIMING)
 
+#include "LoadTiming.h"
 #include "NetworkLoadTiming.h"
 #include "PerformanceEntry.h"
 #include <wtf/RefPtr.h>
@@ -49,9 +50,9 @@
 
 class PerformanceResourceTiming final : public PerformanceEntry {
 public:
-    static Ref<PerformanceResourceTiming> create(const AtomicString& initiatorType, const ResourceRequest& request, const ResourceResponse& response, double initiationTime, double finishTime, Document* requestingDocument)
+    static Ref<PerformanceResourceTiming> create(const AtomicString& initiatorType, const URL& originalURL, const ResourceResponse& response, LoadTiming loadTiming, Document* requestingDocument)
     {
-        return adoptRef(*new PerformanceResourceTiming(initiatorType, request, response, initiationTime, finishTime, requestingDocument));
+        return adoptRef(*new PerformanceResourceTiming(initiatorType, originalURL, response, loadTiming, requestingDocument));
     }
 
     AtomicString initiatorType() const;
@@ -65,12 +66,13 @@
     double connectEnd() const;
     double secureConnectionStart() const;
     double requestStart() const;
+    double responseStart() const;
     double responseEnd() const;
 
     bool isResource() const override { return true; }
 
 private:
-    PerformanceResourceTiming(const AtomicString& initatorType, const ResourceRequest&, const ResourceResponse&, double initiationTime, double finishTime, Document*);
+    PerformanceResourceTiming(const AtomicString& initatorType, const URL& originalURL, const ResourceResponse&, LoadTiming, Document*);
     ~PerformanceResourceTiming();
 
     double resourceTimeToDocumentMilliseconds(double deltaMilliseconds) const;
@@ -77,7 +79,7 @@
 
     AtomicString m_initiatorType;
     NetworkLoadTiming m_timing;
-    double m_finishTime;
+    LoadTiming m_loadTiming;
     bool m_shouldReportDetails;
     RefPtr<Document> m_requestingDocument;
 };

Modified: trunk/Source/WebCore/page/PerformanceResourceTiming.idl (204975 => 204976)


--- trunk/Source/WebCore/page/PerformanceResourceTiming.idl	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/page/PerformanceResourceTiming.idl	2016-08-25 18:22:25 UTC (rev 204976)
@@ -44,5 +44,6 @@
     readonly attribute unrestricted double connectEnd;
     readonly attribute unrestricted double secureConnectionStart;
     readonly attribute unrestricted double requestStart;
+    readonly attribute unrestricted double responseStart;
     readonly attribute unrestricted double responseEnd;
 };

Modified: trunk/Source/WebCore/platform/network/NetworkLoadTiming.h (204975 => 204976)


--- trunk/Source/WebCore/platform/network/NetworkLoadTiming.h	2016-08-25 18:21:16 UTC (rev 204975)
+++ trunk/Source/WebCore/platform/network/NetworkLoadTiming.h	2016-08-25 18:22:25 UTC (rev 204976)
@@ -44,7 +44,7 @@
         , secureConnectionStart(-1)
     {
     }
-    
+
     NetworkLoadTiming(const NetworkLoadTiming& other)
         : domainLookupStart(other.domainLookupStart)
         , domainLookupEnd(other.domainLookupEnd)
@@ -55,7 +55,18 @@
         , secureConnectionStart(other.secureConnectionStart)
     {
     }
-    
+
+    void reset()
+    {
+        domainLookupStart = -1;
+        domainLookupEnd = -1;
+        connectStart = -1;
+        connectEnd = -1;
+        requestStart = 0;
+        responseStart = 0;
+        secureConnectionStart = -1;
+    }
+
     NetworkLoadTiming& operator=(const NetworkLoadTiming& other)
     {
         domainLookupStart = other.domainLookupStart;
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to