File: optimization_guide_top_host_provider.cc

package info (click to toggle)
chromium 89.0.4389.114-1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,388,476 kB
  • sloc: cpp: 19,561,380; javascript: 2,952,268; ansic: 2,261,795; python: 1,396,668; xml: 560,542; java: 490,481; asm: 463,723; objc: 83,151; perl: 76,810; sh: 76,375; cs: 70,715; fortran: 24,137; tcl: 18,916; php: 18,872; makefile: 16,870; ruby: 16,721; pascal: 13,150; sql: 9,521; yacc: 7,497; lex: 1,985; lisp: 840; awk: 190; jsp: 39; sed: 19
file content (359 lines) | stat: -rw-r--r-- 14,997 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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/optimization_guide/optimization_guide_top_host_provider.h"

#include <algorithm>

#include "base/metrics/histogram_macros.h"
#include "base/time/default_clock.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "components/optimization_guide/core/hints_processing_util.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/core/optimization_guide_permissions_util.h"
#include "components/optimization_guide/core/optimization_guide_prefs.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/site_engagement/content/site_engagement_score.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_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"

namespace {

// Returns true if hints can't be fetched for |host|.
bool IsHostBlacklisted(const base::DictionaryValue* top_host_blacklist,
                       const std::string& host) {
  if (!top_host_blacklist)
    return false;
  return top_host_blacklist->FindKey(
      optimization_guide::HashHostForDictionary(host));
}

// Return the current state of the HintsFetcherTopHostBlacklist held in the
// |kHintsFetcherTopHostBlacklistState| pref.
optimization_guide::prefs::HintsFetcherTopHostBlacklistState
GetCurrentBlacklistState(PrefService* pref_service) {
  return static_cast<
      optimization_guide::prefs::HintsFetcherTopHostBlacklistState>(
      pref_service->GetInteger(
          optimization_guide::prefs::kHintsFetcherTopHostBlacklistState));
}

// Updates the state of the HintsFetcherTopHostBlacklist to |new_state|.
void UpdateCurrentBlacklistState(
    PrefService* pref_service,
    optimization_guide::prefs::HintsFetcherTopHostBlacklistState new_state) {
  optimization_guide::prefs::HintsFetcherTopHostBlacklistState current_state =
      GetCurrentBlacklistState(pref_service);
  DCHECK_EQ(
      new_state == optimization_guide::prefs::
                       HintsFetcherTopHostBlacklistState::kInitialized,
      current_state == optimization_guide::prefs::
                           HintsFetcherTopHostBlacklistState::kNotInitialized &&
          new_state == optimization_guide::prefs::
                           HintsFetcherTopHostBlacklistState::kInitialized);

  DCHECK_EQ(
      new_state ==
          optimization_guide::prefs::HintsFetcherTopHostBlacklistState::kEmpty,
      current_state == optimization_guide::prefs::
                           HintsFetcherTopHostBlacklistState::kInitialized &&
          new_state == optimization_guide::prefs::
                           HintsFetcherTopHostBlacklistState::kEmpty);

  // Any state can go to not initialized, so no need to check here.

  if (current_state == new_state)
    return;

  // TODO(mcrouse): Add histogram to record the blacklist state change.
  pref_service->SetInteger(
      optimization_guide::prefs::kHintsFetcherTopHostBlacklistState,
      static_cast<int>(new_state));
}

// Resets the state of the HintsFetcherTopHostBlacklist held in the
// kHintsFetcherTopHostBlacklistState| pref to
// |optimization_guide::prefs::HintsFetcherTopHostBlacklistState::kNotInitialized|.
void ResetTopHostBlacklistState(PrefService* pref_service) {
  if (GetCurrentBlacklistState(pref_service) ==
      optimization_guide::prefs::HintsFetcherTopHostBlacklistState::
          kNotInitialized) {
    return;
  }
  DictionaryPrefUpdate blacklist_pref(
      pref_service, optimization_guide::prefs::kHintsFetcherTopHostBlacklist);
  blacklist_pref->Clear();
  UpdateCurrentBlacklistState(
      pref_service, optimization_guide::prefs::
                        HintsFetcherTopHostBlacklistState::kNotInitialized);
}

}  // namespace

// static
std::unique_ptr<OptimizationGuideTopHostProvider>
OptimizationGuideTopHostProvider::CreateIfAllowed(
    content::BrowserContext* browser_context) {
  Profile* profile = Profile::FromBrowserContext(browser_context);
  if (optimization_guide::IsUserPermittedToFetchFromRemoteOptimizationGuide(
          profile->IsOffTheRecord(), profile->GetPrefs())) {
    return base::WrapUnique(new OptimizationGuideTopHostProvider(
        browser_context, base::DefaultClock::GetInstance()));
  }
  return nullptr;
}

OptimizationGuideTopHostProvider::OptimizationGuideTopHostProvider(
    content::BrowserContext* browser_context,
    base::Clock* time_clock)
    : browser_context_(browser_context),
      time_clock_(time_clock),
      pref_service_(Profile::FromBrowserContext(browser_context_)->GetPrefs()) {
}

OptimizationGuideTopHostProvider::~OptimizationGuideTopHostProvider() {}

void OptimizationGuideTopHostProvider::
    InitializeHintsFetcherTopHostBlacklist() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(browser_context_);
  DCHECK_EQ(GetCurrentBlacklistState(pref_service_),
            optimization_guide::prefs::HintsFetcherTopHostBlacklistState::
                kNotInitialized);
  DCHECK(pref_service_
             ->GetDictionary(
                 optimization_guide::prefs::kHintsFetcherTopHostBlacklist)
             ->empty());

  Profile* profile = Profile::FromBrowserContext(browser_context_);
  auto* engagement_service =
      site_engagement::SiteEngagementService::Get(profile);

  std::unique_ptr<base::DictionaryValue> top_host_blacklist =
      std::make_unique<base::DictionaryValue>();

  std::vector<site_engagement::mojom::SiteEngagementDetails>
      engagement_details = engagement_service->GetAllDetails();

  std::sort(engagement_details.begin(), engagement_details.end(),
            [](const site_engagement::mojom::SiteEngagementDetails& lhs,
               const site_engagement::mojom::SiteEngagementDetails& rhs) {
              return lhs.total_score > rhs.total_score;
            });

  pref_service_->SetDouble(
      optimization_guide::prefs::
          kTimeHintsFetcherTopHostBlacklistLastInitialized,
      time_clock_->Now().ToDeltaSinceWindowsEpoch().InSecondsF());

  // Set the minimum engagement score to -1.0f. This ensures that in the default
  // case (where the blacklist size is enough to accommodate all hosts from the
  // site engagement service), a threshold on the minimum site engagement score
  // does not disqualify |this| from requesting hints for any host.
  pref_service_->SetDouble(
      optimization_guide::prefs::
          kHintsFetcherTopHostBlacklistMinimumEngagementScore,
      -1.0f);

  for (const auto& detail : engagement_details) {
    if (!detail.origin.SchemeIsHTTPOrHTTPS())
      continue;
    if (top_host_blacklist->size() >=
        optimization_guide::features::MaxHintsFetcherTopHostBlacklistSize()) {
      // Set the minimum engagement score to the score of the host that
      // could not be added to  |top_host_blacklist|. Add a small epsilon value
      // to the threshold so that any host with score equal to or less than
      // the threshold is not included in the hints fetcher request.
      pref_service_->SetDouble(
          optimization_guide::prefs::
              kHintsFetcherTopHostBlacklistMinimumEngagementScore,
          std::min(detail.total_score + 0.001f,
                   optimization_guide::features::
                       MinTopHostEngagementScoreThreshold()));
      break;
    }
    top_host_blacklist->SetBoolKey(
        optimization_guide::HashHostForDictionary(detail.origin.host()), true);
  }

  UMA_HISTOGRAM_COUNTS_1000(
      "OptimizationGuide.HintsFetcher.TopHostProvider.BlacklistSize."
      "OnInitialize",
      top_host_blacklist->size());

  pref_service_->Set(optimization_guide::prefs::kHintsFetcherTopHostBlacklist,
                     *top_host_blacklist);

  UpdateCurrentBlacklistState(
      pref_service_, optimization_guide::prefs::
                         HintsFetcherTopHostBlacklistState::kInitialized);
}

// static
void OptimizationGuideTopHostProvider::MaybeUpdateTopHostBlacklist(
    content::NavigationHandle* navigation_handle) {
  if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
    return;

  Profile* profile = Profile::FromBrowserContext(
      navigation_handle->GetWebContents()->GetBrowserContext());

  // Do not update the top host list if the profile is off the record.
  if (profile->IsOffTheRecord())
    return;

  PrefService* pref_service = profile->GetPrefs();

  bool is_user_permitted_to_fetch_hints =
      optimization_guide::IsUserPermittedToFetchFromRemoteOptimizationGuide(
          profile->IsOffTheRecord(), pref_service);
  if (!is_user_permitted_to_fetch_hints) {
    // User toggled state during the session. Make sure the blacklist is
    // cleared.
    ResetTopHostBlacklistState(pref_service);
    return;
  }
  DCHECK(is_user_permitted_to_fetch_hints);

  // Only proceed to update the blacklist if we have a blacklist to update.
  if (GetCurrentBlacklistState(pref_service) !=
      optimization_guide::prefs::HintsFetcherTopHostBlacklistState::
          kInitialized) {
    return;
  }

  DictionaryPrefUpdate blacklist_pref(
      pref_service, optimization_guide::prefs::kHintsFetcherTopHostBlacklist);
  if (!blacklist_pref->FindKey(optimization_guide::HashHostForDictionary(
          navigation_handle->GetURL().host()))) {
    return;
  }
  blacklist_pref->RemovePath(optimization_guide::HashHostForDictionary(
      navigation_handle->GetURL().host()));
  if (blacklist_pref->empty()) {
    blacklist_pref->Clear();
    pref_service->SetInteger(
        optimization_guide::prefs::kHintsFetcherTopHostBlacklistState,
        static_cast<int>(optimization_guide::prefs::
                             HintsFetcherTopHostBlacklistState::kEmpty));
  }
}

std::vector<std::string> OptimizationGuideTopHostProvider::GetTopHosts() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(browser_context_);
  DCHECK(pref_service_);

  Profile* profile = Profile::FromBrowserContext(browser_context_);

  // The user toggled state during the session. Return empty.
  if (!optimization_guide::IsUserPermittedToFetchFromRemoteOptimizationGuide(
          profile->IsOffTheRecord(), pref_service_))
    return std::vector<std::string>();

  // It's possible that the blacklist is initialized but
  // kTimeHintsFetcherTopHostBlacklistLastInitialized pref is not populated.
  // This may happen since the logic to populate
  // kTimeHintsFetcherTopHostBlacklistLastInitialized pref was added in a later
  // Chrome version. In that case, set
  // kTimeHintsFetcherTopHostBlacklistLastInitialized to the conservative value
  // of current time.
  if (pref_service_->GetDouble(
          optimization_guide::prefs::
              kTimeHintsFetcherTopHostBlacklistLastInitialized) == 0) {
    pref_service_->SetDouble(
        optimization_guide::prefs::
            kTimeHintsFetcherTopHostBlacklistLastInitialized,
        time_clock_->Now().ToDeltaSinceWindowsEpoch().InSecondsF());
  }

  if (GetCurrentBlacklistState(pref_service_) ==
      optimization_guide::prefs::HintsFetcherTopHostBlacklistState::
          kNotInitialized) {
    InitializeHintsFetcherTopHostBlacklist();
    return std::vector<std::string>();
  }

  // Create SiteEngagementService to request site engagement scores.
  auto* engagement_service =
      site_engagement::SiteEngagementService::Get(profile);

  const base::DictionaryValue* top_host_blacklist = nullptr;
  if (GetCurrentBlacklistState(pref_service_) !=
      optimization_guide::prefs::HintsFetcherTopHostBlacklistState::kEmpty) {
    top_host_blacklist = pref_service_->GetDictionary(
        optimization_guide::prefs::kHintsFetcherTopHostBlacklist);
    UMA_HISTOGRAM_COUNTS_1000(
        "OptimizationGuide.HintsFetcher.TopHostProvider.BlacklistSize."
        "OnRequest",
        top_host_blacklist->size());
    // This check likely should not be needed as the process of removing hosts
    // from the blacklist should check and update the pref state.
    if (top_host_blacklist->size() == 0) {
      UpdateCurrentBlacklistState(
          pref_service_,
          optimization_guide::prefs::HintsFetcherTopHostBlacklistState::kEmpty);
      top_host_blacklist = nullptr;
    }
  }

  std::vector<std::string> top_hosts;

  // Create a vector of the top hosts by engagement score up to |max_sites|
  // size. Currently utilizes just the first |max_sites| entries. Only HTTPS
  // schemed hosts are included. Hosts are filtered by the blacklist that is
  // populated when DataSaver is first enabled.
  std::vector<site_engagement::mojom::SiteEngagementDetails>
      engagement_details = engagement_service->GetAllDetails();

  std::sort(engagement_details.begin(), engagement_details.end(),
            [](const site_engagement::mojom::SiteEngagementDetails& lhs,
               const site_engagement::mojom::SiteEngagementDetails& rhs) {
              return lhs.total_score > rhs.total_score;
            });

  base::Time blacklist_initialized_time =
      base::Time::FromDeltaSinceWindowsEpoch(
          base::TimeDelta::FromSecondsD(pref_service_->GetDouble(
              optimization_guide::prefs::
                  kTimeHintsFetcherTopHostBlacklistLastInitialized)));

  base::TimeDelta duration_since_blacklist_initialized =
      (time_clock_->Now() - blacklist_initialized_time);

  for (const auto& detail : engagement_details) {
    if (!detail.origin.SchemeIsHTTPOrHTTPS())
      continue;
    // Once the engagement score is less than the initial engagement score for a
    // newly navigated host, return the current set of top hosts. This threshold
    // prevents hosts that have not been engaged recently from having hints
    // requested for them. The engagement_details are sorted above in descending
    // order by engagement score.
    // This filtering is applied only if the the blacklist was initialized
    // recently. If the blacklist was initialized too far back in time, hosts
    // that could not make it to blacklist should have either been navigated to
    // or would have fallen off the blacklist.
    if (duration_since_blacklist_initialized <=
            optimization_guide::features::
                DurationApplyLowEngagementScoreThreshold() &&
        detail.total_score <
            pref_service_->GetDouble(
                optimization_guide::prefs::
                    kHintsFetcherTopHostBlacklistMinimumEngagementScore)) {
      return top_hosts;
    }
    if (!IsHostBlacklisted(top_host_blacklist, detail.origin.host())) {
      top_hosts.push_back(detail.origin.host());
    }
  }

  return top_hosts;
}