File: background_download_service_impl.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 (395 lines) | stat: -rw-r--r-- 14,154 bytes parent folder | download | duplicates (6)
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
// Copyright 2021 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/internal/background_service/ios/background_download_service_impl.h"

#include <utility>
#include <vector>

#include "base/logging.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "components/download/internal/background_service/client_set.h"
#include "components/download/internal/background_service/config.h"
#include "components/download/internal/background_service/entry.h"
#include "components/download/internal/background_service/file_monitor.h"
#include "components/download/internal/background_service/ios/background_download_task_helper.h"
#include "components/download/internal/background_service/ios/entry_utils.h"
#include "components/download/internal/background_service/log_sink.h"
#include "components/download/internal/background_service/stats.h"
#include "components/download/public/background_service/client.h"
#include "components/download/public/background_service/download_metadata.h"
#include "components/download/public/background_service/download_params.h"
#include "components/download/public/background_service/logger.h"

namespace download {
namespace {

// Interval to throttle the download update that results in a database update.
const base::TimeDelta kUpdateInterval = base::Seconds(5);

}  // namespace

BackgroundDownloadServiceImpl::BackgroundDownloadServiceImpl(
    std::unique_ptr<ClientSet> clients,
    std::unique_ptr<Model> model,
    std::unique_ptr<BackgroundDownloadTaskHelper> download_helper,
    std::unique_ptr<FileMonitor> file_monitor,
    const base::FilePath& download_dir,
    std::unique_ptr<Logger> logger,
    LogSink* log_sink,
    base::Clock* clock)
    : config_(std::make_unique<Configuration>()),
      service_config_(config_.get()),
      clients_(std::move(clients)),
      model_(std::move(model)),
      download_helper_(std::move(download_helper)),
      file_monitor_(std::move(file_monitor)),
      logger_(std::move(logger)),
      log_sink_(log_sink),
      clock_(clock),
      download_dir_(download_dir) {
  // iOS doesn't use driver interface, mark it ready.
  startup_status_.driver_ok = true;
}

BackgroundDownloadServiceImpl::~BackgroundDownloadServiceImpl() = default;

void BackgroundDownloadServiceImpl::Initialize(base::OnceClosure callback) {
  init_callback_ = std::move(callback);
  model_->Initialize(this);
}

const ServiceConfig& BackgroundDownloadServiceImpl::GetConfig() {
  NOTREACHED() << " This function is not supported on iOS.";
}

void BackgroundDownloadServiceImpl::OnStartScheduledTask(
    DownloadTaskType task_type,
    TaskFinishedCallback callback) {
  NOTREACHED() << " This function is not supported on iOS.";
}

bool BackgroundDownloadServiceImpl::OnStopScheduledTask(
    DownloadTaskType task_type) {
  NOTREACHED() << " This function is not supported on iOS.";
}

BackgroundDownloadService::ServiceStatus
BackgroundDownloadServiceImpl::GetStatus() {
  if (startup_status_.Failed())
    return BackgroundDownloadService::ServiceStatus::UNAVAILABLE;
  return startup_status_.Complete()
             ? BackgroundDownloadService::ServiceStatus::READY
             : BackgroundDownloadService::ServiceStatus::STARTING_UP;
}

void BackgroundDownloadServiceImpl::StartDownload(
    DownloadParams download_params) {
  if (GetStatus() != BackgroundDownloadService::ServiceStatus::READY) {
    LOG(ERROR) << "Background download service is not intialized successfully.";
    InvokeStartCallback(download_params.client, download_params.guid,
                        DownloadParams::StartResult::INTERNAL_ERROR,
                        std::move(download_params.callback));
    return;
  }

  if (start_callbacks_.find(download_params.guid) != start_callbacks_.end() ||
      model_->Get(download_params.guid) != nullptr) {
    InvokeStartCallback(download_params.client, download_params.guid,
                        DownloadParams::StartResult::UNEXPECTED_GUID,
                        std::move(download_params.callback));
    return;
  }

  DCHECK(!download_params.guid.empty());
  start_callbacks_.emplace(download_params.guid,
                           std::move(download_params.callback));
  Entry entry(download_params);
  entry.target_file_path = download_dir_.AppendASCII(download_params.guid);
  entry.create_time = clock_->Now();
  entry.state = Entry::State::ACTIVE;
  entry.custom_data = std::move(download_params.custom_data);

  model_->Add(entry);
}

void BackgroundDownloadServiceImpl::PauseDownload(const std::string& guid) {
  NOTREACHED() << " This function is not supported on iOS.";
}

void BackgroundDownloadServiceImpl::ResumeDownload(const std::string& guid) {
  NOTREACHED() << " This function is not supported on iOS.";
}
void BackgroundDownloadServiceImpl::CancelDownload(const std::string& guid) {
  cancelled_downloads_.emplace(guid);
}
void BackgroundDownloadServiceImpl::ChangeDownloadCriteria(
    const std::string& guid,
    const SchedulingParams& params) {
  NOTREACHED() << " This function is not supported on iOS.";
}

Logger* BackgroundDownloadServiceImpl::GetLogger() {
  return logger_.get();
}

void BackgroundDownloadServiceImpl::HandleEventsForBackgroundURLSession(
    base::OnceClosure completion_handler) {
  download_helper_->HandleEventsForBackgroundURLSession(
      std::move(completion_handler));
}

void BackgroundDownloadServiceImpl::OnModelReady(bool success) {
  startup_status_.model_ok = success;

  if (!success) {
    DCHECK(startup_status_.Failed());
    stats::LogStartUpResult(false, stats::StartUpResult::FAILURE_REASON_MODEL);
    NotifyServiceUnavailable();
    return;
  }

  PruneDbRecords();
  file_monitor_->Initialize(
      base::BindOnce(&BackgroundDownloadServiceImpl::OnFileMonitorInitialized,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BackgroundDownloadServiceImpl::PruneDbRecords() {
  // Clean up expired entries or entries without a client, disregard whether
  // they are completed.
  std::set<std::string> entries_to_remove;
  for (Entry* entry : model_->PeekEntries()) {
    download::Client* client = clients_->GetClient(entry->client);
    // TODO(xingliu): Ask client whether we can delete the file?
    if (!client ||
        clock_->Now() - entry->create_time > config_->file_keep_alive_time) {
      entries_to_remove.insert(entry->guid);
    }

    // On iOS, we don't implement any resumption mechanism, so unfinished
    // downloads should be deleted.
    if (entry->state != Entry::State::COMPLETE) {
      entries_to_remove.insert(entry->guid);
    }
  }
  for (const auto& guid : entries_to_remove)
    model_->Remove(guid);
}

void BackgroundDownloadServiceImpl::OnFileMonitorInitialized(bool success) {
  if (!success) {
    startup_status_.file_monitor_ok = false;
    DCHECK(startup_status_.Complete());
    DCHECK(startup_status_.Failed());
    stats::LogStartUpResult(false,
                            stats::StartUpResult::FAILURE_REASON_FILE_MONITOR);
    NotifyServiceUnavailable();
    return;
  }

  // Clean up the download file directory on a background thread.
  file_monitor_->DeleteUnknownFiles(
      model_->PeekEntries(), {},
      base::BindOnce(&BackgroundDownloadServiceImpl::OnFilesPruned,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BackgroundDownloadServiceImpl::OnFilesPruned() {
  // Initialization is done.
  startup_status_.file_monitor_ok = true;
  DCHECK(startup_status_.Ok());
  log_sink_->OnServiceStatusChanged();
  stats::LogStartUpResult(false, stats::StartUpResult::SUCCESS);
  if (init_callback_)
    std::move(init_callback_).Run();

  // Report download metadata to clients.
  auto metadata_map = util::MapEntriesToMetadataForClients(
      clients_->GetRegisteredClients(), model_->PeekEntries());
  for (DownloadClient client_id : clients_->GetRegisteredClients()) {
    clients_->GetClient(client_id)->OnServiceInitialized(
        /*state_lost=*/false, metadata_map[client_id]);
  }

  log_sink_->OnServiceDownloadsAvailable();
}

void BackgroundDownloadServiceImpl::NotifyServiceUnavailable() {
  for (DownloadClient client_id : clients_->GetRegisteredClients())
    clients_->GetClient(client_id)->OnServiceUnavailable();

  log_sink_->OnServiceStatusChanged();
}

void BackgroundDownloadServiceImpl::InvokeStartCallback(
    DownloadClient client,
    const std::string& guid,
    DownloadParams::StartResult result,
    DownloadParams::StartCallback callback) {
  log_sink_->OnServiceRequestMade(client, guid, result);
  stats::LogStartDownloadResult(client, result);
  if (callback) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), guid, result));
  }
}

void BackgroundDownloadServiceImpl::OnModelHardRecoverComplete(bool success) {}

void BackgroundDownloadServiceImpl::OnItemAdded(bool success,
                                                DownloadClient client,
                                                const std::string& guid) {
  DownloadParams::StartCallback callback = std::move(start_callbacks_[guid]);
  start_callbacks_.erase(guid);
  if (!success) {
    InvokeStartCallback(client, guid,
                        DownloadParams::StartResult::INTERNAL_ERROR,
                        std::move(callback));
    return;
  }

  Entry* entry = model_->Get(guid);
  DCHECK(entry);

  InvokeStartCallback(client, guid, DownloadParams::StartResult::ACCEPTED,
                      std::move(callback));
  download_helper_->StartDownload(
      entry->guid, entry->target_file_path, entry->request_params,
      entry->scheduling_params,
      base::BindOnce(&BackgroundDownloadServiceImpl::OnDownloadFinished,
                     weak_ptr_factory_.GetWeakPtr(), entry->client,
                     entry->guid),
      base::BindRepeating(&BackgroundDownloadServiceImpl::OnDownloadUpdated,
                          weak_ptr_factory_.GetWeakPtr(), entry->client,
                          entry->guid));
}

void BackgroundDownloadServiceImpl::OnItemUpdated(bool success,
                                                  DownloadClient client,
                                                  const std::string& guid) {}

void BackgroundDownloadServiceImpl::OnItemRemoved(bool success,
                                                  DownloadClient client,
                                                  const std::string& guid) {}

Controller::State BackgroundDownloadServiceImpl::GetControllerState() {
  switch (GetStatus()) {
    case ServiceStatus::STARTING_UP:
      return Controller::State::INITIALIZING;
    case ServiceStatus::READY:
      return Controller::State::READY;
    case ServiceStatus::UNAVAILABLE:
      return Controller::State::UNAVAILABLE;
  }
}

const StartupStatus& BackgroundDownloadServiceImpl::GetStartupStatus() {
  return startup_status_;
}

LogSource::EntryDetailsList
BackgroundDownloadServiceImpl::GetServiceDownloads() {
  EntryDetailsList list;
  auto entries = model_->PeekEntries();
  for (download::Entry* entry : entries) {
    list.push_back(std::make_pair(entry, std::nullopt));
  }
  return list;
}

std::optional<LogSource::EntryDetails>
BackgroundDownloadServiceImpl::GetServiceDownload(const std::string& guid) {
  auto* entry = model_->Get(guid);

  return std::optional<LogSource::EntryDetails>(
      std::make_pair(entry, std::nullopt));
}

void BackgroundDownloadServiceImpl::OnDownloadFinished(
    DownloadClient download_client,
    const std::string& guid,
    bool success,
    const base::FilePath& file_path,
    int64_t file_size) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (cancelled_downloads_.find(guid) != cancelled_downloads_.end()) {
    cancelled_downloads_.erase(guid);
    return;
  }

  download::Client* client = clients_->GetClient(download_client);
  if (!client)
    return;

  // TODO(xingliu): Plumb more details from platform api for failure reasons and
  // bytes downloaded.
  Entry* entry = model_->Get(guid);
  if (!success) {
    stats::LogDownloadCompletion(download_client, CompletionType::FAIL,
                                 file_size);
    if (entry) {
      log_sink_->OnServiceDownloadFailed(CompletionType::UNKNOWN, *entry);
      model_->Remove(guid);
    }
    client->OnDownloadFailed(guid, CompletionInfo(),
                             download::Client::FailureReason::UNKNOWN);
    return;
  }

  if (!entry)
    return;

  entry->bytes_downloaded = base::saturated_cast<uint64_t>(file_size);
  entry->completion_time = clock_->Now();
  entry->state = Entry::State::COMPLETE;
  model_->Update(*entry);
  log_sink_->OnServiceDownloadChanged(guid);
  stats::LogDownloadCompletion(download_client, CompletionType::SUCCEED,
                               file_size);

  CompletionInfo completion_info;
  completion_info.path = file_path;
  completion_info.custom_data = entry->custom_data;
  client->OnDownloadSucceeded(guid, completion_info);
}

void BackgroundDownloadServiceImpl::OnDownloadUpdated(
    DownloadClient download_client,
    const std::string& guid,
    int64_t bytes_downloaded) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (cancelled_downloads_.find(guid) != cancelled_downloads_.end()) {
    return;
  }

  uint64_t bytes_count = base::saturated_cast<uint64_t>(bytes_downloaded);
  MaybeUpdateProgress(guid, bytes_count);

  log_sink_->OnServiceDownloadChanged(guid);
  download::Client* client = clients_->GetClient(download_client);
  if (!client)
    return;

  client->OnDownloadUpdated(guid, /*bytes_uploaded*/ 0u, bytes_count);
}

void BackgroundDownloadServiceImpl::MaybeUpdateProgress(
    const std::string& guid,
    uint64_t bytes_downloaded) {
  // Throttle the model update frequency.
  if (clock_->Now() - update_time_ < kUpdateInterval)
    return;

  update_time_ = clock_->Now();
  Entry* entry = model_->Get(guid);
  DCHECK_GE(bytes_downloaded, 0u);
  entry->bytes_downloaded = bytes_downloaded;
  model_->Update(*entry);
}

}  // namespace download