File: auto_resumption_handler.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 (354 lines) | stat: -rw-r--r-- 11,783 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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/download/public/common/android/auto_resumption_handler.h"

#include <memory>
#include <utility>
#include <vector>

#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "components/download/public/common/download_features.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_utils.h"
#include "components/download/public/task/task_scheduler.h"
#include "services/network/public/cpp/network_connection_tracker.h"
#include "url/gurl.h"

namespace download {
namespace {

static download::AutoResumptionHandler* g_auto_resumption_handler = nullptr;

// The delay to wait for after a chrome restart before resuming all pending
// downloads so that tab loading doesn't get impacted.
const base::TimeDelta kAutoResumeStartupDelay = base::Seconds(10);

// The interval at which various download updates are grouped together for
// computing the params for the task scheduler.
const base::TimeDelta kBatchDownloadUpdatesInterval = base::Seconds(1);

// The delay to wait for before immediately retrying a download after it got
// interrupted due to network reasons.
const base::TimeDelta kDownloadImmediateRetryDelay = base::Seconds(1);

// Any downloads started before this interval will be ignored. User scheduled
// download will not be affected.
const base::TimeDelta kAutoResumptionExpireInterval = base::Days(7);

const download::DownloadTaskType kUnmeteredDownloadsTaskType =
    download::DownloadTaskType::DOWNLOAD_AUTO_RESUMPTION_UNMETERED_TASK;

const download::DownloadTaskType kAnyNetworkDownloadsTaskType =
    download::DownloadTaskType::DOWNLOAD_AUTO_RESUMPTION_ANY_NETWORK_TASK;

// The window start time after which the system should fire the task.
const int64_t kWindowStartTimeSeconds = 0;

// The window end time before which the system should fire the task.
const int64_t kWindowEndTimeSeconds = 24 * 60 * 60;

bool IsConnected(network::mojom::ConnectionType type) {
  switch (type) {
    case network::mojom::ConnectionType::CONNECTION_UNKNOWN:
    case network::mojom::ConnectionType::CONNECTION_NONE:
    case network::mojom::ConnectionType::CONNECTION_BLUETOOTH:
      return false;
    default:
      return true;
  }
}

}  // namespace

AutoResumptionHandler::Config::Config()
    : auto_resumption_size_limit(0),
      is_auto_resumption_enabled_in_native(false) {}

// static
void AutoResumptionHandler::Create(
    std::unique_ptr<download::NetworkStatusListener> network_listener,
    std::unique_ptr<download::TaskManager> task_manager,
    std::unique_ptr<Config> config,
    base::Clock* clock) {
  DCHECK(!g_auto_resumption_handler);
  g_auto_resumption_handler = new AutoResumptionHandler(
      std::move(network_listener), std::move(task_manager), std::move(config),
      clock);
}

// static
AutoResumptionHandler* AutoResumptionHandler::Get() {
  return g_auto_resumption_handler;
}

AutoResumptionHandler::AutoResumptionHandler(
    std::unique_ptr<download::NetworkStatusListener> network_listener,
    std::unique_ptr<download::TaskManager> task_manager,
    std::unique_ptr<Config> config,
    base::Clock* clock)
    : network_listener_(std::move(network_listener)),
      task_manager_(std::move(task_manager)),
      config_(std::move(config)),
      clock_(clock) {
  network_listener_->Start(this);
}

AutoResumptionHandler::~AutoResumptionHandler() {
  network_listener_->Stop();
}

void AutoResumptionHandler::SetResumableDownloads(
    const std::vector<raw_ptr<download::DownloadItem, VectorExperimental>>&
        downloads) {
  resumable_downloads_.clear();
  for (download::DownloadItem* download : downloads) {
    if (!IsAutoResumableDownload(download))
      continue;
    resumable_downloads_.insert(std::make_pair(download->GetGuid(), download));
    download->RemoveObserver(this);
    download->AddObserver(this);
  }

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&AutoResumptionHandler::ResumePendingDownloads,
                     weak_factory_.GetWeakPtr()),
      kAutoResumeStartupDelay);
}

bool AutoResumptionHandler::IsActiveNetworkMetered() const {
  return network::NetworkConnectionTracker::IsConnectionCellular(
      network_listener_->GetConnectionType());
}

void AutoResumptionHandler::OnNetworkStatusReady(
    network::mojom::ConnectionType type) {
  // TODO(xingliu): The API to check network type on all platforms is async now,
  // that early call to IsActiveNetworkMetered() which queries network type
  // might just return a unknown network type.
}

void AutoResumptionHandler::OnNetworkChanged(
    network::mojom::ConnectionType type) {
  if (!IsConnected(type))
    return;

  ResumePendingDownloads();
}

void AutoResumptionHandler::OnDownloadStarted(download::DownloadItem* item) {
  item->RemoveObserver(this);
  item->AddObserver(this);

  OnDownloadUpdated(item);
}

void AutoResumptionHandler::OnDownloadUpdated(download::DownloadItem* item) {
  if (IsAutoResumableDownload(item))
    resumable_downloads_[item->GetGuid()] = item;
  else
    resumable_downloads_.erase(item->GetGuid());

  if (item->GetState() == download::DownloadItem::INTERRUPTED &&
      IsAutoResumableDownload(item) && ShouldResumeNow(item)) {
    downloads_to_retry_.insert(item);
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&AutoResumptionHandler::ResumeDownloadImmediately,
                       weak_factory_.GetWeakPtr()),
        kDownloadImmediateRetryDelay);
    return;
  }
  RecomputeTaskParams();
}

void AutoResumptionHandler::OnDownloadRemoved(download::DownloadItem* item) {
  resumable_downloads_.erase(item->GetGuid());
  downloads_to_retry_.erase(item);
  RecomputeTaskParams();
}

void AutoResumptionHandler::OnDownloadDestroyed(download::DownloadItem* item) {
  resumable_downloads_.erase(item->GetGuid());
  downloads_to_retry_.erase(item);
}

void AutoResumptionHandler::ResumeDownloadImmediately() {
  if (!config_->is_auto_resumption_enabled_in_native)
    return;

  for (download::DownloadItem* download : downloads_to_retry_) {
    if (ShouldResumeNow(download))
      download->Resume(false);
    else
      RecomputeTaskParams();
  }
  downloads_to_retry_.clear();
}

void AutoResumptionHandler::OnStartScheduledTask(
    DownloadTaskType type,
    download::TaskFinishedCallback callback) {
  task_manager_->OnStartScheduledTask(type, std::move(callback));
  ResumePendingDownloads();
}

bool AutoResumptionHandler::OnStopScheduledTask(DownloadTaskType type) {
  task_manager_->OnStopScheduledTask(type);
  RescheduleTaskIfNecessary();
  return false;
}

void AutoResumptionHandler::RecomputeTaskParams() {
  if (recompute_task_params_scheduled_)
    return;

  recompute_task_params_scheduled_ = true;
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&AutoResumptionHandler::RescheduleTaskIfNecessary,
                     weak_factory_.GetWeakPtr()),
      kBatchDownloadUpdatesInterval);
}

// Go through all the downloads.
// 1- If there is no immediately resumable downloads, finish the task
// 2- If there are resumable downloads, schedule a task
// 3- If there are no resumable downloads, unschedule the task.
// At any point either a task is running or is scheduled but not both, which is
// handled by TaskManager.
void AutoResumptionHandler::RescheduleTaskIfNecessary() {
  if (!config_->is_auto_resumption_enabled_in_native)
    return;

  recompute_task_params_scheduled_ = false;
  RescheduleTaskIfNecessaryForTaskType(kUnmeteredDownloadsTaskType);
  RescheduleTaskIfNecessaryForTaskType(kAnyNetworkDownloadsTaskType);
}

// Go through all the downloads. Filter out only the ones having matching
// network type. Then the logic is same for both tasks.
// 1- If no download can resume right now, finish the task and schedule later.
// 2- If no download is in a resumable state, we dont need a task. Unschedule if
// there is any.
// At any point either a task is running or is scheduled but not both, which
// is handled by TaskManager.
void AutoResumptionHandler::RescheduleTaskIfNecessaryForTaskType(
    DownloadTaskType task_type) {
  bool has_resumable_downloads = false;
  bool has_actionable_downloads = false;

  bool requires_unmetered = task_type == kUnmeteredDownloadsTaskType;
  for (auto& pair : resumable_downloads_) {
    download::DownloadItem* download = pair.second;
    // Filter out downloads that don't match the network type.
    if (download->AllowMetered() == requires_unmetered) {
      continue;
    }

    if (!IsAutoResumableDownload(download)) {
      continue;
    }

    // Transient downloads (mainly inline pdf downloads) don't need a task as
    // they don't have a notification in UI.
    if (download->IsTransient()) {
      continue;
    }

    has_resumable_downloads = true;
    has_actionable_downloads |= ShouldResumeNow(download);
  }

  if (!has_actionable_downloads) {
    // We finish the task without specifying system reschedule since we are
    // scheduling another task below.
    task_manager_->NotifyTaskFinished(task_type, /*needs_reschedule=*/false);
  }

  if (!has_resumable_downloads) {
    task_manager_->UnscheduleTask(task_type);
    return;
  }

  download::TaskManager::TaskParams task_params;
  task_params.require_unmetered_network = requires_unmetered;
  task_params.window_start_time_seconds = kWindowStartTimeSeconds;
  task_params.window_end_time_seconds = kWindowEndTimeSeconds;
  task_manager_->ScheduleTask(task_type, task_params);
}

void AutoResumptionHandler::ResumePendingDownloads() {
  if (!config_->is_auto_resumption_enabled_in_native)
    return;

  int resumed = MaybeResumeDownloads(resumable_downloads_);

  // If we resume nothing, finish the current task and reschedule.
  if (!resumed)
    RecomputeTaskParams();
}

int AutoResumptionHandler::MaybeResumeDownloads(
    std::map<std::string, raw_ptr<DownloadItem, CtnExperimental>> downloads) {
  int resumed = 0;
  for (const auto& pair : downloads) {
    DownloadItem* download = pair.second;
    if (!IsAutoResumableDownload(download))
      continue;

    if (ShouldResumeNow(download)) {
      download->Resume(false);
      resumed++;
    }
  }

  return resumed;
}

bool AutoResumptionHandler::ShouldResumeNow(
    download::DownloadItem* download) const {
  if (!IsConnected(network_listener_->GetConnectionType()))
    return false;

  return download->AllowMetered() || !IsActiveNetworkMetered();
}

bool AutoResumptionHandler::IsAutoResumableDownload(
    download::DownloadItem* item) const {
  if (!item || item->IsDangerous())
    return false;

  // Ignore downloads started a while ago.
  if (clock_->Now() - item->GetStartTime() > kAutoResumptionExpireInterval) {
    return false;
  }

  switch (item->GetState()) {
    case download::DownloadItem::IN_PROGRESS:
      return !item->IsPaused();
    case download::DownloadItem::COMPLETE:
    case download::DownloadItem::CANCELLED:
      return false;
    case download::DownloadItem::INTERRUPTED:
      return !item->IsPaused() &&
             IsInterruptedDownloadAutoResumable(
                 item, config_->auto_resumption_size_limit);
    case download::DownloadItem::MAX_DOWNLOAD_STATE:
      NOTREACHED();
  }

  return false;
}

}  // namespace download