File: in_memory_download.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 (276 lines) | stat: -rw-r--r-- 8,782 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
// Copyright 2017 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/in_memory_download.h"

#include <memory>
#include <string>
#include <string_view>

#include "base/functional/bind.h"
#include "base/task/single_thread_task_runner.h"
#include "components/download/internal/background_service/blob_task_proxy.h"
#include "net/base/load_flags.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/mojom/url_response_head.mojom.h"
#include "storage/browser/blob/blob_data_handle.h"
#include "storage/browser/blob/blob_storage_context.h"

namespace download {

InMemoryDownload::InMemoryDownload(const std::string& guid)
    : guid_(guid),
      state_(State::INITIAL),
      paused_(false),
      bytes_downloaded_(0u),
      bytes_uploaded_(0u) {}

InMemoryDownload::~InMemoryDownload() = default;

InMemoryDownloadImpl::InMemoryDownloadImpl(
    const std::string& guid,
    const RequestParams& request_params,
    scoped_refptr<network::ResourceRequestBody> request_body,
    const net::NetworkTrafficAnnotationTag& traffic_annotation,
    Delegate* delegate,
    scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
    : InMemoryDownload(guid),
      request_params_(request_params),
      request_body_(std::move(request_body)),
      traffic_annotation_(traffic_annotation),
      io_task_runner_(io_task_runner),
      delegate_(delegate),
      completion_notified_(false),
      started_(false) {
  DCHECK(!guid_.empty());
  DCHECK(delegate_);
}

InMemoryDownloadImpl::~InMemoryDownloadImpl() {
  io_task_runner_->DeleteSoon(FROM_HERE, blob_task_proxy_.release());
}

void InMemoryDownloadImpl::Start() {
  DCHECK(state_ == State::INITIAL) << "Only call Start() for new download.";
  state_ = State::RETRIEVE_URL_LOADER_FACTIORY;
  delegate_->RetrievedURLLoaderFactory(
      base::BindOnce(&InMemoryDownloadImpl::OnRetrievedURLLoaderFactory,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InMemoryDownloadImpl::OnRetrievedURLLoaderFactory(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
  state_ = State::RETRIEVE_BLOB_CONTEXT;
  url_loader_factory_ = url_loader_factory;
  delegate_->RetrieveBlobContextGetter(
      base::BindOnce(&InMemoryDownloadImpl::OnRetrievedBlobContextGetter,
                     weak_ptr_factory_.GetWeakPtr()));
}

void InMemoryDownloadImpl::OnRetrievedBlobContextGetter(
    BlobContextGetter blob_context_getter) {
  DCHECK(state_ == State::RETRIEVE_BLOB_CONTEXT);
  blob_task_proxy_ =
      BlobTaskProxy::Create(blob_context_getter, io_task_runner_);
  SendRequest();
  state_ = State::IN_PROGRESS;
}

void InMemoryDownloadImpl::Pause() {
  if (state_ == State::IN_PROGRESS) {
    paused_ = true;
  }
}

void InMemoryDownloadImpl::Resume() {
  paused_ = false;

  switch (state_) {
    case State::INITIAL:
    case State::RETRIEVE_URL_LOADER_FACTIORY:
    case State::RETRIEVE_BLOB_CONTEXT:
      return;
    case State::IN_PROGRESS:
      // Let the network pipe continue to read data.
      if (resume_callback_) {
        std::move(resume_callback_).Run();
      }
      return;
    case State::FAILED:
      // Restart the download.
      Reset();
      SendRequest();
      state_ = State::IN_PROGRESS;
      return;
    case State::COMPLETE:
      NotifyDelegateDownloadComplete();
      return;
  }
}

std::unique_ptr<storage::BlobDataHandle> InMemoryDownloadImpl::ResultAsBlob()
    const {
  DCHECK(state_ == State::COMPLETE || state_ == State::FAILED);
  // Return a copy.
  return std::make_unique<storage::BlobDataHandle>(*blob_data_handle_);
}

size_t InMemoryDownloadImpl::EstimateMemoryUsage() const {
  return bytes_downloaded_;
}

void InMemoryDownloadImpl::OnDataReceived(std::string_view string_piece,
                                          base::OnceClosure resume) {
  data_.append(string_piece);
  bytes_downloaded_ += string_piece.size();

  if (paused_) {
    // Read data later and cache the resumption callback when paused.
    resume_callback_ = std::move(resume);
    return;
  }

  // Continue to read data.
  std::move(resume).Run();

  // TODO(xingliu): Throttle the update frequency. See https://crbug.com/809674.
  delegate_->OnDownloadProgress(this);
}

void InMemoryDownloadImpl::OnComplete(bool success) {
  if (success) {
    SaveAsBlob();
    return;
  }

  state_ = State::FAILED;

  // Release download data.
  data_.clear();

  // OnComplete() called without OnResponseStarted(). This will happen when the
  // request was aborted.
  if (!started_) {
    OnResponseStarted(GURL(), network::mojom::URLResponseHead());
  }

  NotifyDelegateDownloadComplete();
}

void InMemoryDownloadImpl::OnRetry(base::OnceClosure start_retry) {
  Reset();

  // The original URL is recorded in this class instead of |loader_|, so when
  // running retry closure from SimpleUrlLoader, add back the original URL.
  url_chain_.push_back(request_params_.url);

  std::move(start_retry).Run();
}

void InMemoryDownloadImpl::SaveAsBlob() {
  auto callback = base::BindOnce(&InMemoryDownloadImpl::OnSaveBlobDone,
                                 weak_ptr_factory_.GetWeakPtr());
  auto data = std::make_unique<std::string>(std::move(data_));
  blob_task_proxy_->SaveAsBlob(std::move(data), std::move(callback));
}

void InMemoryDownloadImpl::OnSaveBlobDone(
    std::unique_ptr<storage::BlobDataHandle> blob_handle,
    storage::BlobStatus status) {
  // |status| is valid on IO thread, consumer of |blob_handle| should validate
  // the data when using the blob data.
  state_ =
      (status == storage::BlobStatus::DONE) ? State::COMPLETE : State::FAILED;

  // TODO(xingliu): Add metric for blob status code. If failed, consider remove
  // |blob_data_handle_|. See https://crbug.com/809674.
  DCHECK(data_.empty())
      << "Download data should be contained in |blob_data_handle_|.";
  blob_data_handle_ = std::move(blob_handle);
  completion_time_ = base::Time::Now();

  // Resets network backend.
  loader_.reset();

  // Not considering |paused_| here, if pause after starting a blob operation,
  // just let it finish.
  NotifyDelegateDownloadComplete();
}

void InMemoryDownloadImpl::NotifyDelegateDownloadComplete() {
  if (completion_notified_) {
    return;
  }
  completion_notified_ = true;

  delegate_->OnDownloadComplete(this);
}

void InMemoryDownloadImpl::SendRequest() {
  auto request = std::make_unique<network::ResourceRequest>();
  request->url = request_params_.url;
  request->method = request_params_.method;
  request->headers = request_params_.request_headers;
  request->load_flags = net::LOAD_DISABLE_CACHE;
  if (request_body_) {
    request->request_body = std::move(request_body_);
    request->enable_upload_progress = true;
  }
  if (request_params_.isolation_info) {
    request->site_for_cookies =
        request_params_.isolation_info->site_for_cookies();
  }

  url_chain_.push_back(request_params_.url);

  loader_ =
      network::SimpleURLLoader::Create(std::move(request), traffic_annotation_);
  loader_->SetOnRedirectCallback(base::BindRepeating(
      &InMemoryDownloadImpl::OnRedirect, weak_ptr_factory_.GetWeakPtr()));
  loader_->SetOnResponseStartedCallback(
      base::BindRepeating(&InMemoryDownloadImpl::OnResponseStarted,
                          weak_ptr_factory_.GetWeakPtr()));
  loader_->SetOnUploadProgressCallback(base::BindRepeating(
      &InMemoryDownloadImpl::OnUploadProgress, weak_ptr_factory_.GetWeakPtr()));

  // TODO(xingliu): Use SimpleURLLoader's retry when it won't hit CHECK in
  // SharedURLLoaderFactory.
  loader_->DownloadAsStream(url_loader_factory_.get(), this);
}

void InMemoryDownloadImpl::OnRedirect(
    const GURL& url_before_redirect,
    const net::RedirectInfo& redirect_info,
    const network::mojom::URLResponseHead& response_head,
    std::vector<std::string>* to_be_removed_headers) {
  url_chain_.push_back(redirect_info.new_url);
}

void InMemoryDownloadImpl::OnResponseStarted(
    const GURL& final_url,
    const network::mojom::URLResponseHead& response_head) {
  started_ = true;
  response_headers_ = response_head.headers;

  delegate_->OnDownloadStarted(this);
}

void InMemoryDownloadImpl::OnUploadProgress(uint64_t position, uint64_t total) {
  bytes_uploaded_ = position;
  delegate_->OnUploadProgress(this);
}

void InMemoryDownloadImpl::Reset() {
  data_.clear();
  url_chain_.clear();
  response_headers_.reset();
  bytes_downloaded_ = 0u;
  completion_notified_ = false;
  started_ = false;
  resume_callback_.Reset();
}

}  // namespace download