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
|
// 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/ash/file_suggest/item_suggest_cache.h"
#include <algorithm>
#include <string>
#include "ash/constants/ash_pref_names.h"
#include "ash/public/cpp/app_list/app_list_features.h"
#include "base/callback_list.h"
#include "base/functional/bind.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/drive/drive_pref_names.h"
#include "components/google/core/common/google_util.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "google_apis/gaia/gaia_constants.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h"
namespace ash {
namespace {
// Maximum accepted size of an ItemSuggest response. 1MB.
constexpr int kMaxResponseSize = 1024 * 1024;
constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("launcher_item_suggest", R"(
semantics {
sender: "Launcher suggested drive files"
description:
"The Chrome OS launcher requests suggestions for Drive files from "
"the Drive ItemSuggest API. These are displayed in the launcher."
trigger:
"Once on login after Drive FS is mounted. Afterwards, whenever the "
"Chrome OS launcher is opened."
data:
"OAuth2 access token."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"This cannot be disabled except by policy."
chrome_policy {
DriveDisabled {
DriveDisabled: true
}
}
})");
bool IsDisabledByPolicy(const Profile* profile) {
return profile->GetPrefs()->GetBoolean(drive::prefs::kDisableDrive);
}
base::Time GetLastRequestTime(Profile* profile) {
return profile->GetPrefs()->GetTime(
ash::prefs::kLauncherLastContinueRequestTime);
}
void SetLastRequestTime(Profile* profile, const base::Time& time) {
profile->GetPrefs()->SetTime(ash::prefs::kLauncherLastContinueRequestTime,
time);
}
//------------------
// Metrics utilities
//------------------
void LogStatus(ItemSuggestCache::Status status) {
base::UmaHistogramEnumeration("Apps.AppList.ItemSuggestCache.Status", status);
}
void LogResponseSize(const int size) {
base::UmaHistogramCounts100000("Apps.AppList.ItemSuggestCache.ResponseSize",
size);
}
void LogLatency(base::TimeDelta latency) {
base::UmaHistogramTimes("Apps.AppList.ItemSuggestCache.UpdateCacheLatency",
latency);
}
//----------------------
// JSON response parsing
//----------------------
std::optional<std::string> GetString(const base::Value::Dict& value,
const std::string& key) {
const auto* field = value.FindString(key);
if (!field) {
return std::nullopt;
}
return *field;
}
std::optional<ItemSuggestCache::Result> ConvertResult(
const base::Value* value) {
if (!value->is_dict()) {
return std::nullopt;
}
const auto& value_dict = value->GetDict();
// Get the item ID and display name.
const auto& item_id = GetString(value_dict, "itemId");
const auto& display_text = GetString(value_dict, "displayText");
if (!item_id || !display_text) {
return std::nullopt;
}
ItemSuggestCache::Result result(item_id.value(), display_text.value(),
/*prediction_reason=*/std::nullopt);
// Get the justification string. We allow this to be empty, so return the
// previously-created `result` on failure.
const auto* justification_dict = value_dict.FindDict("justification");
if (!justification_dict) {
return result;
}
// We use `unstructuredJustificationDescription` because justifications are
// displayed on one line, and `justificationDescription` is intended for
// multi-line formatting.
const auto* description =
justification_dict->FindDict("unstructuredJustificationDescription");
if (!description) {
return result;
}
// `unstructuredJustificationDescription` contains only one text segment by
// convention.
const auto* text_segments = description->FindList("textSegment");
if (!text_segments || text_segments->empty() ||
!(*text_segments)[0].is_dict()) {
return result;
}
const auto& text_segment = (*text_segments)[0].GetDict();
const auto justification = GetString(text_segment, "text");
if (!justification) {
return result;
}
result.prediction_reason = justification;
return result;
}
std::optional<ItemSuggestCache::Results> ConvertResults(
const base::Value* value) {
if (!value->is_dict()) {
return std::nullopt;
}
const auto& value_dict = value->GetDict();
const auto suggestion_id = GetString(value_dict, "suggestionSessionId");
if (!suggestion_id) {
return std::nullopt;
}
ItemSuggestCache::Results results(suggestion_id.value());
const auto* items = value_dict.FindList("item");
if (!items) {
// Return empty results if there are no items.
return results;
}
for (const auto& result_value : *items) {
auto result = ConvertResult(&result_value);
// If any result fails conversion, fail completely and return std::nullopt,
// rather than just skipping this result. This makes clear the distinction
// between a response format issue and the response containing no results.
if (!result) {
return std::nullopt;
}
results.results.push_back(std::move(result.value()));
}
return results;
}
} // namespace
BASE_FEATURE(kLauncherItemSuggest,
"LauncherItemSuggest",
base::FEATURE_DISABLED_BY_DEFAULT);
constexpr base::FeatureParam<bool> ItemSuggestCache::kEnabled;
constexpr base::FeatureParam<std::string> ItemSuggestCache::kServerUrl;
constexpr base::FeatureParam<std::string> ItemSuggestCache::kModelName;
constexpr base::FeatureParam<bool> ItemSuggestCache::kMultipleQueriesPerSession;
constexpr base::FeatureParam<int> ItemSuggestCache::kLongDelayMinutes;
ItemSuggestCache::Result::Result(
const std::string& id,
const std::string& title,
const std::optional<std::string>& prediction_reason)
: id(id), title(title), prediction_reason(prediction_reason) {}
ItemSuggestCache::Result::Result(const Result& other)
: id(other.id),
title(other.title),
prediction_reason(other.prediction_reason) {}
ItemSuggestCache::Result::~Result() = default;
ItemSuggestCache::Results::Results(const std::string& suggestion_id)
: suggestion_id(suggestion_id) {}
ItemSuggestCache::Results::Results(const Results& other)
: suggestion_id(other.suggestion_id), results(other.results) {}
ItemSuggestCache::Results::~Results() = default;
ItemSuggestCache::ItemSuggestCache(
const std::string& locale,
Profile* profile,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: made_request_(false),
enabled_(kEnabled.Get()),
server_url_(kServerUrl.Get()),
multiple_queries_per_session_(kMultipleQueriesPerSession.Get()),
locale_(locale),
profile_(profile),
url_loader_factory_(std::move(url_loader_factory)) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
ItemSuggestCache::~ItemSuggestCache() = default;
base::CallbackListSubscription ItemSuggestCache::RegisterCallback(
ItemSuggestCache::OnResultsCallback callback) {
return on_results_callback_list_.Add(std::move(callback));
}
std::optional<ItemSuggestCache::Results> ItemSuggestCache::GetResults() {
// Return a copy because a pointer to |results_| will become invalid whenever
// the cache is updated.
return results_;
}
std::string ItemSuggestCache::GetRequestBody() {
// We request that ItemSuggest serve our request via particular model by
// specifying the model name in client_tags. This is a non-standard part of
// the API, implemented so we can experiment with model backends. The
// client_tags can be set via Finch based on what is expected by the
// ItemSuggest backend, and unexpected tags will be assigned a default model.
static constexpr char kRequestBody[] = R"({
"client_info": {
"platform_type": "CHROME_OS",
"scenario_type": "CHROME_OS_ZSS_FILES",
"language_code": "$1",
"request_type": "BACKGROUND_REQUEST",
"client_tags": {
"name": "$2"
}
},
"max_suggestions": 10,
"type_detail_fields": "drive_item.title,justification.display_text"
})";
const std::string& model = kModelName.Get();
return base::ReplaceStringPlaceholders(kRequestBody, {locale_, model},
nullptr);
}
base::TimeDelta ItemSuggestCache::GetDelay() {
bool use_long_delay = profile_->GetPrefs()->GetBoolean(
ash::prefs::kLauncherUseLongContinueDelay);
return base::Minutes(use_long_delay ? kLongDelayMinutes.Get()
: kShortDelayMinutes);
}
void ItemSuggestCache::MaybeUpdateCache() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
update_start_time_ = base::TimeTicks::Now();
if (base::Time::Now() - GetLastRequestTime(profile_) < GetDelay()) {
return;
}
// Make no requests and exit in these cases:
// - Item suggest has been disabled via experiment.
// - Item suggest has been disabled by policy.
// - The server url is not https or not trusted by Google.
// - We've already made a request this session and we are not configured to
// query multiple times.
if (!enabled_) {
LogStatus(Status::kDisabledByExperiment);
return;
} else if (IsDisabledByPolicy(profile_)) {
LogStatus(Status::kDisabledByPolicy);
return;
} else if (!server_url_.SchemeIs(url::kHttpsScheme) ||
!google_util::IsGoogleAssociatedDomainUrl(server_url_)) {
LogStatus(Status::kInvalidServerUrl);
return;
} else if (made_request_ && !multiple_queries_per_session_) {
LogStatus(Status::kPostLaunchUpdateIgnored);
return;
}
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile_);
if (!identity_manager) {
LogStatus(Status::kNoIdentityManager);
return;
}
// Fetch an OAuth2 access token.
token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>(
"launcher_item_suggest", identity_manager,
signin::ScopeSet({GaiaConstants::kDriveReadOnlyOAuth2Scope}),
base::BindOnce(&ItemSuggestCache::OnTokenReceived,
weak_factory_.GetWeakPtr()),
signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
signin::ConsentLevel::kSync);
}
void ItemSuggestCache::UpdateCacheWithJsonForTest(
const std::string& json_response) {
data_decoder::DataDecoder::ParseJsonIsolated(
json_response, base::BindOnce(&ItemSuggestCache::OnJsonParsed,
weak_factory_.GetWeakPtr()));
}
void ItemSuggestCache::OnTokenReceived(GoogleServiceAuthError error,
signin::AccessTokenInfo token_info) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
token_fetcher_.reset();
if (error.state() != GoogleServiceAuthError::NONE) {
LogStatus(Status::kGoogleAuthError);
return;
}
// Make a new request. This destroys any existing |url_loader_| which will
// cancel that request if it is in-progress.
SetLastRequestTime(profile_, base::Time::Now());
made_request_ = true;
url_loader_ = MakeRequestLoader(token_info.token);
url_loader_->SetRetryOptions(0, network::SimpleURLLoader::RETRY_NEVER);
url_loader_->AttachStringForUpload(GetRequestBody(), "application/json");
// Perform the request.
url_loader_->DownloadToString(
url_loader_factory_.get(),
base::BindOnce(&ItemSuggestCache::OnSuggestionsReceived,
weak_factory_.GetWeakPtr()),
kMaxResponseSize);
}
void ItemSuggestCache::OnSuggestionsReceived(
std::unique_ptr<std::string> json_response) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const int net_error = url_loader_->NetError();
if (net_error != net::OK) {
if (!url_loader_->ResponseInfo() || !url_loader_->ResponseInfo()->headers) {
if (net_error == net::ERR_INSUFFICIENT_RESOURCES) {
LogStatus(Status::kResponseTooLarge);
} else {
// Note that requests ending in kNetError don't count towards
// ItemSuggest QPS, but the last request time is still updated.
LogStatus(Status::kNetError);
}
} else {
const int status = url_loader_->ResponseInfo()->headers->response_code();
if (status >= 500) {
LogStatus(Status::k5xxStatus);
} else if (status >= 400) {
LogStatus(Status::k4xxStatus);
} else if (status >= 300) {
LogStatus(Status::k3xxStatus);
}
}
return;
} else if (!json_response || json_response->empty()) {
LogStatus(Status::kEmptyResponse);
return;
}
LogResponseSize(json_response->size());
// Parse the JSON response from ItemSuggest.
data_decoder::DataDecoder::ParseJsonIsolated(
*json_response, base::BindOnce(&ItemSuggestCache::OnJsonParsed,
weak_factory_.GetWeakPtr()));
}
void ItemSuggestCache::OnJsonParsed(
data_decoder::DataDecoder::ValueOrError result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!result.has_value()) {
LogStatus(Status::kJsonParseFailure);
return;
}
// Convert the JSON value into a Results object. If the conversion fails, or
// if the conversion contains no results, we shouldn't update the stored
// results.
const auto& results = ConvertResults(&*result);
if (!results) {
LogStatus(Status::kJsonConversionFailure);
} else if (results->results.empty()) {
LogStatus(Status::kNoResultsInResponse);
if (!results_) {
// Make sure that |results_| is non-null to indicate that an update was
// successful.
results_ = std::move(results.value());
}
} else {
LogStatus(Status::kOk);
LogLatency(base::TimeTicks::Now() - update_start_time_);
results_ = std::move(results.value());
on_results_callback_list_.Notify();
}
}
std::unique_ptr<network::SimpleURLLoader> ItemSuggestCache::MakeRequestLoader(
const std::string& token) {
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->method = "POST";
resource_request->url = server_url_;
// Do not allow cookies.
resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
// Ignore the cache because we always want fresh results.
resource_request->load_flags =
net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE;
DCHECK(resource_request->url.is_valid());
resource_request->headers.SetHeader(net::HttpRequestHeaders::kContentType,
"application/json");
resource_request->headers.SetHeader(net::HttpRequestHeaders::kAuthorization,
"Bearer " + token);
return network::SimpleURLLoader::Create(std::move(resource_request),
kTrafficAnnotation);
}
// static
std::optional<ItemSuggestCache::Results> ItemSuggestCache::ConvertJsonForTest(
const base::Value* value) {
return ConvertResults(value);
}
} // namespace ash
|