File: Performance.cpp

package info (click to toggle)
webkit2gtk 2.51.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 455,340 kB
  • sloc: cpp: 3,865,253; javascript: 197,710; ansic: 165,177; python: 49,241; asm: 21,868; ruby: 18,095; perl: 16,926; xml: 4,623; sh: 2,409; yacc: 2,356; java: 2,019; lex: 1,330; pascal: 372; makefile: 210
file content (620 lines) | stat: -rw-r--r-- 22,134 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 * Copyright (C) 2012 Intel Inc. All rights reserved.
 * Copyright (C) 2016 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "Performance.h"

#include "ContextDestructionObserverInlines.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Event.h"
#include "EventCounts.h"
#include "EventLoop.h"
#include "EventNames.h"
#include "ExceptionOr.h"
#include "LargestContentfulPaint.h"
#include "LocalFrame.h"
#include "Logging.h"
#include "PerformanceEntry.h"
#include "PerformanceEventTiming.h"
#include "PerformanceMarkOptions.h"
#include "PerformanceMeasureOptions.h"
#include "PerformanceNavigation.h"
#include "PerformanceNavigationTiming.h"
#include "PerformanceObserver.h"
#include "PerformancePaintTiming.h"
#include "PerformanceResourceTiming.h"
#include "PerformanceTiming.h"
#include "PerformanceUserTiming.h"
#include "ResourceResponse.h"
#include "ScriptExecutionContext.h"
#include "dom/DOMHighResTimeStamp.h"
#include <JavaScriptCore/ProfilerSupport.h>
#include <ranges>
#include <wtf/SystemTracing.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/StringToIntegerConversion.h>

namespace WebCore {

WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(Performance);

static Seconds timePrecision { 1_ms };

static bool isSignpostEnabled()
{
    static bool flag = false;
    static std::once_flag onceKey;
    std::call_once(onceKey, [&] {
        const char* value = getenv("WebKitPerformanceSignpostEnabled");
        if (value) {
            if (auto result = parseInteger<int>(StringView::fromLatin1(value)); result && result.value())
                flag = true;
        }
    });
    return flag;
}

Performance::Performance(ScriptExecutionContext* context, MonotonicTime timeOrigin)
    : ContextDestructionObserver(context)
    , m_resourceTimingBufferFullTimer(*this, &Performance::resourceTimingBufferFullTimerFired) // FIXME: Migrate this to the event loop as well. https://bugs.webkit.org/show_bug.cgi?id=229044
    , m_timeOrigin(timeOrigin)
    , m_continuousTimeOrigin(timeOrigin.approximateContinuousTime())
{
    ASSERT(m_timeOrigin);
}

Performance::~Performance() = default;

void Performance::contextDestroyed()
{
    m_resourceTimingBufferFullTimer.stop();
    ContextDestructionObserver::contextDestroyed();
}

DOMHighResTimeStamp Performance::now() const
{
    return nowInReducedResolutionSeconds().milliseconds();
}

DOMHighResTimeStamp Performance::timeOrigin() const
{
    return reduceTimeResolution(m_timeOrigin.approximateWallTime().secondsSinceEpoch()).milliseconds();
}

ReducedResolutionSeconds Performance::nowInReducedResolutionSeconds() const
{
    Seconds now = MonotonicTime::now() - m_timeOrigin;
    return reduceTimeResolution(now);
}

Seconds Performance::reduceTimeResolution(Seconds seconds)
{
    return seconds.reduceTimeResolution(timePrecision);
}

void Performance::allowHighPrecisionTime()
{
    timePrecision = Seconds::highTimePrecision();
}

Seconds Performance::timeResolution()
{
    return timePrecision;
}

Seconds Performance::relativeTimeFromTimeOriginInReducedResolutionSeconds(MonotonicTime timestamp) const
{
    return reduceTimeResolution(timestamp - m_timeOrigin);
}

DOMHighResTimeStamp Performance::relativeTimeFromTimeOriginInReducedResolution(MonotonicTime timestamp) const
{
    return relativeTimeFromTimeOriginInReducedResolutionSeconds(timestamp).milliseconds();
}

MonotonicTime Performance::monotonicTimeFromRelativeTime(DOMHighResTimeStamp relativeTime) const
{
    return m_timeOrigin + Seconds::fromMilliseconds(relativeTime);
}

ScriptExecutionContext* Performance::scriptExecutionContext() const
{
    return ContextDestructionObserver::scriptExecutionContext();
}

EventCounts* Performance::eventCounts()
{
    if (!is<Document>(scriptExecutionContext()))
        return nullptr;

    ASSERT(isMainThread());
    // FIXME: stop lazy-initializing m_eventCounts after event
    // timing stops being gated by a flag:
    if (!m_eventCounts)
        lazyInitialize(m_eventCounts, makeUniqueWithoutRefCountedCheck<EventCounts>(this));

    return m_eventCounts.get();
}

uint64_t Performance::interactionCount()
{
    ASSERT(is<Document>(scriptExecutionContext()));
    ASSERT(isMainThread());
    return downcast<Document>(*scriptExecutionContext()).window()->interactionCount();
}

PerformanceNavigation* Performance::navigation()
{
    if (!is<Document>(scriptExecutionContext()))
        return nullptr;

    ASSERT(isMainThread());
    if (!m_navigation)
        m_navigation = PerformanceNavigation::create(downcast<Document>(*scriptExecutionContext()).window());
    return m_navigation.get();
}

PerformanceTiming* Performance::timing()
{
    if (!is<Document>(scriptExecutionContext()))
        return nullptr;

    ASSERT(isMainThread());
    if (!m_timing)
        m_timing = PerformanceTiming::create(downcast<Document>(*scriptExecutionContext()).window());
    return m_timing.get();
}

Vector<Ref<PerformanceEntry>> Performance::getEntries() const
{
    Vector<Ref<PerformanceEntry>> entries;

    if (m_navigationTiming)
        entries.append(*m_navigationTiming);

    entries.appendVector(m_resourceTimingBuffer);

    if (m_userTiming) {
        entries.appendVector(m_userTiming->getMarks());
        entries.appendVector(m_userTiming->getMeasures());
    }

    if (m_firstContentfulPaint)
        entries.append(*m_firstContentfulPaint);

    // getEntries should not include largest-contentful-paint.

    if (m_firstInput)
        entries.append(*m_firstInput);

    std::ranges::sort(entries, PerformanceEntry::startTimeCompareLessThan);
    return entries;
}

Vector<Ref<PerformanceEntry>> Performance::getEntriesByType(const String& entryType) const
{
    Vector<Ref<PerformanceEntry>> entries;

    if (m_navigationTiming && entryType == "navigation"_s)
        entries.append(*m_navigationTiming);
    
    if (entryType == "resource"_s)
        entries.appendVector(m_resourceTimingBuffer);

    if (m_firstContentfulPaint && entryType == "paint"_s)
        entries.append(*m_firstContentfulPaint);

    // getEntriesByType should not include largest-contentful-paint.

    if (m_userTiming) {
        if (entryType == "mark"_s)
            entries.appendVector(m_userTiming->getMarks());
        else if (entryType == "measure"_s)
            entries.appendVector(m_userTiming->getMeasures());
    }

    if (entryType == "first-input"_s && m_firstInput)
        entries.append(*m_firstInput);

    std::ranges::sort(entries, PerformanceEntry::startTimeCompareLessThan);
    return entries;
}

Vector<Ref<PerformanceEntry>> Performance::getEntriesByName(const String& name, const String& entryType) const
{
    Vector<Ref<PerformanceEntry>> entries;

    if (m_navigationTiming && (entryType.isNull() || entryType == "navigation"_s) && name == m_navigationTiming->name())
        entries.append(*m_navigationTiming);

    if (entryType.isNull() || entryType == "resource"_s) {
        for (auto& resource : m_resourceTimingBuffer) {
            if (resource->name() == name)
                entries.append(resource);
        }
    }

    if (m_firstContentfulPaint && (entryType.isNull() || entryType == "paint"_s) && name == "first-contentful-paint"_s)
        entries.append(*m_firstContentfulPaint);

    // getEntriesByName should not include largest-contentful-paint.

    if (m_userTiming) {
        if (entryType.isNull() || entryType == "mark"_s)
            entries.appendVector(m_userTiming->getMarks(name));
        if (entryType.isNull() || entryType == "measure"_s)
            entries.appendVector(m_userTiming->getMeasures(name));
    }

    if (entryType.isNull() || entryType == "first-input"_s) {
        if (m_firstInput && name == m_firstInput->name())
            entries.append(*m_firstInput);
    }

    std::ranges::sort(entries, PerformanceEntry::startTimeCompareLessThan);
    return entries;
}

void Performance::appendBufferedEntriesByType(const String& entryType, Vector<Ref<PerformanceEntry>>& entries, PerformanceObserver& observer) const
{
    if (m_navigationTiming && entryType == "navigation"_s && !observer.hasNavigationTiming()) {
        entries.append(*m_navigationTiming);
        observer.addedNavigationTiming();
    }

    if (entryType == "resource"_s)
        entries.appendVector(m_resourceTimingBuffer);

    if (entryType == "paint"_s && m_firstContentfulPaint)
        entries.append(*m_firstContentfulPaint);

    if (entryType == "largest-contentful-paint"_s && m_largestContentfulPaint)
        entries.append(*m_largestContentfulPaint);

    if (entryType == "event"_s)
        entries.appendVector(m_eventTimingBuffer);

    if (entryType == "first-input"_s && m_firstInput)
        entries.append(*m_firstInput);

    if (m_userTiming) {
        if (entryType.isNull() || entryType == "mark"_s)
            entries.appendVector(m_userTiming->getMarks());
        if (entryType.isNull() || entryType == "measure"_s)
            entries.appendVector(m_userTiming->getMeasures());
    }
}

void Performance::countEvent(EventType type)
{
    ASSERT(isMainThread());
    eventCounts()->add(type);
}

void Performance::processEventEntry(const PerformanceEventTimingCandidate& candidate)
{
    // Constants to avoid the need to round to the appropriate resolution
    // (PerformanceEventTiming::durationResolution) when filtering candidates:
    static constexpr Seconds minDurationCutoffBeforeRounding = PerformanceEventTiming::minimumDurationThreshold - (PerformanceEventTiming::durationResolution / 2);
    static constexpr Seconds defaultDurationCutoffBeforeRounding = PerformanceEventTiming::defaultDurationThreshold - (PerformanceEventTiming::durationResolution / 2);

    // The event timing spec requires us to set first-input and call
    // setDispatchedInputEvent() when an entry with nonzero interactionID has
    // its duration set, and only if hasDispatchedInputEvent() is false. This, however,
    // causes inconsistent behavior: a pointerdown event that had its duration assigned
    // before receiving an interactionID wouldn't qualify for first-input.
    //
    // We instead set first-input and call setDispatchedInputEvent() here; ongoing
    // spec discussion at https://github.com/w3c/event-timing/issues/159 :
    if (!m_firstInput && !candidate.interactionID.isUnassigned()) {
        m_firstInput = PerformanceEventTiming::create(candidate, true);
        queueEntry(*m_firstInput);
        if (RefPtr document = dynamicDowncast<Document>(*scriptExecutionContext())) {
            if (RefPtr window = document->window())
                window->setDispatchedInputEvent();
        }
    }

    if (candidate.duration < minDurationCutoffBeforeRounding)
        return;

    // FIXME: early return more often by keeping track of m_observers; we
    // should keep track of the minimum defaultThreshold and whether any
    // observers are interested in 'event' entries:
    if (candidate.duration <= defaultDurationCutoffBeforeRounding && !m_observers.size())
        return;

    auto entry = PerformanceEventTiming::create(candidate);
    if (m_eventTimingBuffer.size() < m_eventTimingBufferSize && candidate.duration > defaultDurationCutoffBeforeRounding)
        m_eventTimingBuffer.append(entry);

    queueEntry(entry);
}

void Performance::clearResourceTimings()
{
    m_resourceTimingBuffer.clear();
    m_resourceTimingBufferFullFlag = false;
}

void Performance::setResourceTimingBufferSize(unsigned size)
{
    m_resourceTimingBufferSize = size;
    m_resourceTimingBufferFullFlag = false;
}

void Performance::reportFirstContentfulPaint(DOMHighResTimeStamp timestamp)
{
    ASSERT(!m_firstContentfulPaint);
    m_firstContentfulPaint = PerformancePaintTiming::createFirstContentfulPaint(timestamp);
    queueEntry(*m_firstContentfulPaint);
}

void Performance::enqueueLargestContentfulPaint(Ref<LargestContentfulPaint>&& paintEntry)
{
    m_largestContentfulPaint = RefPtr { WTFMove(paintEntry) };
    queueEntry(*m_largestContentfulPaint);
}

void Performance::addNavigationTiming(DocumentLoader& documentLoader, Document& document, CachedResource& resource, const DocumentLoadTiming& timing, const NetworkLoadMetrics& metrics)
{
    m_navigationTiming = PerformanceNavigationTiming::create(m_timeOrigin, resource, timing, metrics, document.eventTiming(), document.securityOrigin(), documentLoader.triggeringAction().type());
}

void Performance::documentLoadFinished(const NetworkLoadMetrics& metrics)
{
    if (!m_navigationTiming)
        return;

    m_navigationTiming->documentLoadFinished(metrics);
}

void Performance::navigationFinished(MonotonicTime loadEventEnd)
{
    if (!m_navigationTiming)
        return;

    m_navigationTiming->documentLoadTiming().setLoadEventEnd(loadEventEnd);
    queueEntry(*m_navigationTiming);
}

void Performance::addResourceTiming(ResourceTiming&& resourceTiming)
{
    ASSERT(scriptExecutionContext());

    auto entry = PerformanceResourceTiming::create(m_timeOrigin, WTFMove(resourceTiming));

    if (m_waitingForBackupBufferToBeProcessed) {
        m_backupResourceTimingBuffer.append(WTFMove(entry));
        return;
    }

    if (m_resourceTimingBufferFullFlag) {
        // We fired resourcetimingbufferfull event but the author script didn't clear the buffer.
        // Notify performance observers but don't add it to the buffer.
        queueEntry(entry.get());
        return;
    }

    if (isResourceTimingBufferFull()) {
        ASSERT(!m_resourceTimingBufferFullTimer.isActive());
        m_backupResourceTimingBuffer.append(WTFMove(entry));
        m_waitingForBackupBufferToBeProcessed = true;
        m_resourceTimingBufferFullTimer.startOneShot(0_s);
        return;
    }

    queueEntry(entry.get());
    m_resourceTimingBuffer.append(WTFMove(entry));
}

bool Performance::isResourceTimingBufferFull() const
{
    return m_resourceTimingBuffer.size() >= m_resourceTimingBufferSize;
}

void Performance::resourceTimingBufferFullTimerFired()
{
    ASSERT(scriptExecutionContext());

    while (!m_backupResourceTimingBuffer.isEmpty()) {
        auto beforeCount = m_backupResourceTimingBuffer.size();

        auto backupBuffer = std::exchange(m_backupResourceTimingBuffer, { });
        ASSERT(m_backupResourceTimingBuffer.isEmpty());

        if (isResourceTimingBufferFull()) {
            m_resourceTimingBufferFullFlag = true;
            dispatchEvent(Event::create(eventNames().resourcetimingbufferfullEvent, Event::CanBubble::No, Event::IsCancelable::No));
        }

        if (m_resourceTimingBufferFullFlag) {
            for (auto& entry : backupBuffer)
                queueEntry(entry);
            // Dispatching resourcetimingbufferfull event may have inserted more entries.
            for (auto& entry : std::exchange(m_backupResourceTimingBuffer, { }))
                queueEntry(entry);
            break;
        }

        // More entries may have added while dispatching resourcetimingbufferfull event.
        backupBuffer.appendVector(std::exchange(m_backupResourceTimingBuffer, { }));

        for (auto& entry : backupBuffer) {
            if (!isResourceTimingBufferFull()) {
                m_resourceTimingBuffer.append(entry.copyRef());
                queueEntry(entry);
            } else
                m_backupResourceTimingBuffer.append(entry.copyRef());
        }

        auto afterCount = m_backupResourceTimingBuffer.size();

        if (beforeCount <= afterCount) {
            m_backupResourceTimingBuffer.clear();
            break;
        }
    }
    m_waitingForBackupBufferToBeProcessed = false;
}

ExceptionOr<Ref<PerformanceMark>> Performance::mark(JSC::JSGlobalObject& globalObject, const String& markName, std::optional<PerformanceMarkOptions>&& markOptions)
{
    if (!m_userTiming)
        m_userTiming = makeUnique<PerformanceUserTiming>(*this);

    auto mark = m_userTiming->mark(globalObject, markName, WTFMove(markOptions));
    if (mark.hasException())
        return mark.releaseException();

    queueEntry(mark.returnValue().get());
    return mark.releaseReturnValue();
}

void Performance::clearMarks(const String& markName)
{
    if (!m_userTiming)
        m_userTiming = makeUnique<PerformanceUserTiming>(*this);
    m_userTiming->clearMarks(markName);
}

ExceptionOr<Ref<PerformanceMeasure>> Performance::measure(JSC::JSGlobalObject& globalObject, const String& measureName, std::optional<StartOrMeasureOptions>&& startOrMeasureOptions, const String& endMark)
{
    if (!m_userTiming)
        m_userTiming = makeUnique<PerformanceUserTiming>(*this);

    auto measure = m_userTiming->measure(globalObject, measureName, WTFMove(startOrMeasureOptions), endMark);
    if (measure.hasException())
        return measure.releaseException();

    if (isSignpostEnabled()) {
        Ref entry { measure.returnValue() };
        auto message = measureName.utf8();
#if OS(DARWIN)
        {
            auto startTime = m_continuousTimeOrigin + Seconds::fromMilliseconds(entry->startTime());
            auto endTime = m_continuousTimeOrigin + Seconds::fromMilliseconds(entry->startTime() + entry->duration());
            uint64_t platformStartTime = startTime.toMachContinuousTime();
            uint64_t platformEndTime = endTime.toMachContinuousTime();
            uint64_t correctedStartTime = std::min(platformStartTime, platformEndTime);
            uint64_t correctedEndTime = std::max(platformStartTime, platformEndTime);
            // Because signpost intervals are closed invervals [start, end], we decrease the endTime by 1 if startTime and endTime is not the same.
            if (correctedStartTime != correctedEndTime)
                correctedEndTime -= 1;

            WTFBeginSignpostAlwaysWithSpecificTime(entry.ptr(), WebKitPerformance, correctedStartTime, "%" PUBLIC_LOG_STRING, message.data());
            WTFEndSignpostAlwaysWithSpecificTime(entry.ptr(), WebKitPerformance, correctedEndTime, "%" PUBLIC_LOG_STRING, message.data());
        }
#endif
        {
            auto timeOrigin = m_continuousTimeOrigin.approximateMonotonicTime();
            auto startTime = timeOrigin + Seconds::fromMilliseconds(entry->startTime());
            auto endTime = timeOrigin + Seconds::fromMilliseconds(entry->startTime() + entry->duration());
            JSC::ProfilerSupport::markInterval(entry.ptr(), JSC::ProfilerSupport::Category::WebKitPerformanceSignpost, startTime, endTime, WTFMove(message));
        }
    }

    queueEntry(measure.returnValue().get());
    return measure.releaseReturnValue();
}

void Performance::clearMeasures(const String& measureName)
{
    if (!m_userTiming)
        m_userTiming = makeUnique<PerformanceUserTiming>(*this);
    m_userTiming->clearMeasures(measureName);
}

void Performance::removeAllObservers()
{
    for (auto& observer : m_observers)
        observer->disassociate();
    m_observers.clear();
}

void Performance::registerPerformanceObserver(PerformanceObserver& observer)
{
    m_observers.add(&observer);
}

void Performance::unregisterPerformanceObserver(PerformanceObserver& observer)
{
    m_observers.remove(&observer);
}

void Performance::queueEntry(PerformanceEntry& entry)
{
    bool shouldScheduleTask = false;
    for (auto& observer : m_observers) {
        bool isObserverInterested = observer->typeFilter().contains(entry.performanceEntryType());
        if (entry.performanceEntryType() == PerformanceEntry::Type::Event && entry.duration() < observer->durationThreshold().milliseconds())
            isObserverInterested = false;

        if (entry.performanceEntryType() == PerformanceEntry::Type::Navigation && observer->hasNavigationTiming())
            isObserverInterested = false;

        if (isObserverInterested) {
            observer->queueEntry(entry);
            shouldScheduleTask = true;
        }
    }

    if (!shouldScheduleTask)
        return;

    LOG_WITH_STREAM(PerformanceTimeline, stream << "PerformanceEntry of type " << entry.name() << " dispatched to interested observer at t=" << now());
    scheduleTaskIfNeeded();
}

void Performance::scheduleTaskIfNeeded()
{
    if (m_hasScheduledDeliveryTask)
        return;

    RefPtr context = scriptExecutionContext();
    if (!context)
        return;

    m_hasScheduledDeliveryTask = true;
    context->eventLoop().queueTask(TaskSource::PerformanceTimeline, [protectedThis = Ref { *this }, this] {
        RefPtr context = scriptExecutionContext();
        if (!context)
            return;

        m_hasScheduledDeliveryTask = false;
        for (auto& observer : copyToVector(m_observers))
            observer->deliver();
    });
}

} // namespace WebCore