summaryrefslogtreecommitdiffstats
path: root/storage/browser/blob/blob_storage_context.cc
blob: 554c84e278e7725404cafe4386b69029bf114e01 (plain)
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
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "storage/browser/blob/blob_storage_context.h"

#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/message_loop/message_loop_proxy.h"
#include "storage/browser/blob/blob_data_handle.h"
#include "storage/common/blob/blob_data.h"
#include "url/gurl.h"

namespace storage {

namespace {

// We can't use GURL directly for these hash fragment manipulations
// since it doesn't have specific knowlege of the BlobURL format. GURL
// treats BlobURLs as if they were PathURLs which don't support hash
// fragments.

bool BlobUrlHasRef(const GURL& url) {
  return url.spec().find('#') != std::string::npos;
}

GURL ClearBlobUrlRef(const GURL& url) {
  size_t hash_pos = url.spec().find('#');
  if (hash_pos == std::string::npos)
    return url;
  return GURL(url.spec().substr(0, hash_pos));
}

// TODO(michaeln): use base::SysInfo::AmountOfPhysicalMemoryMB() in some
// way to come up with a better limit.
static const int64 kMaxMemoryUsage = 500 * 1024 * 1024;  // Half a gig.

}  // namespace

BlobStorageContext::BlobMapEntry::BlobMapEntry()
    : refcount(0), flags(0) {
}

BlobStorageContext::BlobMapEntry::BlobMapEntry(
    int refcount, int flags, BlobData* data)
    : refcount(refcount), flags(flags), data(data) {
}

BlobStorageContext::BlobMapEntry::~BlobMapEntry() {
}

BlobStorageContext::BlobStorageContext()
    : memory_usage_(0) {
}

BlobStorageContext::~BlobStorageContext() {
}

scoped_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromUUID(
    const std::string& uuid) {
  scoped_ptr<BlobDataHandle> result;
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end())
    return result.Pass();
  if (found->second.flags & EXCEEDED_MEMORY)
    return result.Pass();
  DCHECK(!(found->second.flags & BEING_BUILT));
  result.reset(new BlobDataHandle(
      found->second.data.get(), this, base::MessageLoopProxy::current().get()));
  return result.Pass();
}

scoped_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromPublicURL(
    const GURL& url) {
  BlobURLMap::iterator found = public_blob_urls_.find(
      BlobUrlHasRef(url) ? ClearBlobUrlRef(url) : url);
  if (found == public_blob_urls_.end())
    return scoped_ptr<BlobDataHandle>();
  return GetBlobDataFromUUID(found->second);
}

scoped_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob(
    const BlobData* data) {
  StartBuildingBlob(data->uuid());
  for (std::vector<BlobData::Item>::const_iterator iter =
           data->items().begin();
       iter != data->items().end(); ++iter) {
    AppendBlobDataItem(data->uuid(), *iter);
  }
  FinishBuildingBlob(data->uuid(), data->content_type());
  scoped_ptr<BlobDataHandle> handle = GetBlobDataFromUUID(data->uuid());
  DecrementBlobRefCount(data->uuid());
  return handle.Pass();
}

bool BlobStorageContext::RegisterPublicBlobURL(
    const GURL& blob_url, const std::string& uuid) {
  DCHECK(!BlobUrlHasRef(blob_url));
  DCHECK(IsInUse(uuid));
  DCHECK(!IsUrlRegistered(blob_url));
  if (!IsInUse(uuid) || IsUrlRegistered(blob_url))
    return false;
  IncrementBlobRefCount(uuid);
  public_blob_urls_[blob_url] = uuid;
  return true;
}

void BlobStorageContext::RevokePublicBlobURL(const GURL& blob_url) {
  DCHECK(!BlobUrlHasRef(blob_url));
  if (!IsUrlRegistered(blob_url))
    return;
  DecrementBlobRefCount(public_blob_urls_[blob_url]);
  public_blob_urls_.erase(blob_url);
}

void BlobStorageContext::StartBuildingBlob(const std::string& uuid) {
  DCHECK(!IsInUse(uuid) && !uuid.empty());
  blob_map_[uuid] = BlobMapEntry(1, BEING_BUILT, new BlobData(uuid));
}

void BlobStorageContext::AppendBlobDataItem(
    const std::string& uuid, const BlobData::Item& item) {
  DCHECK(IsBeingBuilt(uuid));
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end())
    return;
  if (found->second.flags & EXCEEDED_MEMORY)
    return;
  BlobData* target_blob_data = found->second.data.get();
  DCHECK(target_blob_data);

  bool exceeded_memory = false;

  // The blob data is stored in the canonical way which only contains a
  // list of Data, File, and FileSystem items. Aggregated TYPE_BLOB items
  // are expanded into the primitive constituent types.
  // 1) The Data item is denoted by the raw data and length.
  // 2) The File item is denoted by the file path, the range and the expected
  //    modification time.
  // 3) The FileSystem File item is denoted by the FileSystem URL, the range
  //    and the expected modification time.
  // 4) The Blob items are expanded.
  // TODO(michaeln): Would be nice to avoid copying Data items when expanding.

  DCHECK(item.length() > 0);
  switch (item.type()) {
    case BlobData::Item::TYPE_BYTES:
      DCHECK(!item.offset());
      exceeded_memory = !AppendBytesItem(target_blob_data,
                                         item.bytes(),
                                         static_cast<int64>(item.length()));
      break;
    case BlobData::Item::TYPE_FILE:
      AppendFileItem(target_blob_data,
                     item.path(),
                     item.offset(),
                     item.length(),
                     item.expected_modification_time());
      break;
    case BlobData::Item::TYPE_FILE_FILESYSTEM:
      AppendFileSystemFileItem(target_blob_data,
                               item.filesystem_url(),
                               item.offset(),
                               item.length(),
                               item.expected_modification_time());
      break;
    case BlobData::Item::TYPE_BLOB: {
      scoped_ptr<BlobDataHandle> src = GetBlobDataFromUUID(item.blob_uuid());
      if (src)
        exceeded_memory = !ExpandStorageItems(target_blob_data,
                                              src->data(),
                                              item.offset(),
                                              item.length());
      break;
    }
    default:
      NOTREACHED();
      break;
  }

  // If we're using too much memory, drop this blob's data.
  // TODO(michaeln): Blob memory storage does not yet spill over to disk,
  // as a stop gap, we'll prevent memory usage over a max amount.
  if (exceeded_memory) {
    memory_usage_ -= target_blob_data->GetMemoryUsage();
    found->second.flags |= EXCEEDED_MEMORY;
    found->second.data = new BlobData(uuid);
    return;
  }
}

void BlobStorageContext::FinishBuildingBlob(
    const std::string& uuid, const std::string& content_type) {
  DCHECK(IsBeingBuilt(uuid));
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end())
    return;
  found->second.data->set_content_type(content_type);
  found->second.flags &= ~BEING_BUILT;
}

void BlobStorageContext::CancelBuildingBlob(const std::string& uuid) {
  DCHECK(IsBeingBuilt(uuid));
  DecrementBlobRefCount(uuid);
}

void BlobStorageContext::IncrementBlobRefCount(const std::string& uuid) {
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end()) {
    DCHECK(false);
    return;
  }
  ++(found->second.refcount);
}

void BlobStorageContext::DecrementBlobRefCount(const std::string& uuid) {
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end())
    return;
  DCHECK_EQ(found->second.data->uuid(), uuid);
  if (--(found->second.refcount) == 0) {
    memory_usage_ -= found->second.data->GetMemoryUsage();
    blob_map_.erase(found);
  }
}

bool BlobStorageContext::ExpandStorageItems(
    BlobData* target_blob_data, BlobData* src_blob_data,
    uint64 offset, uint64 length) {
  DCHECK(target_blob_data && src_blob_data &&
         length != static_cast<uint64>(-1));

  std::vector<BlobData::Item>::const_iterator iter =
      src_blob_data->items().begin();
  if (offset) {
    for (; iter != src_blob_data->items().end(); ++iter) {
      if (offset >= iter->length())
        offset -= iter->length();
      else
        break;
    }
  }

  for (; iter != src_blob_data->items().end() && length > 0; ++iter) {
    uint64 current_length = iter->length() - offset;
    uint64 new_length = current_length > length ? length : current_length;
    if (iter->type() == BlobData::Item::TYPE_BYTES) {
      if (!AppendBytesItem(
              target_blob_data,
              iter->bytes() + static_cast<size_t>(iter->offset() + offset),
              static_cast<int64>(new_length))) {
        return false;  // exceeded memory
      }
    } else if (iter->type() == BlobData::Item::TYPE_FILE) {
      AppendFileItem(target_blob_data,
                     iter->path(),
                     iter->offset() + offset,
                     new_length,
                     iter->expected_modification_time());
    } else {
      DCHECK(iter->type() == BlobData::Item::TYPE_FILE_FILESYSTEM);
      AppendFileSystemFileItem(target_blob_data,
                               iter->filesystem_url(),
                               iter->offset() + offset,
                               new_length,
                               iter->expected_modification_time());
    }
    length -= new_length;
    offset = 0;
  }
  return true;
}

bool BlobStorageContext::AppendBytesItem(
    BlobData* target_blob_data, const char* bytes, int64 length) {
  if (length < 0) {
    DCHECK(false);
    return false;
  }
  if (memory_usage_ + length > kMaxMemoryUsage)
    return false;
  target_blob_data->AppendData(bytes, static_cast<size_t>(length));
  memory_usage_ += length;
  return true;
}

void BlobStorageContext::AppendFileItem(
    BlobData* target_blob_data,
    const base::FilePath& file_path, uint64 offset, uint64 length,
    const base::Time& expected_modification_time) {
  target_blob_data->AppendFile(file_path, offset, length,
                               expected_modification_time);

  // It may be a temporary file that should be deleted when no longer needed.
  scoped_refptr<ShareableFileReference> shareable_file =
      ShareableFileReference::Get(file_path);
  if (shareable_file.get())
    target_blob_data->AttachShareableFileReference(shareable_file.get());
}

void BlobStorageContext::AppendFileSystemFileItem(
    BlobData* target_blob_data,
    const GURL& filesystem_url, uint64 offset, uint64 length,
    const base::Time& expected_modification_time) {
  target_blob_data->AppendFileSystemFile(filesystem_url, offset, length,
                                         expected_modification_time);
}

bool BlobStorageContext::IsInUse(const std::string& uuid) {
  return blob_map_.find(uuid) != blob_map_.end();
}

bool BlobStorageContext::IsBeingBuilt(const std::string& uuid) {
  BlobMap::iterator found = blob_map_.find(uuid);
  if (found == blob_map_.end())
    return false;
  return found->second.flags & BEING_BUILT;
}

bool BlobStorageContext::IsUrlRegistered(const GURL& blob_url) {
  return public_blob_urls_.find(blob_url) != public_blob_urls_.end();
}

}  // namespace storage