Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(41)

Side by Side Diff: storage/browser/blob/blob_storage_context.cc

Issue 2448353002: [BlobAsync] Moving async handling into BlobStorageContext & quota out. (Closed)
Patch Set: comments Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "storage/browser/blob/blob_storage_context.h" 5 #include "storage/browser/blob/blob_storage_context.h"
6 6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <algorithm> 7 #include <algorithm>
11 #include <limits> 8 #include <limits>
12 #include <memory> 9 #include <memory>
10 #include <set>
13 #include <utility> 11 #include <utility>
14 12
15 #include "base/bind.h" 13 #include "base/bind.h"
16 #include "base/callback.h" 14 #include "base/callback.h"
17 #include "base/location.h" 15 #include "base/location.h"
18 #include "base/logging.h" 16 #include "base/logging.h"
19 #include "base/memory/ptr_util.h" 17 #include "base/memory/ptr_util.h"
20 #include "base/message_loop/message_loop.h" 18 #include "base/message_loop/message_loop.h"
21 #include "base/metrics/histogram_macros.h" 19 #include "base/metrics/histogram_macros.h"
20 #include "base/numerics/safe_conversions.h"
21 #include "base/numerics/safe_math.h"
22 #include "base/task_runner.h"
22 #include "base/threading/thread_task_runner_handle.h" 23 #include "base/threading/thread_task_runner_handle.h"
23 #include "base/trace_event/trace_event.h" 24 #include "base/trace_event/trace_event.h"
24 #include "storage/browser/blob/blob_data_builder.h" 25 #include "storage/browser/blob/blob_data_builder.h"
25 #include "storage/browser/blob/blob_data_handle.h"
26 #include "storage/browser/blob/blob_data_item.h" 26 #include "storage/browser/blob/blob_data_item.h"
27 #include "storage/browser/blob/blob_data_snapshot.h" 27 #include "storage/browser/blob/blob_data_snapshot.h"
28 #include "storage/browser/blob/shareable_blob_data_item.h" 28 #include "storage/browser/blob/shareable_blob_data_item.h"
29 #include "storage/common/data_element.h"
29 #include "url/gurl.h" 30 #include "url/gurl.h"
30 31
31 namespace storage { 32 namespace storage {
32 using BlobRegistryEntry = BlobStorageRegistry::Entry; 33 namespace {
33 using BlobState = BlobStorageRegistry::BlobState; 34 using ItemCopyEntry = BlobEntry::ItemCopyEntry;
34 35 using QuotaAllocationTask = BlobMemoryController::QuotaAllocationTask;
35 BlobStorageContext::BlobStorageContext() : memory_usage_(0) {} 36
37 bool IsBytes(DataElement::Type type) {
38 return type == DataElement::TYPE_BYTES ||
39 type == DataElement::TYPE_BYTES_DESCRIPTION;
40 }
41 } // namespace
42
43 BlobStorageContext::BlobFlattener::BlobFlattener(
44 const BlobDataBuilder& input_builder,
45 BlobEntry* output_blob,
46 BlobStorageRegistry* registry) {
47 const std::string& uuid = input_builder.uuid_;
48 std::set<std::string> dependent_blob_uuids;
49
50 size_t num_files_with_unknown_size = 0;
51 size_t num_building_dependent_blobs = 0;
52
53 base::CheckedNumeric<uint64_t> checked_total_size = 0;
54 base::CheckedNumeric<uint64_t> checked_memory_quota_needed = 0;
55
56 for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
57 const DataElement& input_element = input_item->data_element();
58 DataElement::Type type = input_element.type();
59 uint64_t length = input_element.length();
60
61 if (IsBytes(type)) {
62 DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
63 checked_memory_quota_needed += length;
64 checked_total_size += length;
65 scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
66 std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
67 pending_memory_items.push_back(item);
68 transport_items.push_back(item.get());
69 output_blob->AppendSharedBlobItem(uuid, std::move(item));
70 continue;
71 }
72 if (type == DataElement::TYPE_BLOB) {
73 BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
74
75 if (!ref_entry || input_element.blob_uuid() == uuid) {
76 status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
77 return;
78 }
79
80 if (BlobStatusIsError(ref_entry->status())) {
81 status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
82 return;
83 }
84
85 if (ref_entry->total_size() == DataElement::kUnknownSize) {
86 // We can't reference a blob with unknown size.
87 status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
88 return;
89 }
90
91 if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
92 dependent_blob_uuids.end()) {
93 dependent_blobs.push_back(
94 std::make_pair(input_element.blob_uuid(), ref_entry));
95 dependent_blob_uuids.insert(input_element.blob_uuid());
96 if (BlobStatusIsPending(ref_entry->status())) {
97 num_building_dependent_blobs++;
98 }
99 }
100
101 length = length == DataElement::kUnknownSize ? ref_entry->total_size()
102 : input_element.length();
103 checked_total_size += length;
104
105 // If we're referencing the whole blob, then we don't need to slice.
106 if (input_element.offset() == 0 && length == ref_entry->total_size()) {
107 for (const auto& shareable_item : ref_entry->items()) {
108 output_blob->AppendSharedBlobItem(uuid, shareable_item);
109 }
110 continue;
111 }
112
113 // Validate our reference has good offset & length.
114 if (input_element.offset() + length > ref_entry->total_size()) {
115 status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
116 return;
117 }
118
119 BlobSlice slice(*ref_entry, input_element.offset(), length);
120
121 if (slice.first_source_item) {
122 copies.push_back(ItemCopyEntry(slice.first_source_item,
123 slice.first_item_slice_offset,
124 slice.dest_items.front()));
125 pending_memory_items.push_back(slice.dest_items.front());
126 }
127 if (slice.last_source_item) {
128 copies.push_back(
129 ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
130 pending_memory_items.push_back(slice.dest_items.back());
131 }
132 checked_memory_quota_needed += slice.copying_memory_size;
133
134 for (auto& shareable_item : slice.dest_items) {
135 output_blob->AppendSharedBlobItem(uuid, std::move(shareable_item));
136 }
137 continue;
138 }
139
140 DCHECK(!BlobDataBuilder::IsFutureFileItem(input_element))
141 << "File allocation not implemented.";
142 if (length == DataElement::kUnknownSize)
143 num_files_with_unknown_size++;
144
145 scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
146 std::move(input_item), ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
147
148 checked_total_size += length;
149 output_blob->AppendSharedBlobItem(uuid, std::move(item));
150 }
151
152 if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
153 status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
154 return;
155 }
156 if (!checked_total_size.IsValid() || !checked_memory_quota_needed.IsValid()) {
157 status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
158 return;
159 }
160 total_size = checked_total_size.ValueOrDie();
161 memory_quota_needed = checked_memory_quota_needed.ValueOrDie();
162 if (memory_quota_needed) {
163 status = BlobStatus::PENDING_QUOTA;
164 } else {
165 status = BlobStatus::PENDING_INTERNALS;
166 }
167 }
168
169 BlobStorageContext::BlobFlattener::~BlobFlattener() {}
170
171 BlobStorageContext::BlobSlice::BlobSlice(const BlobEntry& source,
172 uint64_t slice_offset,
173 uint64_t slice_size) {
174 const auto& source_items = source.items();
175 const auto& offsets = source.offsets();
176 DCHECK_LE(slice_offset + slice_size, source.total_size());
177 size_t item_index =
178 std::upper_bound(offsets.begin(), offsets.end(), slice_offset) -
179 offsets.begin();
180 uint64_t item_offset =
181 item_index == 0 ? slice_offset : slice_offset - offsets[item_index - 1];
182 size_t num_items = source_items.size();
183
184 size_t first_item_index = item_index;
185 copying_memory_size = 0;
186
187 // Read starting from 'first_item_index' and 'item_offset'.
188 for (uint64_t total_sliced = 0;
189 item_index < num_items && total_sliced < slice_size; item_index++) {
190 const scoped_refptr<BlobDataItem>& source_item =
191 source_items[item_index]->item();
192 uint64_t source_length = source_item->length();
193 DCHECK_NE(source_length, std::numeric_limits<uint64_t>::max());
194 DCHECK_NE(source_length, 0ull);
195
196 uint64_t read_size =
197 std::min(source_length - item_offset, slice_size - total_sliced);
198 total_sliced += read_size;
199
200 if (read_size == source_length) {
201 // We can share the entire item.
202 dest_items.push_back(source_items[item_index]);
203 continue;
204 }
205
206 scoped_refptr<BlobDataItem> data_item;
207 ShareableBlobDataItem::State state =
208 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA;
209 switch (source_item->type()) {
210 case DataElement::TYPE_BYTES_DESCRIPTION:
211 case DataElement::TYPE_BYTES: {
212 if (item_index == first_item_index) {
213 first_item_slice_offset = item_offset;
214 first_source_item = source_items[item_index];
215 } else {
216 last_source_item = source_items[item_index];
217 }
218 copying_memory_size += read_size;
219 // Since we don't have quota yet for memory, we create temporary items
220 // for this data. When our blob is finished constructing, all dependent
221 // blobs are done, and we have enough memory quota, we'll copy the data
222 // over.
223 std::unique_ptr<DataElement> element(new DataElement());
224 element->SetToBytesDescription(base::checked_cast<size_t>(read_size));
225 data_item = new BlobDataItem(std::move(element));
226 state = ShareableBlobDataItem::QUOTA_NEEDED;
227 break;
228 }
229 case DataElement::TYPE_FILE: {
230 std::unique_ptr<DataElement> element(new DataElement());
231 element->SetToFilePathRange(
232 source_item->path(), source_item->offset() + item_offset, read_size,
233 source_item->expected_modification_time());
234 data_item =
235 new BlobDataItem(std::move(element), source_item->data_handle_);
236
237 DCHECK(!BlobDataBuilder::IsFutureFileItem(source_item->data_element()))
238 << "File allocation unimplemented.";
239 break;
240 }
241 case DataElement::TYPE_FILE_FILESYSTEM: {
242 std::unique_ptr<DataElement> element(new DataElement());
243 element->SetToFileSystemUrlRange(
244 source_item->filesystem_url(), source_item->offset() + item_offset,
245 read_size, source_item->expected_modification_time());
246 data_item = new BlobDataItem(std::move(element));
247 break;
248 }
249 case DataElement::TYPE_DISK_CACHE_ENTRY: {
250 std::unique_ptr<DataElement> element(new DataElement());
251 element->SetToDiskCacheEntryRange(source_item->offset() + item_offset,
252 read_size);
253 data_item =
254 new BlobDataItem(std::move(element), source_item->data_handle_,
255 source_item->disk_cache_entry(),
256 source_item->disk_cache_stream_index(),
257 source_item->disk_cache_side_stream_index());
258 break;
259 }
260 case DataElement::TYPE_BLOB:
261 case DataElement::TYPE_UNKNOWN:
262 CHECK(false) << "Illegal blob item type: " << source_item->type();
263 }
264 dest_items.push_back(
265 new ShareableBlobDataItem(std::move(data_item), state));
266 item_offset = 0;
267 }
268 }
269
270 BlobStorageContext::BlobSlice::~BlobSlice() {}
271
272 BlobStorageContext::BlobStorageContext()
273 : memory_controller_(base::FilePath(), scoped_refptr<base::TaskRunner>()),
274 ptr_factory_(this) {}
36 275
37 BlobStorageContext::~BlobStorageContext() { 276 BlobStorageContext::~BlobStorageContext() {
38 } 277 }
39 278
40 std::unique_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromUUID( 279 std::unique_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromUUID(
41 const std::string& uuid) { 280 const std::string& uuid) {
42 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 281 BlobEntry* entry = registry_.GetEntry(uuid);
43 if (!entry) { 282 if (!entry)
44 return nullptr; 283 return nullptr;
45 } 284 return CreateHandle(uuid, entry);
46 return base::WrapUnique(
47 new BlobDataHandle(uuid, entry->content_type, entry->content_disposition,
48 this, base::ThreadTaskRunnerHandle::Get().get()));
49 } 285 }
50 286
51 std::unique_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromPublicURL( 287 std::unique_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromPublicURL(
52 const GURL& url) { 288 const GURL& url) {
53 std::string uuid; 289 std::string uuid;
54 BlobRegistryEntry* entry = registry_.GetEntryFromURL(url, &uuid); 290 BlobEntry* entry = registry_.GetEntryFromURL(url, &uuid);
55 if (!entry) { 291 if (!entry)
56 return nullptr; 292 return nullptr;
57 } 293 return CreateHandle(uuid, entry);
58 return base::WrapUnique(
59 new BlobDataHandle(uuid, entry->content_type, entry->content_disposition,
60 this, base::ThreadTaskRunnerHandle::Get().get()));
61 } 294 }
62 295
63 std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob( 296 std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob(
64 const BlobDataBuilder& external_builder) { 297 const BlobDataBuilder& external_builder) {
65 TRACE_EVENT0("Blob", "Context::AddFinishedBlob"); 298 TRACE_EVENT0("Blob", "Context::AddFinishedBlob");
66 CreatePendingBlob(external_builder.uuid(), external_builder.content_type_, 299 return BuildBlob(external_builder, TransportAllowedCallback());
67 external_builder.content_disposition_);
68 CompletePendingBlob(external_builder);
69 std::unique_ptr<BlobDataHandle> handle =
70 GetBlobDataFromUUID(external_builder.uuid_);
71 DecrementBlobRefCount(external_builder.uuid_);
72 return handle;
73 } 300 }
74 301
75 std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob( 302 std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob(
76 const BlobDataBuilder* builder) { 303 const BlobDataBuilder* builder) {
77 DCHECK(builder); 304 DCHECK(builder);
78 return AddFinishedBlob(*builder); 305 return AddFinishedBlob(*builder);
79 } 306 }
80 307
308 std::unique_ptr<BlobDataHandle> BlobStorageContext::AddBrokenBlob(
309 const std::string& uuid,
310 const std::string& content_type,
311 const std::string& content_disposition,
312 BlobStatus reason) {
313 DCHECK(!registry_.HasEntry(uuid));
314 DCHECK(BlobStatusIsError(reason));
315 BlobEntry* entry =
316 registry_.CreateEntry(uuid, content_type, content_disposition);
317 entry->set_status(reason);
318 FinishBuilding(entry);
319 return CreateHandle(uuid, entry);
320 }
321
81 bool BlobStorageContext::RegisterPublicBlobURL(const GURL& blob_url, 322 bool BlobStorageContext::RegisterPublicBlobURL(const GURL& blob_url,
82 const std::string& uuid) { 323 const std::string& uuid) {
83 if (!registry_.CreateUrlMapping(blob_url, uuid)) { 324 if (!registry_.CreateUrlMapping(blob_url, uuid))
84 return false; 325 return false;
85 }
86 IncrementBlobRefCount(uuid); 326 IncrementBlobRefCount(uuid);
87 return true; 327 return true;
88 } 328 }
89 329
90 void BlobStorageContext::RevokePublicBlobURL(const GURL& blob_url) { 330 void BlobStorageContext::RevokePublicBlobURL(const GURL& blob_url) {
91 std::string uuid; 331 std::string uuid;
92 if (!registry_.DeleteURLMapping(blob_url, &uuid)) { 332 if (!registry_.DeleteURLMapping(blob_url, &uuid))
93 return; 333 return;
94 }
95 DecrementBlobRefCount(uuid); 334 DecrementBlobRefCount(uuid);
96 } 335 }
97 336
98 void BlobStorageContext::CreatePendingBlob( 337 std::unique_ptr<BlobDataHandle> BlobStorageContext::BuildBlob(
99 const std::string& uuid, 338 const BlobDataBuilder& content,
100 const std::string& content_type, 339 const TransportAllowedCallback& can_populate_memory) {
101 const std::string& content_disposition) { 340 DCHECK(!registry_.HasEntry(content.uuid_));
102 DCHECK(!registry_.GetEntry(uuid) && !uuid.empty()); 341
103 registry_.CreateEntry(uuid, content_type, content_disposition); 342 BlobEntry* entry = registry_.CreateEntry(
343 content.uuid(), content.content_type_, content.content_disposition_);
344
345 // This flattens all blob references in the transportion content out and
346 // stores the complete item representation in the internal data.
347 BlobFlattener flattener(content, entry, &registry_);
348
349 DCHECK(flattener.status != BlobStatus::PENDING_TRANSPORT ||
350 !can_populate_memory)
351 << "There is no pending content for the user to populate, so the "
352 "callback should be null.";
353 DCHECK(flattener.status != BlobStatus::PENDING_TRANSPORT ||
354 can_populate_memory)
355 << "If we have pending content then there needs to be a callback "
356 "present.";
357
358 entry->set_size(flattener.total_size);
359 entry->set_status(flattener.status);
360 std::unique_ptr<BlobDataHandle> handle = CreateHandle(content.uuid_, entry);
361
362 size_t num_building_dependent_blobs = 0;
363 std::vector<std::unique_ptr<BlobDataHandle>> dependent_blobs;
364 // We hold a handle to all blobs we're using. This is important, as our memory
365 // accounting can be delayed until OnEnoughSizeForBlobData is called, and we
366 // only free memory on canceling when we've done this accounting. If a
367 // dependent blob is dereferenced, then we're the last blob holding onto that
368 // data item, and we need to account for that. So we prevent that case by
369 // holding onto all blobs.
370 for (const std::pair<std::string, BlobEntry*>& pending_blob :
371 flattener.dependent_blobs) {
372 dependent_blobs.push_back(
373 CreateHandle(pending_blob.first, pending_blob.second));
374 if (BlobStatusIsPending(pending_blob.second->status())) {
375 pending_blob.second->building_state_->build_completion_callbacks
376 .push_back(base::Bind(&BlobStorageContext::OnDependentBlobFinished,
377 ptr_factory_.GetWeakPtr(), content.uuid_));
378 num_building_dependent_blobs++;
379 }
380 }
381
382 entry->set_building_state(base::MakeUnique<BlobEntry::BuildingState>(
383 !flattener.transport_items.empty(), can_populate_memory,
384 num_building_dependent_blobs));
385 BlobEntry::BuildingState* building_state = entry->building_state_.get();
386 std::swap(building_state->copies, flattener.copies);
387 std::swap(building_state->dependent_blobs, dependent_blobs);
388 std::swap(building_state->transport_items, flattener.transport_items);
389
390 // Break ourselves if we have an error. BuildingState must be set first so the
391 // callback is called correctly.
392 if (BlobStatusIsError(flattener.status)) {
393 CancelBuildingBlobInternal(content.uuid(), entry, flattener.status);
394 return handle;
395 }
396
397 if (!memory_controller_.CanReserveQuota(flattener.memory_quota_needed)) {
398 CancelBuildingBlobInternal(content.uuid(), entry,
399 BlobStatus::ERR_OUT_OF_MEMORY);
400 return handle;
401 }
402
403 if (flattener.memory_quota_needed > 0) {
404 // The blob can complete during the execution of this line.
405 base::WeakPtr<QuotaAllocationTask> pending_request =
406 memory_controller_.ReserveMemoryQuota(
407 std::move(flattener.pending_memory_items),
408 base::Bind(&BlobStorageContext::OnEnoughSizeForMemory,
409 ptr_factory_.GetWeakPtr(), content.uuid_));
410 // Building state will be null if the blob is already finished.
411 if (entry->building_state_)
412 entry->building_state_->memory_quota_request = std::move(pending_request);
413 }
414
415 if (entry->CanFinishBuilding())
416 FinishBuilding(entry);
417
418 return handle;
104 } 419 }
105 420
106 void BlobStorageContext::CompletePendingBlob( 421 void BlobStorageContext::CancelBuildingBlob(const std::string& uuid,
107 const BlobDataBuilder& external_builder) { 422 BlobStatus reason) {
108 BlobRegistryEntry* entry = registry_.GetEntry(external_builder.uuid()); 423 CancelBuildingBlobInternal(uuid, registry_.GetEntry(uuid), reason);
109 DCHECK(entry);
110 DCHECK(!entry->data.get()) << "Blob already constructed: "
111 << external_builder.uuid();
112 // We want to handle storing our broken blob as well.
113 switch (entry->state) {
114 case BlobState::PENDING: {
115 entry->data_builder.reset(new InternalBlobData::Builder());
116 InternalBlobData::Builder* internal_data_builder =
117 entry->data_builder.get();
118
119 bool broken = false;
120 for (const auto& blob_item : external_builder.items_) {
121 IPCBlobCreationCancelCode error_code;
122 if (!AppendAllocatedBlobItem(external_builder.uuid_, blob_item,
123 internal_data_builder, &error_code)) {
124 broken = true;
125 memory_usage_ -= entry->data_builder->GetNonsharedMemoryUsage();
126 entry->state = BlobState::BROKEN;
127 entry->broken_reason = error_code;
128 entry->data_builder.reset(new InternalBlobData::Builder());
129 break;
130 }
131 }
132 entry->data = entry->data_builder->Build();
133 entry->data_builder.reset();
134 entry->state = broken ? BlobState::BROKEN : BlobState::COMPLETE;
135 break;
136 }
137 case BlobState::BROKEN: {
138 InternalBlobData::Builder builder;
139 entry->data = builder.Build();
140 break;
141 }
142 case BlobState::COMPLETE:
143 DCHECK(false) << "Blob already constructed: " << external_builder.uuid();
144 return;
145 }
146
147 UMA_HISTOGRAM_COUNTS("Storage.Blob.ItemCount", entry->data->items().size());
148 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.Broken",
149 entry->state == BlobState::BROKEN);
150 if (entry->state == BlobState::BROKEN) {
151 UMA_HISTOGRAM_ENUMERATION(
152 "Storage.Blob.BrokenReason", static_cast<int>(entry->broken_reason),
153 (static_cast<int>(IPCBlobCreationCancelCode::LAST) + 1));
154 }
155 size_t total_memory = 0, nonshared_memory = 0;
156 entry->data->GetMemoryUsage(&total_memory, &nonshared_memory);
157 UMA_HISTOGRAM_COUNTS("Storage.Blob.TotalSize", total_memory / 1024);
158 UMA_HISTOGRAM_COUNTS("Storage.Blob.TotalUnsharedSize",
159 nonshared_memory / 1024);
160 TRACE_COUNTER1("Blob", "MemoryStoreUsageBytes", memory_usage_);
161
162 auto runner = base::ThreadTaskRunnerHandle::Get();
163 for (const auto& callback : entry->build_completion_callbacks) {
164 runner->PostTask(FROM_HERE,
165 base::Bind(callback, entry->state == BlobState::COMPLETE,
166 entry->broken_reason));
167 }
168 entry->build_completion_callbacks.clear();
169 } 424 }
170 425
171 void BlobStorageContext::CancelPendingBlob(const std::string& uuid, 426 void BlobStorageContext::NotifyTransportComplete(const std::string& uuid) {
172 IPCBlobCreationCancelCode reason) { 427 BlobEntry* entry = registry_.GetEntry(uuid);
173 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 428 CHECK(entry) << "There is no blob entry with uuid " << uuid;
174 DCHECK(entry && entry->state == BlobState::PENDING); 429 DCHECK(BlobStatusIsPending(entry->status()));
175 entry->state = BlobState::BROKEN; 430 NotifyTransportCompleteInternal(entry);
176 entry->broken_reason = reason;
177 CompletePendingBlob(BlobDataBuilder(uuid));
178 } 431 }
179 432
180 void BlobStorageContext::IncrementBlobRefCount(const std::string& uuid) { 433 void BlobStorageContext::IncrementBlobRefCount(const std::string& uuid) {
181 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 434 BlobEntry* entry = registry_.GetEntry(uuid);
182 DCHECK(entry); 435 DCHECK(entry);
183 ++(entry->refcount); 436 entry->IncrementRefCount();
184 } 437 }
185 438
186 void BlobStorageContext::DecrementBlobRefCount(const std::string& uuid) { 439 void BlobStorageContext::DecrementBlobRefCount(const std::string& uuid) {
187 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 440 BlobEntry* entry = registry_.GetEntry(uuid);
188 DCHECK(entry); 441 DCHECK(entry);
189 DCHECK_GT(entry->refcount, 0u); 442 DCHECK_GT(entry->refcount(), 0u);
190 if (--(entry->refcount) == 0) { 443 entry->DecrementRefCount();
191 size_t memory_freeing = 0; 444 if (entry->refcount() == 0) {
192 if (entry->state == BlobState::COMPLETE) { 445 ClearAndFreeMemory(uuid, entry);
193 memory_freeing = entry->data->GetUnsharedMemoryUsage();
194 entry->data->RemoveBlobFromShareableItems(uuid);
195 }
196 DCHECK_LE(memory_freeing, memory_usage_);
197 memory_usage_ -= memory_freeing;
198 registry_.DeleteEntry(uuid); 446 registry_.DeleteEntry(uuid);
199 } 447 }
200 } 448 }
201 449
202 std::unique_ptr<BlobDataSnapshot> BlobStorageContext::CreateSnapshot( 450 std::unique_ptr<BlobDataSnapshot> BlobStorageContext::CreateSnapshot(
203 const std::string& uuid) { 451 const std::string& uuid) {
204 std::unique_ptr<BlobDataSnapshot> result; 452 std::unique_ptr<BlobDataSnapshot> result;
205 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 453 BlobEntry* entry = registry_.GetEntry(uuid);
206 if (entry->state != BlobState::COMPLETE) { 454 if (entry->status() != BlobStatus::DONE)
207 return result; 455 return result;
208 } 456
209
210 const InternalBlobData& data = *entry->data;
211 std::unique_ptr<BlobDataSnapshot> snapshot(new BlobDataSnapshot( 457 std::unique_ptr<BlobDataSnapshot> snapshot(new BlobDataSnapshot(
212 uuid, entry->content_type, entry->content_disposition)); 458 uuid, entry->content_type(), entry->content_disposition()));
213 snapshot->items_.reserve(data.items().size()); 459 snapshot->items_.reserve(entry->items().size());
214 for (const auto& shareable_item : data.items()) { 460 for (const auto& shareable_item : entry->items()) {
215 snapshot->items_.push_back(shareable_item->item()); 461 snapshot->items_.push_back(shareable_item->item());
216 } 462 }
463 memory_controller_.NotifyMemoryItemsUsed(entry->items());
217 return snapshot; 464 return snapshot;
218 } 465 }
219 466
220 bool BlobStorageContext::IsBroken(const std::string& uuid) const { 467 BlobStatus BlobStorageContext::GetBlobStatus(const std::string& uuid) const {
221 const BlobRegistryEntry* entry = registry_.GetEntry(uuid); 468 const BlobEntry* entry = registry_.GetEntry(uuid);
222 if (!entry) { 469 if (!entry)
223 return true; 470 return BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
224 } 471 return entry->status();
225 return entry->state == BlobState::BROKEN;
226 }
227
228 bool BlobStorageContext::IsBeingBuilt(const std::string& uuid) const {
229 const BlobRegistryEntry* entry = registry_.GetEntry(uuid);
230 if (!entry) {
231 return false;
232 }
233 return entry->state == BlobState::PENDING;
234 } 472 }
235 473
236 void BlobStorageContext::RunOnConstructionComplete( 474 void BlobStorageContext::RunOnConstructionComplete(
237 const std::string& uuid, 475 const std::string& uuid,
238 const BlobConstructedCallback& done) { 476 const BlobStatusCallback& done) {
239 BlobRegistryEntry* entry = registry_.GetEntry(uuid); 477 BlobEntry* entry = registry_.GetEntry(uuid);
240 DCHECK(entry); 478 DCHECK(entry);
241 switch (entry->state) { 479 if (BlobStatusIsPending(entry->status())) {
242 case BlobState::COMPLETE: 480 entry->building_state_->build_completion_callbacks.push_back(done);
243 done.Run(true, IPCBlobCreationCancelCode::UNKNOWN); 481 return;
244 return; 482 }
245 case BlobState::BROKEN: 483 done.Run(entry->status());
246 done.Run(false, entry->broken_reason); 484 }
247 return; 485
248 case BlobState::PENDING: 486 std::unique_ptr<BlobDataHandle> BlobStorageContext::CreateHandle(
249 entry->build_completion_callbacks.push_back(done); 487 const std::string& uuid,
250 return; 488 BlobEntry* entry) {
251 } 489 return base::WrapUnique(new BlobDataHandle(
252 NOTREACHED(); 490 uuid, entry->content_type_, entry->content_disposition_, entry->size_,
253 } 491 this, base::ThreadTaskRunnerHandle::Get().get()));
254 492 }
255 bool BlobStorageContext::AppendAllocatedBlobItem( 493
256 const std::string& target_blob_uuid, 494 void BlobStorageContext::NotifyTransportCompleteInternal(BlobEntry* entry) {
257 scoped_refptr<BlobDataItem> blob_item, 495 DCHECK(entry);
258 InternalBlobData::Builder* target_blob_builder, 496 for (ShareableBlobDataItem* shareable_item :
259 IPCBlobCreationCancelCode* error_code) { 497 entry->building_state_->transport_items) {
260 DCHECK(error_code); 498 DCHECK(shareable_item->state() == ShareableBlobDataItem::QUOTA_GRANTED);
261 *error_code = IPCBlobCreationCancelCode::UNKNOWN; 499 shareable_item->set_state(ShareableBlobDataItem::POPULATED_WITH_QUOTA);
262 bool error = false; 500 }
263 501 entry->set_status(BlobStatus::PENDING_INTERNALS);
264 // The blob data is stored in the canonical way which only contains a 502 if (entry->CanFinishBuilding())
265 // list of Data, File, and FileSystem items. Aggregated TYPE_BLOB items 503 FinishBuilding(entry);
266 // are expanded into the primitive constituent types and reused if possible. 504 }
267 // 1) The Data item is denoted by the raw data and length. 505
268 // 2) The File item is denoted by the file path, the range and the expected 506 void BlobStorageContext::CancelBuildingBlobInternal(const std::string& uuid,
269 // modification time. 507 BlobEntry* entry,
270 // 3) The FileSystem File item is denoted by the FileSystem URL, the range 508 BlobStatus reason) {
271 // and the expected modification time. 509 DCHECK(entry);
272 // 4) The Blob item is denoted by the source blob and an offset and size. 510 DCHECK(BlobStatusIsError(reason));
273 // Internal items that are fully used by the new blob (not cut by the 511 TransportAllowedCallback transport_allowed_callback;
274 // offset or size) are shared between the blobs. Otherwise, the relevant 512 if (entry->building_state_ &&
275 // portion of the item is copied. 513 entry->building_state_->transport_allowed_callback) {
276 514 transport_allowed_callback =
277 DCHECK(blob_item->data_element_ptr()); 515 entry->building_state_->transport_allowed_callback;
278 const DataElement& data_element = blob_item->data_element(); 516 entry->building_state_->transport_allowed_callback.Reset();
279 uint64_t length = data_element.length(); 517 }
280 uint64_t offset = data_element.offset(); 518 ClearAndFreeMemory(uuid, entry);
281 UMA_HISTOGRAM_COUNTS("Storage.Blob.StorageSizeBeforeAppend", 519 entry->set_status(reason);
282 memory_usage_ / 1024); 520 if (transport_allowed_callback) {
283 switch (data_element.type()) { 521 transport_allowed_callback.Run(
284 case DataElement::TYPE_BYTES: 522 reason, std::vector<BlobMemoryController::FileCreationInfo>());
285 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.Bytes", length / 1024); 523 }
286 DCHECK(!offset); 524 FinishBuilding(entry);
287 if (memory_usage_ + length > kBlobStorageMaxMemoryUsage) { 525 }
288 error = true; 526
289 *error_code = IPCBlobCreationCancelCode::OUT_OF_MEMORY; 527 void BlobStorageContext::FinishBuilding(BlobEntry* entry) {
290 break; 528 DCHECK(entry);
529
530 if (BlobStatusIsPending(entry->status_)) {
531 for (const ItemCopyEntry& copy : entry->building_state_->copies) {
532 // Our source item can be a file if it was a slice of an unpopulated file,
533 // or a slice of data that was then paged to disk.
534 size_t dest_size = static_cast<size_t>(copy.dest_item->item()->length());
535 DataElement::Type dest_type = copy.dest_item->item()->type();
536 switch (copy.source_item->item()->type()) {
537 case DataElement::TYPE_BYTES: {
538 DCHECK_EQ(dest_type, DataElement::TYPE_BYTES_DESCRIPTION);
539 const char* src_data =
540 copy.source_item->item()->bytes() + copy.source_item_offset;
541 copy.dest_item->item()->item_->SetToBytes(src_data, dest_size);
542 } break;
543 case DataElement::TYPE_FILE:
544 case DataElement::TYPE_UNKNOWN:
545 case DataElement::TYPE_BLOB:
546 case DataElement::TYPE_BYTES_DESCRIPTION:
547 case DataElement::TYPE_FILE_FILESYSTEM:
548 case DataElement::TYPE_DISK_CACHE_ENTRY:
549 NOTREACHED();
550 break;
291 } 551 }
292 memory_usage_ += length; 552 copy.dest_item->set_state(ShareableBlobDataItem::POPULATED_WITH_QUOTA);
293 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
294 target_blob_uuid, blob_item,
295 ShareableBlobDataItem::POPULATED_WITH_QUOTA));
296 break;
297 case DataElement::TYPE_FILE: {
298 bool full_file = (length == std::numeric_limits<uint64_t>::max());
299 UMA_HISTOGRAM_BOOLEAN("Storage.BlobItemSize.File.Unknown", full_file);
300 if (!full_file) {
301 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.File",
302 (length - offset) / 1024);
303 }
304 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
305 target_blob_uuid, blob_item,
306 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA));
307 break;
308 } 553 }
309 case DataElement::TYPE_FILE_FILESYSTEM: { 554 entry->set_status(BlobStatus::DONE);
310 bool full_file = (length == std::numeric_limits<uint64_t>::max()); 555 }
311 UMA_HISTOGRAM_BOOLEAN("Storage.BlobItemSize.FileSystem.Unknown", 556
312 full_file); 557 std::vector<BlobStatusCallback> callbacks;
313 if (!full_file) { 558 if (entry->building_state_.get()) {
314 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.FileSystem", 559 std::swap(callbacks, entry->building_state_->build_completion_callbacks);
315 (length - offset) / 1024); 560 entry->building_state_.reset();
316 } 561 }
317 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem( 562
318 target_blob_uuid, blob_item, 563 memory_controller_.NotifyMemoryItemsUsed(entry->items());
319 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA)); 564
320 break; 565 auto runner = base::ThreadTaskRunnerHandle::Get();
566 for (const auto& callback : callbacks)
567 runner->PostTask(FROM_HERE, base::Bind(callback, entry->status()));
568
569 for (const auto& shareable_item : entry->items()) {
570 DCHECK_NE(DataElement::TYPE_BYTES_DESCRIPTION,
571 shareable_item->item()->type());
572 DCHECK(shareable_item->IsPopulated()) << shareable_item->state();
573 }
574 }
575
576 void BlobStorageContext::RequestTransport(
577 BlobEntry* entry,
578 std::vector<BlobMemoryController::FileCreationInfo> files) {
579 BlobEntry::BuildingState* building_state = entry->building_state_.get();
580 if (building_state->transport_allowed_callback) {
581 TransportAllowedCallback user_data_population_callback =
582 building_state->transport_allowed_callback;
583 building_state->transport_allowed_callback.Reset();
584 user_data_population_callback.Run(BlobStatus::PENDING_TRANSPORT,
585 std::move(files));
kinuko 2016/11/16 03:53:51 nit: base::ResetAndReturn can be probably used her
dmurph 2016/11/16 20:05:01 Done.
586 return;
587 }
588 DCHECK(files.empty());
589 NotifyTransportCompleteInternal(entry);
590 }
591
592 void BlobStorageContext::OnEnoughSizeForMemory(const std::string& uuid,
593 bool success) {
594 if (!success) {
595 CancelBuildingBlob(uuid, BlobStatus::ERR_OUT_OF_MEMORY);
596 return;
597 }
598 BlobEntry* entry = registry_.GetEntry(uuid);
599 if (!entry || !entry->building_state_.get())
600 return;
601 BlobEntry::BuildingState& building_state = *entry->building_state_;
602 DCHECK(!building_state.memory_quota_request);
603
604 if (building_state.transport_items_present) {
605 entry->set_status(BlobStatus::PENDING_TRANSPORT);
606 RequestTransport(entry,
607 std::vector<BlobMemoryController::FileCreationInfo>());
608 } else {
609 entry->set_status(BlobStatus::PENDING_INTERNALS);
610 }
611
612 if (entry->CanFinishBuilding())
613 FinishBuilding(entry);
614 }
615
616 void BlobStorageContext::OnDependentBlobFinished(
617 const std::string& owning_blob_uuid,
618 BlobStatus status) {
619 BlobEntry* entry = registry_.GetEntry(owning_blob_uuid);
620 if (!entry || !entry->building_state_)
621 return;
622
623 if (BlobStatusIsError(status)) {
624 DCHECK_NE(BlobStatus::ERR_BLOB_DEREFERENCED_WHILE_BUILDING, status)
625 << "Referenced blob should never be dereferenced while we "
626 << "are depending on it, as our system holds a handle.";
627 CancelBuildingBlobInternal(owning_blob_uuid, entry,
628 BlobStatus::ERR_REFERENCED_BLOB_BROKEN);
629 return;
630 }
631 DCHECK_GT(entry->building_state_->num_building_dependent_blobs, 0u);
632 --entry->building_state_->num_building_dependent_blobs;
633
634 if (entry->CanFinishBuilding())
635 FinishBuilding(entry);
636 }
637
638 void BlobStorageContext::ClearAndFreeMemory(const std::string& uuid,
639 BlobEntry* entry) {
640 if (entry->building_state_) {
641 BlobEntry::BuildingState* building_state = entry->building_state_.get();
642 if (building_state->memory_quota_request) {
643 building_state->memory_quota_request->Cancel();
321 } 644 }
322 case DataElement::TYPE_BLOB: { 645 }
323 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.Blob", 646 entry->RemoveBlobFromShareableItems(uuid);
324 (length - offset) / 1024); 647 entry->ClearItems();
325 // We grab the handle to ensure it stays around while we copy it. 648 entry->ClearOffsets();
326 std::unique_ptr<BlobDataHandle> src = 649 entry->set_size(0);
327 GetBlobDataFromUUID(data_element.blob_uuid());
328 if (!src || src->IsBroken() || src->IsBeingBuilt()) {
329 error = true;
330 *error_code = IPCBlobCreationCancelCode::REFERENCED_BLOB_BROKEN;
331 break;
332 }
333 BlobRegistryEntry* other_entry =
334 registry_.GetEntry(data_element.blob_uuid());
335 DCHECK(other_entry->data);
336 if (!AppendBlob(target_blob_uuid, *other_entry->data, offset, length,
337 target_blob_builder)) {
338 error = true;
339 *error_code = IPCBlobCreationCancelCode::OUT_OF_MEMORY;
340 }
341 break;
342 }
343 case DataElement::TYPE_DISK_CACHE_ENTRY: {
344 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.CacheEntry",
345 (length - offset) / 1024);
346 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
347 target_blob_uuid, blob_item,
348 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA));
349 break;
350 }
351 case DataElement::TYPE_BYTES_DESCRIPTION:
352 case DataElement::TYPE_UNKNOWN:
353 NOTREACHED();
354 break;
355 }
356 UMA_HISTOGRAM_COUNTS("Storage.Blob.StorageSizeAfterAppend",
357 memory_usage_ / 1024);
358 return !error;
359 }
360
361 bool BlobStorageContext::AppendBlob(
362 const std::string& target_blob_uuid,
363 const InternalBlobData& blob,
364 uint64_t offset,
365 uint64_t length,
366 InternalBlobData::Builder* target_blob_builder) {
367 DCHECK_GT(length, 0ull);
368
369 const std::vector<scoped_refptr<ShareableBlobDataItem>>& items = blob.items();
370 auto iter = items.begin();
371 if (offset) {
372 for (; iter != items.end(); ++iter) {
373 const BlobDataItem& item = *(iter->get()->item());
374 if (offset >= item.length())
375 offset -= item.length();
376 else
377 break;
378 }
379 }
380
381 for (; iter != items.end() && length > 0; ++iter) {
382 scoped_refptr<ShareableBlobDataItem> shareable_item = iter->get();
383 const BlobDataItem& item = *(shareable_item->item());
384 uint64_t item_length = item.length();
385 DCHECK_GT(item_length, offset);
386 uint64_t current_length = item_length - offset;
387 uint64_t new_length = current_length > length ? length : current_length;
388
389 bool reusing_blob_item = offset == 0 && new_length == item.length();
390 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.ReusedItem", reusing_blob_item);
391 if (reusing_blob_item) {
392 shareable_item->referencing_blobs_mutable()->insert(target_blob_uuid);
393 target_blob_builder->AppendSharedBlobItem(shareable_item);
394 length -= new_length;
395 continue;
396 }
397
398 // We need to do copying of the items when we have a different offset or
399 // length
400 switch (item.type()) {
401 case DataElement::TYPE_BYTES: {
402 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.BlobSlice.Bytes",
403 new_length / 1024);
404 if (memory_usage_ + new_length > kBlobStorageMaxMemoryUsage) {
405 return false;
406 }
407 DCHECK(!item.offset());
408 std::unique_ptr<DataElement> element(new DataElement());
409 element->SetToBytes(item.bytes() + offset,
410 static_cast<int64_t>(new_length));
411 memory_usage_ += new_length;
412 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
413 target_blob_uuid, new BlobDataItem(std::move(element)),
414 ShareableBlobDataItem::POPULATED_WITH_QUOTA));
415 } break;
416 case DataElement::TYPE_FILE: {
417 DCHECK_NE(item.length(), std::numeric_limits<uint64_t>::max())
418 << "We cannot use a section of a file with an unknown length";
419 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.BlobSlice.File",
420 new_length / 1024);
421 std::unique_ptr<DataElement> element(new DataElement());
422 element->SetToFilePathRange(item.path(), item.offset() + offset,
423 new_length,
424 item.expected_modification_time());
425 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
426 target_blob_uuid,
427 new BlobDataItem(std::move(element), item.data_handle_),
428 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA));
429 } break;
430 case DataElement::TYPE_FILE_FILESYSTEM: {
431 UMA_HISTOGRAM_COUNTS("Storage.BlobItemSize.BlobSlice.FileSystem",
432 new_length / 1024);
433 std::unique_ptr<DataElement> element(new DataElement());
434 element->SetToFileSystemUrlRange(item.filesystem_url(),
435 item.offset() + offset, new_length,
436 item.expected_modification_time());
437 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
438 target_blob_uuid, new BlobDataItem(std::move(element)),
439 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA));
440 } break;
441 case DataElement::TYPE_DISK_CACHE_ENTRY: {
442 std::unique_ptr<DataElement> element(new DataElement());
443 element->SetToDiskCacheEntryRange(item.offset() + offset,
444 new_length);
445 target_blob_builder->AppendSharedBlobItem(new ShareableBlobDataItem(
446 target_blob_uuid,
447 new BlobDataItem(std::move(element), item.data_handle_,
448 item.disk_cache_entry(),
449 item.disk_cache_stream_index(),
450 item.disk_cache_side_stream_index()),
451 ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA));
452 } break;
453 case DataElement::TYPE_BYTES_DESCRIPTION:
454 case DataElement::TYPE_BLOB:
455 case DataElement::TYPE_UNKNOWN:
456 CHECK(false) << "Illegal blob item type: " << item.type();
457 }
458 length -= new_length;
459 offset = 0;
460 }
461 return true;
462 } 650 }
463 651
464 } // namespace storage 652 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698