<!DOCTYPE html>
<html>
<body>
<script src="/resources/js-test-pre.js"></script>
<script>

description('This tests clearing the resource timing buffer during a resourcetimingbufferfull event.<br>'
    + 'WebKit should not hit a release assertion.');

function startTest()
{
    performance.clearResourceTimings();
    shouldBe('performance.getEntriesByType("resource").length', '0');
    evalAndLog('performance.setResourceTimingBufferSize(2)');
    evalAndLog('fetchImages(3).then(checkInitialState)');
}

let resourceIndex = 0;
async function fetchImages(count)
{
    for (let i = 0; i < count; i++, resourceIndex++)
        await fetch(`../../resources/square100.png?resource=${resourceIndex}`);
}

async function checkInitialState()
{
    shouldBe('originalResources = performance.getEntriesByType("resource"); originalResources.length', '2');
    shouldBeEqualToString('originalResources[0].initiatorType', 'fetch');
    shouldBeEqualToString('new URL(originalResources[0].name).search', '?resource=0');
    shouldBeEqualToString('originalResources[1].initiatorType', 'fetch');
    shouldBeEqualToString('new URL(originalResources[1].name).search', '?resource=1');
    shouldBe('resourcetimingbufferfullEventCount', '0');
}

let resourcetimingbufferfullEventCount = 0;
performance.onresourcetimingbufferfull = () => {
    resourcetimingbufferfullEventCount++;
    debug('');
    debug(`Inside resourcetimingbufferfull ${resourcetimingbufferfullEventCount}`);
    if (resourcetimingbufferfullEventCount == 1) {
        evalAndLog('performance.setResourceTimingBufferSize(1)');
        shouldBe('resourcesAfterShrinkingBuffer = performance.getEntriesByType("resource"); resourcesAfterShrinkingBuffer.length', '2');
        shouldBe('resourcesAfterShrinkingBuffer[0]', 'originalResources[0]');
        shouldBe('resourcesAfterShrinkingBuffer[1]', 'originalResources[1]');
        shouldBe('performance.clearResourceTimings(); performance.getEntriesByType("resource").length', '0');
        setTimeout(() => {
            debug('');
            debug('After resourcetimingbufferfull');
            shouldBe('resourcetimingbufferfullEventCount', '1');
            shouldBe('resourcesAfterClearing = performance.getEntriesByType("resource"); resourcesAfterClearing.length', '1');
            shouldBeEqualToString('resourcesAfterClearing[0].initiatorType', 'fetch');
            shouldBeEqualToString('new URL(resourcesAfterClearing[0].name).search', '?resource=2');
            finishJSTest();
        }, 0);
    }
}

var jsTestIsAsync = true;

window.onload = startTest;

</script>
<script src="/resources/js-test-post.js"></script>
</body>
</html>
