File: background_tab_loading_policy.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (684 lines) | stat: -rw-r--r-- 26,297 bytes parent folder | download | duplicates (5)
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/performance_manager/policies/background_tab_loading_policy.h"

#include <vector>

#include "base/check.h"
#include "base/containers/contains.h"
#include "base/metrics/field_trial_params.h"
#include "base/numerics/safe_conversions.h"
#include "base/system/sys_info.h"
#include "base/time/time.h"
#include "base/trace_event/memory_pressure_level_proto.h"
#include "base/trace_event/named_trigger.h"
#include "base/trace_event/typed_macros.h"
#include "chrome/browser/performance_manager/mechanisms/page_loader.h"
#include "chrome/browser/performance_manager/policies/background_tab_loading_policy_helpers.h"
#include "chrome/browser/performance_manager/public/background_tab_loading_policy.h"
#include "chrome/browser/profiles/profile.h"
#include "components/performance_manager/graph/page_node_impl.h"
#include "components/performance_manager/public/decorators/site_data_recorder.h"
#include "components/performance_manager/public/features.h"
#include "components/performance_manager/public/graph/node_data_describer_registry.h"
#include "components/performance_manager/public/performance_manager.h"
#include "components/performance_manager/public/persistence/site_data/site_data_reader.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/site_engagement/core/mojom/site_engagement_details.mojom.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/permission_controller.h"
#include "content/public/browser/permission_descriptor_util.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "url/gurl.h"

namespace performance_manager {

namespace policies {

namespace {

// Pointer to the instance of itself.
BackgroundTabLoadingPolicy* g_background_tab_loading_policy = nullptr;

const char kDescriberName[] = "BackgroundTabLoadingPolicy";

size_t GetSiteEngagementScore(content::WebContents* contents) {
  // Get the active navigation entry. Restored tabs should always have one.
  auto& controller = contents->GetController();
  auto* nav_entry =
      controller.GetEntryAtIndex(controller.GetCurrentEntryIndex());
  DCHECK(nav_entry);

  auto* engagement_svc = site_engagement::SiteEngagementService::Get(
      Profile::FromBrowserContext(contents->GetBrowserContext()));
  double engagement =
      engagement_svc->GetDetails(nav_entry->GetURL()).total_score;

  // Return the engagement as an integer.
  return engagement;
}

}  // namespace

// static
constexpr uint32_t BackgroundTabLoadingPolicy::kMinTabsToLoad;
constexpr uint32_t BackgroundTabLoadingPolicy::kMaxTabsToLoad;
constexpr uint32_t BackgroundTabLoadingPolicy::kDesiredAmountOfFreeMemoryMb;
constexpr base::TimeDelta
    BackgroundTabLoadingPolicy::kMaxTimeSinceLastUseToLoad;
constexpr uint32_t BackgroundTabLoadingPolicy::kMinSimultaneousTabLoads;
constexpr uint32_t BackgroundTabLoadingPolicy::kMaxSimultaneousTabLoads;
constexpr uint32_t BackgroundTabLoadingPolicy::kCoresPerSimultaneousTabLoad;

BackgroundTabLoadingPolicy::PageNodeData::PageNodeData(
    base::WeakPtr<PageNode> page_node,
    GURL main_frame_url,
    blink::mojom::PermissionStatus notification_permission_status)
    : page_node(std::move(page_node)),
      main_frame_url(std::move(main_frame_url)),
      notification_permission_status(notification_permission_status) {}

BackgroundTabLoadingPolicy::PageNodeData::PageNodeData(PageNodeData&& other) =
    default;
BackgroundTabLoadingPolicy::PageNodeData&
BackgroundTabLoadingPolicy::PageNodeData::operator=(PageNodeData&& other) =
    default;
BackgroundTabLoadingPolicy::PageNodeData::PageNodeData(
    const PageNodeData& other) = default;
BackgroundTabLoadingPolicy::PageNodeData&
BackgroundTabLoadingPolicy::PageNodeData::operator=(const PageNodeData& other) =
    default;
BackgroundTabLoadingPolicy::PageNodeData::~PageNodeData() = default;

void ScheduleLoadForRestoredTabs(
    std::vector<content::WebContents*> web_contents_vector) {
  // Trigger a slow-reports and collect a session restore trace if needed.
  base::trace_event::EmitNamedTrigger("session-restore-config");
  TRACE_EVENT("browser", "ScheduleLoadForRestoredTabs", "tabs_count",
              web_contents_vector.size());

  DCHECK(!web_contents_vector.empty());

  std::vector<BackgroundTabLoadingPolicy::PageNodeData> page_node_data_vector;
  page_node_data_vector.reserve(web_contents_vector.size());
  for (content::WebContents* content : web_contents_vector) {
    content::PermissionController* permission_controller =
        content->GetBrowserContext()->GetPermissionController();

    // Cannot use GetPermissionStatusForCurrentDocument() because the navigation
    // hasn't been committed in the RenderFrameHost yet, as evidenced by the
    // DCHECK below.
    DCHECK_EQ(content->GetPrimaryMainFrame()->GetLastCommittedURL(), GURL());
    DCHECK_NE(content->GetLastCommittedURL(), GURL());

    auto permission_descriptor = content::PermissionDescriptorUtil::
        CreatePermissionDescriptorForPermissionType(
            blink::PermissionType::NOTIFICATIONS);
    // Without kBackgroundTabLoadingRestoreMainFrameState, use the incorrect
    // lookup method to get bug-for-bug compatibility with TabLoader.
    // TODO(crbug.com/40121561): Remove this after comparing the performance.
    auto notification_permission =
        features::kBackgroundTabLoadingRestoreMainFrameState.Get()
            ? permission_controller
                  ->GetPermissionResultForOriginWithoutContext(
                      permission_descriptor,
                      url::Origin::Create(content->GetLastCommittedURL()))
                  .status
            : permission_controller->GetPermissionStatusForCurrentDocument(
                  permission_descriptor, content->GetPrimaryMainFrame());

    page_node_data_vector.emplace_back(
        PerformanceManager::GetPrimaryPageNodeForWebContents(content),
        content->GetLastCommittedURL(), notification_permission);
    if (features::kBackgroundTabLoadingMinSiteEngagement.Get() > 0) {
      page_node_data_vector.back().site_engagement =
          GetSiteEngagementScore(content);
    }
  }

  BackgroundTabLoadingPolicy::GetInstance()->ScheduleLoadForRestoredTabs(
      std::move(page_node_data_vector));
}

BackgroundTabLoadingPolicy::BackgroundTabLoadingPolicy(
    base::RepeatingClosure all_restored_tabs_loaded_callback)
    : all_restored_tabs_loaded_callback_(
          std::move(all_restored_tabs_loaded_callback)),
      page_loader_(std::make_unique<mechanism::PageLoader>()) {
  DCHECK(!g_background_tab_loading_policy);
  g_background_tab_loading_policy = this;
  max_simultaneous_tab_loads_ = CalculateMaxSimultaneousTabLoads(
      kMinSimultaneousTabLoads, kMaxSimultaneousTabLoads,
      kCoresPerSimultaneousTabLoad, base::SysInfo::NumberOfProcessors());
}

BackgroundTabLoadingPolicy::~BackgroundTabLoadingPolicy() {
  DCHECK_EQ(this, g_background_tab_loading_policy);
  g_background_tab_loading_policy = nullptr;
}

void BackgroundTabLoadingPolicy::OnPassedToGraph(Graph* graph) {
  graph->AddPageNodeObserver(this);
  graph->AddSystemNodeObserver(this);
  graph->GetNodeDataDescriberRegistry()->RegisterDescriber(this,
                                                           kDescriberName);
}

void BackgroundTabLoadingPolicy::OnTakenFromGraph(Graph* graph) {
  graph->GetNodeDataDescriberRegistry()->UnregisterDescriber(this);
  graph->RemoveSystemNodeObserver(this);
  graph->RemovePageNodeObserver(this);
}

void BackgroundTabLoadingPolicy::OnLoadingStateChanged(
    const PageNode* page_node,
    PageNode::LoadingState previous_state) {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::OnLoadingStateChanged");
  DCHECK_EQ(has_restored_tabs_to_load_, HasRestoredTabsToLoad());

  switch (page_node->GetLoadingState()) {
    // Loading is complete or stalled.
    case PageNode::LoadingState::kLoadingNotStarted:
    case PageNode::LoadingState::kLoadedIdle:
    case PageNode::LoadingState::kLoadingTimedOut:

    {
      // Stop tracking the page within this policy.
      RemovePageNode(page_node);

      // Since there might be a free loading slot, attempt to load more tabs.
      MaybeLoadSomeTabs();

      return;
    }

    // Loading starts.
    case PageNode::LoadingState::kLoading: {
      if (previous_state == PageNode::LoadingState::kLoadedBusy) {
        // The PageNode remained in |page_nodes_loading_| when it transitioned
        // from |kLoading| to |kLoadedBusy|, so no change is necessary when it
        // transitions back to |kLoading|.
        DCHECK(base::Contains(page_nodes_loading_, page_node));
        DCHECK(!base::Contains(page_nodes_load_initiated_, page_node));
        DCHECK(!FindPageNodeToLoadData(page_node));
        return;
      }

      // The PageNode started loading because of this policy or because of
      // external factors (e.g. user-initiated). In either case, remove the
      // PageNode from the set of PageNodes for which a load needs to be
      // initiated and from the set of PageNodes for which a load has been
      // initiated but hasn't started.
      const bool erased =
          ErasePageNodeToLoadData(page_node) ||
          std::erase(page_nodes_load_initiated_, page_node) != 0;

      // Keep track of all PageNodes that are loading, even when the load isn't
      // initiated by this policy.
      DCHECK(!base::Contains(page_nodes_loading_, page_node));
      page_nodes_loading_.emplace(page_node, erased);

      return;
    }

    // Loading is progressing.
    case PageNode::LoadingState::kLoadedBusy: {
      // The PageNode should have been added to |page_nodes_loading_| when it
      // transitioned to |kLoading|.
      DCHECK(base::Contains(page_nodes_loading_, page_node));
      DCHECK(!base::Contains(page_nodes_load_initiated_, page_node));
      DCHECK(!FindPageNodeToLoadData(page_node));
      return;
    }
  }
}

void BackgroundTabLoadingPolicy::OnBeforePageNodeRemoved(
    const PageNode* page_node) {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::OnBeforePageNodeRemoved");
  RemovePageNode(page_node);

  // There may be free loading slots, check and load more tabs if that's the
  // case.
  MaybeLoadSomeTabs();
}

void BackgroundTabLoadingPolicy::ScheduleLoadForRestoredTabs(
    std::vector<BackgroundTabLoadingPolicy::PageNodeData>
        page_node_data_vector) {
  has_restored_tabs_to_load_ = true;

  const size_t page_nodes_to_load_initial_size = page_nodes_to_load_.size();

  for (const auto& page_node_data : page_node_data_vector) {
    PageNode* page_node = page_node_data.page_node.get();
    if (!page_node)
      continue;

    DCHECK_EQ(page_node->GetType(), PageType::kTab);
    DCHECK(!FindPageNodeToLoadData(page_node));
    DCHECK(!base::Contains(page_nodes_load_initiated_, page_node));

    // Setting main frame restored state ensures that the notification
    // permission status and background title/favicon update properties are set
    // correctly when `ScoreTab` scores the page.
    // TODO(crbug.com/40121561): Remove the feature check after comparing the
    // performance to TabLoader, which lacks this call.
    if (features::kBackgroundTabLoadingRestoreMainFrameState.Get()) {
      PageNodeImpl::FromNode(page_node)->SetMainFrameRestoredState(
          page_node_data.main_frame_url,
          page_node_data.notification_permission_status);
    }

    // No need to schedule a load if the page is already loading.
    if (base::Contains(page_nodes_loading_, page_node)) {
      // Track that this policy was responsible for scheduling the load.
      page_nodes_loading_[page_node] = true;
      continue;
    }

    // Put the page in the queue for loading.
    page_nodes_to_load_.push_back(std::make_unique<PageNodeToLoadData>(
        page_node, page_node_data.site_engagement));
  }

  // Asynchronously determine whether pages added to `page_nodes_to_load_` are
  // used in background. Do this after all pages have been added to
  // `page_nodes_to_load_`, otherwise the policy may start loading pages without
  // knowing about all the tabs that must be loaded (see
  // `OnUsedInBackgroundAvailable()`).
  for (size_t i = page_nodes_to_load_initial_size;
       i < page_nodes_to_load_.size(); ++i) {
    SetUsedInBackgroundAsync(page_nodes_to_load_[i].get());
  }

  // All restored tabs may be loaded.
  UpdateHasRestoredTabsToLoad();
}

void BackgroundTabLoadingPolicy::SetMockLoaderForTesting(
    std::unique_ptr<mechanism::PageLoader> loader) {
  page_loader_ = std::move(loader);
}

void BackgroundTabLoadingPolicy::SetMaxSimultaneousLoadsForTesting(
    size_t loading_slots) {
  max_simultaneous_tab_loads_ = loading_slots;
}

void BackgroundTabLoadingPolicy::SetFreeMemoryForTesting(
    size_t free_memory_mb) {
  free_memory_mb_for_testing_ = free_memory_mb;
}

void BackgroundTabLoadingPolicy::ResetPolicyForTesting() {
  tab_loads_started_ = 0;
}

BackgroundTabLoadingPolicy* BackgroundTabLoadingPolicy::GetInstance() {
  return g_background_tab_loading_policy;
}

BackgroundTabLoadingPolicy::PageNodeToLoadData::PageNodeToLoadData(
    const PageNode* page_node,
    std::optional<size_t> site_engagement)
    : page_node(page_node), site_engagement(site_engagement) {}

BackgroundTabLoadingPolicy::PageNodeToLoadData::~PageNodeToLoadData() = default;

bool BackgroundTabLoadingPolicy::PageNodeToLoadData::
    UsesBackgroundCommunication() const {
  return page_node->GetNotificationPermissionStatus() ==
             blink::mojom::PermissionStatus::GRANTED ||
         updates_title_or_favicon_in_bg.value();
}

struct BackgroundTabLoadingPolicy::ScoredTabComparator {
  bool operator()(const std::unique_ptr<PageNodeToLoadData>& tab0,
                  const std::unique_ptr<PageNodeToLoadData>& tab1) {
    DCHECK(tab0->score.has_value());
    DCHECK(tab1->score.has_value());
    // Greater scores sort first.
    return tab0->score > tab1->score;
  }
};

base::Value::Dict BackgroundTabLoadingPolicy::DescribePageNodeData(
    const PageNode* node) const {
  base::Value::Dict dict;
  if (base::Contains(page_nodes_load_initiated_, node)) {
    // Transient state between InitiateLoad() and OnLoadingStateChanged(),
    // shouldn't be sticking around for long.
    dict.Set("page_load_initiated", true);
  }
  if (base::Contains(page_nodes_loading_, node)) {
    dict.Set("page_loading", true);
  }
  return !dict.empty() ? std::move(dict) : base::Value::Dict();
}

base::Value::Dict BackgroundTabLoadingPolicy::DescribeSystemNodeData(
    const SystemNode* node) const {
  base::Value::Dict dict;
  dict.Set("max_simultaneous_tab_loads",
           base::saturated_cast<int>(max_simultaneous_tab_loads_));
  dict.Set("tab_loads_started", base::saturated_cast<int>(tab_loads_started_));
  dict.Set("tabs_scored", base::saturated_cast<int>(tabs_scored_));
  return dict;
}

bool BackgroundTabLoadingPolicy::ShouldLoad(
    const PageNodeToLoadData& page_node_data) {
  if (tab_loads_started_ < kMinTabsToLoad)
    return true;

  if (tab_loads_started_ >= kMaxTabsToLoad)
    return false;

  // If there is a free memory constraint then enforce it.
  size_t free_memory_mb = GetFreePhysicalMemoryMib();
  if (free_memory_mb < kDesiredAmountOfFreeMemoryMb)
    return false;

  // Enforce a max time since last use.
  const base::TimeDelta time_since_last_visibility_change =
      base::TimeTicks::Now() -
      page_node_data.page_node->GetLastVisibilityChangeTime();
  if (time_since_last_visibility_change > kMaxTimeSinceLastUseToLoad) {
    return false;
  }

  // Enforce a minimum site engagement score if applicable.
  // Only enforce the site engagement score for tabs that don't make use of
  // background communication mechanisms. These sites often have low engagements
  // because they are only used very sporadically, but it is important that they
  // are loaded because if not loaded the user can miss important messages.
  const size_t min_site_engagement =
      features::kBackgroundTabLoadingMinSiteEngagement.Get();
  if (!page_node_data.UsesBackgroundCommunication() &&
      page_node_data.site_engagement.value_or(min_site_engagement) <
          min_site_engagement) {
    return false;
  }

  return true;
}

void BackgroundTabLoadingPolicy::OnUsedInBackgroundAvailable(
    base::WeakPtr<PageNode> page_node) {
  TRACE_EVENT("browser",
              "BackgroundTabLoadingPolicy::OnUsedInBackgroundAvailable");
  if (!page_node) {
    // Ignore the value if the PageNode was deleted.
    return;
  }
  PageNodeToLoadData* page_node_to_load_data =
      FindPageNodeToLoadData(page_node.get());
  if (!page_node_to_load_data) {
    // Ignore the value if the PageNode is no longer in the list of PageNodes to
    // load (it may already have started loading).
    return;
  }

  SiteDataReader* reader = GetSiteDataReader(page_node.get());

  // A tab can't play audio until it has been visible at least once so
  // UsesAudioInBackground() is ignored.
  page_node_to_load_data->updates_title_or_favicon_in_bg =
      reader && (reader->UpdatesFaviconInBackground() !=
                     SiteFeatureUsage::kSiteFeatureNotInUse ||
                 reader->UpdatesTitleInBackground() !=
                     SiteFeatureUsage::kSiteFeatureNotInUse);

  ScoreTab(page_node_to_load_data);
  DispatchNotifyAllTabsScoredIfNeeded();
}

void BackgroundTabLoadingPolicy::StopLoadingTabs() {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::StopLoadingTabs");
  // Clear out the remaining tabs to load and clean ourselves up.
  page_nodes_to_load_.clear();
  tabs_scored_ = 0;

  // TODO(crbug.com/40126598): Interrupt all ongoing loads.

  // All restored tabs may be loaded.
  UpdateHasRestoredTabsToLoad();
}

void BackgroundTabLoadingPolicy::OnMemoryPressure(
    base::MemoryPressureListener::MemoryPressureLevel new_level) {
  TRACE_EVENT_INSTANT(
      "browser", "BackgroundTabLoadingPolicy::OnMemoryPressure",
      [&](perfetto::EventContext ctx) {
        auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
        auto* data = event->set_chrome_memory_pressure_notification();
        data->set_level(
            base::trace_event::MemoryPressureLevelToTraceEnum(new_level));
      });
  switch (new_level) {
    case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE:
      break;
    case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE:
    case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL:
      StopLoadingTabs();
      break;
  }
}

SiteDataReader* BackgroundTabLoadingPolicy::GetSiteDataReader(
    const PageNode* page_node) const {
  return SiteDataRecorder::Data::GetReaderForPageNode(page_node);
}

void BackgroundTabLoadingPolicy::ScoreTab(
    PageNodeToLoadData* page_node_to_load_data) {
  DCHECK(!page_node_to_load_data->score.has_value());
  float score = 0.0f;

  // Give higher priorities to tabs used in the background, and lowest
  // priority to internal tabs. Apps and pinned tabs are simply treated as
  // normal tabs.
  if (page_node_to_load_data->UsesBackgroundCommunication()) {
    score = 2;
  } else if (!page_node_to_load_data->page_node->GetMainFrameUrl().SchemeIs(
                 content::kChromeUIScheme)) {
    score = 1;
  }

  // Refine the score using the age of the tab. More recently used tabs have
  // higher scores.
  const base::TimeDelta time_since_last_visibility_change =
      base::TimeTicks::Now() -
      page_node_to_load_data->page_node->GetLastVisibilityChangeTime();
  score += CalculateAgeScore(time_since_last_visibility_change.InSecondsF());

  ++tabs_scored_;
  page_node_to_load_data->score = score;
}

void BackgroundTabLoadingPolicy::SetUsedInBackgroundAsync(
    PageNodeToLoadData* page_node_to_load_data) {
  const PageNode* page_node = page_node_to_load_data->page_node.get();
  SiteDataReader* reader = GetSiteDataReader(page_node);
  auto callback =
      base::BindOnce(&BackgroundTabLoadingPolicy::OnUsedInBackgroundAvailable,
                     weak_factory_.GetWeakPtr(),
                     PageNodeImpl::FromNode(page_node)->GetWeakPtr());

  // The tab won't have a reader if it doesn't have an URL tracked in the
  // site data database.
  if (!reader) {
    std::move(callback).Run();
    return;
  }

  reader->RegisterDataLoadedCallback(std::move(callback));
}

void BackgroundTabLoadingPolicy::DispatchNotifyAllTabsScoredIfNeeded() {
  if (tabs_scored_ == page_nodes_to_load_.size()) {
    NotifyAllTabsScored();
  }
}

void BackgroundTabLoadingPolicy::NotifyAllTabsScored() {
  std::stable_sort(page_nodes_to_load_.begin(), page_nodes_to_load_.end(),
                   ScoredTabComparator());
  MaybeLoadSomeTabs();
}

void BackgroundTabLoadingPolicy::InitiateLoad(const PageNode* page_node) {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::InitiateLoad");
  // The page shouldn't already be loading.
  DCHECK(!base::Contains(page_nodes_load_initiated_, page_node));
  DCHECK(!base::Contains(page_nodes_loading_, page_node));

  // Mark |page_node| as load initiated. Ensure that InitiateLoad is only called
  // for a PageNode that is tracked by the policy.
  ErasePageNodeToLoadData(page_node);
  DCHECK(!FindPageNodeToLoadData(page_node));
  page_nodes_load_initiated_.push_back(page_node);
  tab_loads_started_++;

  // Make the call to load |page_node|.
  page_loader_->LoadPageNode(page_node);
}

void BackgroundTabLoadingPolicy::RemovePageNode(const PageNode* page_node) {
  ErasePageNodeToLoadData(page_node);
  std::erase(page_nodes_load_initiated_, page_node);
  page_nodes_loading_.erase(page_node);

  // All restored tabs may be loaded.
  UpdateHasRestoredTabsToLoad();
}

void BackgroundTabLoadingPolicy::MaybeLoadSomeTabs() {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::MaybeLoadSomeTabs");
  // Continue to load tabs while possible. This is in a loop with a
  // recalculation of GetMaxNewTabLoads() as reentrancy can cause conditions
  // to change as each tab load is initiated.
  while (GetMaxNewTabLoads() > 0)
    LoadNextTab();

  // All restored tabs may be loaded.
  UpdateHasRestoredTabsToLoad();
}

size_t BackgroundTabLoadingPolicy::GetMaxNewTabLoads() const {
  // Can't load tabs until all tabs have been scored.
  if (tabs_scored_ < page_nodes_to_load_.size())
    return 0U;

  // This takes into account all tabs currently loading across the browser,
  // including ones that BackgroundTabLoadingPolicy isn't explicitly managing.
  // This ensures that BackgroundTabLoadingPolicy respects user interaction
  // first and foremost. There's a small race between when we initiated loading
  // and when PageNodeObserver notifies us that it has actually started, so we
  // also make use of |page_nodes_initiated_| to track these.
  size_t loading_tab_count =
      page_nodes_load_initiated_.size() + page_nodes_loading_.size();

  // Determine the number of free loading slots available.
  size_t page_nodes_to_load = 0;
  if (loading_tab_count < max_simultaneous_tab_loads_)
    page_nodes_to_load = max_simultaneous_tab_loads_ - loading_tab_count;

  // Cap the number of loads by the actual number of tabs remaining.
  page_nodes_to_load = std::min(page_nodes_to_load, page_nodes_to_load_.size());

  return page_nodes_to_load;
}

void BackgroundTabLoadingPolicy::LoadNextTab() {
  TRACE_EVENT("browser", "BackgroundTabLoadingPolicy::LoadNextTab");
  DCHECK(!page_nodes_to_load_.empty());
  DCHECK_EQ(tabs_scored_, page_nodes_to_load_.size());

  // Find the next PageNode to load.
  while (!page_nodes_to_load_.empty()) {
    const PageNode* page_node = page_nodes_to_load_.front()->page_node;
    if (ShouldLoad(*page_nodes_to_load_.front())) {
      InitiateLoad(page_node);
      return;
    }

    // |page_node| should not be loaded at this time. Remove |page_node| from
    // the policy.
    ErasePageNodeToLoadData(page_node);
  }
}

size_t BackgroundTabLoadingPolicy::GetFreePhysicalMemoryMib() const {
  if (free_memory_mb_for_testing_ != 0)
    return free_memory_mb_for_testing_;
  constexpr uint64_t kMibibytesInBytes = 1 << 20;
  return base::SysInfo::AmountOfAvailablePhysicalMemory() / kMibibytesInBytes;
}

bool BackgroundTabLoadingPolicy::ErasePageNodeToLoadData(
    const PageNode* page_node) {
  for (auto& page_node_to_load_data : page_nodes_to_load_) {
    if (page_node_to_load_data->page_node == page_node) {
      if (page_node_to_load_data->score.has_value()) {
        // If the PageNode has already been scored, remove it from the
        // |tabs_scored_| count.
        DCHECK_GT(tabs_scored_, 0U);
        --tabs_scored_;
        std::erase(page_nodes_to_load_, page_node_to_load_data);
      } else {
        std::erase(page_nodes_to_load_, page_node_to_load_data);

        // If the PageNode has not been scored yet, then removing it may trigger
        // all tabs scored notification.
        DispatchNotifyAllTabsScoredIfNeeded();
      }
      return true;
    }
  }
  return false;
}

BackgroundTabLoadingPolicy::PageNodeToLoadData*
BackgroundTabLoadingPolicy::FindPageNodeToLoadData(const PageNode* page_node) {
  for (auto& page_node_to_load_data : page_nodes_to_load_) {
    if (page_node_to_load_data->page_node == page_node) {
      return page_node_to_load_data.get();
    }
  }
  return nullptr;
}

bool BackgroundTabLoadingPolicy::HasRestoredTabsToLoad() const {
  if (!page_nodes_to_load_.empty())
    return true;
  if (!page_nodes_load_initiated_.empty())
    return true;
  for (const auto& [_, load_initiated_by_this] : page_nodes_loading_) {
    if (load_initiated_by_this)
      return true;
  }
  return false;
}

void BackgroundTabLoadingPolicy::UpdateHasRestoredTabsToLoad() {
  if (!has_restored_tabs_to_load_) {
    DCHECK(!HasRestoredTabsToLoad());
    return;
  }
  if (HasRestoredTabsToLoad())
    return;
  has_restored_tabs_to_load_ = false;
  all_restored_tabs_loaded_callback_.Run();
}

}  // namespace policies

}  // namespace performance_manager