| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "components/offline_pages/background/request_picker.h" | |
| 6 | |
| 7 #include "base/bind.h" | |
| 8 #include "base/logging.h" | |
| 9 #include "components/offline_pages/background/save_page_request.h" | |
| 10 | |
| 11 namespace { | |
| 12 template <typename T> | |
| 13 int signum(T t) { | |
| 14 return (T(0) < t) - (t < T(0)); | |
| 15 } | |
| 16 | |
| 17 #define CALL_MEMBER_FUNCTION(object, ptrToMember) ((object)->*(ptrToMember)) | |
| 18 } // namespace | |
| 19 | |
| 20 namespace offline_pages { | |
| 21 | |
| 22 RequestPicker::RequestPicker(RequestQueue* requestQueue, | |
| 23 OfflinerPolicy* policy, | |
| 24 RequestNotifier* notifier, | |
| 25 RequestCoordinatorEventLogger* event_logger) | |
| 26 : queue_(requestQueue), | |
| 27 policy_(policy), | |
| 28 notifier_(notifier), | |
| 29 event_logger_(event_logger), | |
| 30 fewer_retries_better_(false), | |
| 31 earlier_requests_better_(false), | |
| 32 weak_ptr_factory_(this) {} | |
| 33 | |
| 34 RequestPicker::~RequestPicker() {} | |
| 35 | |
| 36 // Entry point for the async operation to choose the next request. | |
| 37 void RequestPicker::ChooseNextRequest( | |
| 38 RequestCoordinator::RequestPickedCallback picked_callback, | |
| 39 RequestCoordinator::RequestNotPickedCallback not_picked_callback, | |
| 40 DeviceConditions* device_conditions, | |
| 41 const std::set<int64_t>& disabled_requests) { | |
| 42 picked_callback_ = picked_callback; | |
| 43 not_picked_callback_ = not_picked_callback; | |
| 44 fewer_retries_better_ = policy_->ShouldPreferUntriedRequests(); | |
| 45 earlier_requests_better_ = policy_->ShouldPreferEarlierRequests(); | |
| 46 current_conditions_.reset(new DeviceConditions(*device_conditions)); | |
| 47 // Get all requests from queue (there is no filtering mechanism). | |
| 48 queue_->GetRequests(base::Bind(&RequestPicker::GetRequestResultCallback, | |
| 49 weak_ptr_factory_.GetWeakPtr(), | |
| 50 disabled_requests)); | |
| 51 } | |
| 52 | |
| 53 // When we get contents from the queue, use them to pick the next | |
| 54 // request to operate on (if any). | |
| 55 void RequestPicker::GetRequestResultCallback( | |
| 56 const std::set<int64_t>& disabled_requests, | |
| 57 RequestQueue::GetRequestsResult, | |
| 58 std::vector<std::unique_ptr<SavePageRequest>> requests) { | |
| 59 // If there is nothing to do, return right away. | |
| 60 if (requests.size() == 0) { | |
| 61 not_picked_callback_.Run(false); | |
| 62 return; | |
| 63 } | |
| 64 | |
| 65 // Get the expired requests to be removed from the queue, and the valid ones | |
| 66 // from which to pick the next request. | |
| 67 std::vector<std::unique_ptr<SavePageRequest>> valid_requests; | |
| 68 std::vector<std::unique_ptr<SavePageRequest>> expired_requests; | |
| 69 SplitRequests(std::move(requests), &valid_requests, &expired_requests); | |
| 70 std::vector<int64_t> expired_request_ids; | |
| 71 for (const auto& request : expired_requests) | |
| 72 expired_request_ids.push_back(request->request_id()); | |
| 73 | |
| 74 queue_->RemoveRequests(expired_request_ids, | |
| 75 base::Bind(&RequestPicker::OnRequestExpired, | |
| 76 weak_ptr_factory_.GetWeakPtr())); | |
| 77 | |
| 78 // Pick the most deserving request for our conditions. | |
| 79 const SavePageRequest* picked_request = nullptr; | |
| 80 | |
| 81 RequestCompareFunction comparator = nullptr; | |
| 82 | |
| 83 // Choose which comparison function to use based on policy. | |
| 84 if (policy_->RetryCountIsMoreImportantThanRecency()) | |
| 85 comparator = &RequestPicker::RetryCountFirstCompareFunction; | |
| 86 else | |
| 87 comparator = &RequestPicker::RecencyFirstCompareFunction; | |
| 88 | |
| 89 // Iterate once through the requests, keeping track of best candidate. | |
| 90 bool non_user_requested_tasks_remaining = false; | |
| 91 for (unsigned i = 0; i < valid_requests.size(); ++i) { | |
| 92 // If the request is on the disabled list, skip it. | |
| 93 auto search = disabled_requests.find(valid_requests[i]->request_id()); | |
| 94 if (search != disabled_requests.end()) { | |
| 95 continue; | |
| 96 } | |
| 97 if (!valid_requests[i]->user_requested()) | |
| 98 non_user_requested_tasks_remaining = true; | |
| 99 if (!RequestConditionsSatisfied(valid_requests[i].get())) | |
| 100 continue; | |
| 101 if (IsNewRequestBetter(picked_request, valid_requests[i].get(), comparator)) | |
| 102 picked_request = valid_requests[i].get(); | |
| 103 } | |
| 104 | |
| 105 // If we have a best request to try next, get the request coodinator to | |
| 106 // start it. Otherwise return that we have no candidates. | |
| 107 if (picked_request != nullptr) { | |
| 108 picked_callback_.Run(*picked_request); | |
| 109 } else { | |
| 110 not_picked_callback_.Run(non_user_requested_tasks_remaining); | |
| 111 } | |
| 112 } | |
| 113 | |
| 114 // Filter out requests that don't meet the current conditions. For instance, if | |
| 115 // this is a predictive request, and we are not on WiFi, it should be ignored | |
| 116 // this round. | |
| 117 bool RequestPicker::RequestConditionsSatisfied(const SavePageRequest* request) { | |
| 118 // If the user did not request the page directly, make sure we are connected | |
| 119 // to power and have WiFi and sufficient battery remaining before we take this | |
| 120 // request. | |
| 121 | |
| 122 if (!current_conditions_->IsPowerConnected() && | |
| 123 policy_->PowerRequired(request->user_requested())) { | |
| 124 return false; | |
| 125 } | |
| 126 | |
| 127 if (current_conditions_->GetNetConnectionType() != | |
| 128 net::NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI && | |
| 129 policy_->UnmeteredNetworkRequired(request->user_requested())) { | |
| 130 return false; | |
| 131 } | |
| 132 | |
| 133 if (current_conditions_->GetBatteryPercentage() < | |
| 134 policy_->BatteryPercentageRequired(request->user_requested())) { | |
| 135 return false; | |
| 136 } | |
| 137 | |
| 138 // If we have already started this page the max number of times, it is not | |
| 139 // eligible to try again. | |
| 140 if (request->started_attempt_count() >= policy_->GetMaxStartedTries()) | |
| 141 return false; | |
| 142 | |
| 143 // If we have already completed trying this page the max number of times, it | |
| 144 // is not eligible to try again. | |
| 145 if (request->completed_attempt_count() >= policy_->GetMaxCompletedTries()) | |
| 146 return false; | |
| 147 | |
| 148 // If the request is paused, do not consider it. | |
| 149 if (request->request_state() == SavePageRequest::RequestState::PAUSED) | |
| 150 return false; | |
| 151 | |
| 152 // If the request is expired, do not consider it. | |
| 153 base::TimeDelta requestAge = base::Time::Now() - request->creation_time(); | |
| 154 if (requestAge > | |
| 155 base::TimeDelta::FromSeconds( | |
| 156 policy_->GetRequestExpirationTimeInSeconds())) | |
| 157 return false; | |
| 158 | |
| 159 // If this request is not active yet, return false. | |
| 160 // TODO(petewil): If the only reason we return nothing to do is that we have | |
| 161 // inactive requests, we still want to try again later after their activation | |
| 162 // time elapses, we shouldn't take ourselves completely off the scheduler. | |
| 163 if (request->activation_time() > base::Time::Now()) | |
| 164 return false; | |
| 165 | |
| 166 return true; | |
| 167 } | |
| 168 | |
| 169 // Look at policies to decide which requests to prefer. | |
| 170 bool RequestPicker::IsNewRequestBetter(const SavePageRequest* oldRequest, | |
| 171 const SavePageRequest* newRequest, | |
| 172 RequestCompareFunction comparator) { | |
| 173 | |
| 174 // If there is no old request, the new one is better. | |
| 175 if (oldRequest == nullptr) | |
| 176 return true; | |
| 177 | |
| 178 // User requested pages get priority. | |
| 179 if (newRequest->user_requested() && !oldRequest->user_requested()) | |
| 180 return true; | |
| 181 | |
| 182 // Otherwise, use the comparison function for the current policy, which | |
| 183 // returns true if the older request is better. | |
| 184 return !(CALL_MEMBER_FUNCTION(this, comparator)(oldRequest, newRequest)); | |
| 185 } | |
| 186 | |
| 187 // Compare the results, checking request count before recency. Returns true if | |
| 188 // left hand side is better, false otherwise. | |
| 189 bool RequestPicker::RetryCountFirstCompareFunction( | |
| 190 const SavePageRequest* left, const SavePageRequest* right) { | |
| 191 // Check the attempt count. | |
| 192 int result = CompareRetryCount(left, right); | |
| 193 | |
| 194 if (result != 0) | |
| 195 return (result > 0); | |
| 196 | |
| 197 // If we get here, the attempt counts were the same, so check recency. | |
| 198 result = CompareCreationTime(left, right); | |
| 199 | |
| 200 return (result > 0); | |
| 201 } | |
| 202 | |
| 203 // Compare the results, checking recency before request count. Returns true if | |
| 204 // left hand side is better, false otherwise. | |
| 205 bool RequestPicker::RecencyFirstCompareFunction( | |
| 206 const SavePageRequest* left, const SavePageRequest* right) { | |
| 207 // Check the recency. | |
| 208 int result = CompareCreationTime(left, right); | |
| 209 | |
| 210 if (result != 0) | |
| 211 return (result > 0); | |
| 212 | |
| 213 // If we get here, the recency was the same, so check the attempt count. | |
| 214 result = CompareRetryCount(left, right); | |
| 215 | |
| 216 return (result > 0); | |
| 217 } | |
| 218 | |
| 219 // Compare left and right side, returning 1 if the left side is better | |
| 220 // (preferred by policy), 0 if the same, and -1 if the right side is better. | |
| 221 int RequestPicker::CompareRetryCount( | |
| 222 const SavePageRequest* left, const SavePageRequest* right) { | |
| 223 // Check the attempt count. | |
| 224 int result = signum(left->completed_attempt_count() - | |
| 225 right->completed_attempt_count()); | |
| 226 | |
| 227 // Flip the direction of comparison if policy prefers fewer retries. | |
| 228 if (fewer_retries_better_) | |
| 229 result *= -1; | |
| 230 | |
| 231 return result; | |
| 232 } | |
| 233 | |
| 234 // Compare left and right side, returning 1 if the left side is better | |
| 235 // (preferred by policy), 0 if the same, and -1 if the right side is better. | |
| 236 int RequestPicker::CompareCreationTime( | |
| 237 const SavePageRequest* left, const SavePageRequest* right) { | |
| 238 // Check the recency. | |
| 239 base::TimeDelta difference = left->creation_time() - right->creation_time(); | |
| 240 int result = signum(difference.InMilliseconds()); | |
| 241 | |
| 242 // Flip the direction of comparison if policy prefers fewer retries. | |
| 243 if (earlier_requests_better_) | |
| 244 result *= -1; | |
| 245 | |
| 246 return result; | |
| 247 } | |
| 248 | |
| 249 void RequestPicker::SplitRequests( | |
| 250 std::vector<std::unique_ptr<SavePageRequest>> requests, | |
| 251 std::vector<std::unique_ptr<SavePageRequest>>* valid_requests, | |
| 252 std::vector<std::unique_ptr<SavePageRequest>>* expired_requests) { | |
| 253 for (auto& request : requests) { | |
| 254 if (base::Time::Now() - request->creation_time() >= | |
| 255 base::TimeDelta::FromSeconds(kRequestExpirationTimeInSeconds)) { | |
| 256 expired_requests->push_back(std::move(request)); | |
| 257 } else { | |
| 258 valid_requests->push_back(std::move(request)); | |
| 259 } | |
| 260 } | |
| 261 } | |
| 262 | |
| 263 // Callback used after expired requests are deleted from the queue and notifies | |
| 264 // the coordinator. | |
| 265 void RequestPicker::OnRequestExpired( | |
| 266 std::unique_ptr<UpdateRequestsResult> result) { | |
| 267 const RequestCoordinator::BackgroundSavePageResult save_page_result( | |
| 268 RequestCoordinator::BackgroundSavePageResult::EXPIRED); | |
| 269 for (const auto& request : result->updated_items) { | |
| 270 event_logger_->RecordDroppedSavePageRequest( | |
| 271 request.client_id().name_space, save_page_result, request.request_id()); | |
| 272 notifier_->NotifyCompleted(request, save_page_result); | |
| 273 } | |
| 274 } | |
| 275 | |
| 276 } // namespace offline_pages | |
| OLD | NEW |