[content shell] implement testRunner.overridePreference
[chromium-blink-merge.git] / webkit / appcache / mock_appcache_storage.cc
blob2fa1d041897e1b9dad1ff5e2eff80e5f4c19dde5
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "webkit/appcache/mock_appcache_storage.h"
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "base/memory/ref_counted.h"
10 #include "base/message_loop.h"
11 #include "base/stl_util.h"
12 #include "webkit/appcache/appcache.h"
13 #include "webkit/appcache/appcache_entry.h"
14 #include "webkit/appcache/appcache_group.h"
15 #include "webkit/appcache/appcache_response.h"
16 #include "webkit/appcache/appcache_service.h"
18 // This is a quick and easy 'mock' implementation of the storage interface
19 // that doesn't put anything to disk.
21 // We simply add an extra reference to objects when they're put in storage,
22 // and remove the extra reference when they are removed from storage.
23 // Responses are never really removed from the in-memory disk cache.
24 // Delegate callbacks are made asyncly to appropiately mimic what will
25 // happen with a real disk-backed storage impl that involves IO on a
26 // background thread.
28 namespace appcache {
30 MockAppCacheStorage::MockAppCacheStorage(AppCacheService* service)
31 : AppCacheStorage(service),
32 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
33 simulate_make_group_obsolete_failure_(false),
34 simulate_store_group_and_newest_cache_failure_(false),
35 simulate_find_main_resource_(false),
36 simulate_find_sub_resource_(false),
37 simulated_found_cache_id_(kNoCacheId),
38 simulated_found_group_id_(0),
39 simulated_found_network_namespace_(false) {
40 last_cache_id_ = 0;
41 last_group_id_ = 0;
42 last_response_id_ = 0;
45 MockAppCacheStorage::~MockAppCacheStorage() {
48 void MockAppCacheStorage::GetAllInfo(Delegate* delegate) {
49 ScheduleTask(
50 base::Bind(&MockAppCacheStorage::ProcessGetAllInfo,
51 weak_factory_.GetWeakPtr(),
52 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
55 void MockAppCacheStorage::LoadCache(int64 id, Delegate* delegate) {
56 DCHECK(delegate);
57 AppCache* cache = working_set_.GetCache(id);
58 if (ShouldCacheLoadAppearAsync(cache)) {
59 ScheduleTask(
60 base::Bind(&MockAppCacheStorage::ProcessLoadCache,
61 weak_factory_.GetWeakPtr(), id,
62 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
63 return;
65 ProcessLoadCache(id, GetOrCreateDelegateReference(delegate));
68 void MockAppCacheStorage::LoadOrCreateGroup(
69 const GURL& manifest_url, Delegate* delegate) {
70 DCHECK(delegate);
71 AppCacheGroup* group = working_set_.GetGroup(manifest_url);
72 if (ShouldGroupLoadAppearAsync(group)) {
73 ScheduleTask(
74 base::Bind(&MockAppCacheStorage::ProcessLoadOrCreateGroup,
75 weak_factory_.GetWeakPtr(), manifest_url,
76 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
77 return;
79 ProcessLoadOrCreateGroup(
80 manifest_url, GetOrCreateDelegateReference(delegate));
83 void MockAppCacheStorage::StoreGroupAndNewestCache(
84 AppCacheGroup* group, AppCache* newest_cache, Delegate* delegate) {
85 DCHECK(group && delegate && newest_cache);
87 // Always make this operation look async.
88 ScheduleTask(
89 base::Bind(&MockAppCacheStorage::ProcessStoreGroupAndNewestCache,
90 weak_factory_.GetWeakPtr(), make_scoped_refptr(group),
91 make_scoped_refptr(newest_cache),
92 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
95 void MockAppCacheStorage::FindResponseForMainRequest(
96 const GURL& url, const GURL& preferred_manifest_url, Delegate* delegate) {
97 DCHECK(delegate);
99 // Note: MockAppCacheStorage does not respect the preferred_manifest_url.
101 // Always make this operation look async.
102 ScheduleTask(
103 base::Bind(&MockAppCacheStorage::ProcessFindResponseForMainRequest,
104 weak_factory_.GetWeakPtr(), url,
105 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
108 void MockAppCacheStorage::FindResponseForSubRequest(
109 AppCache* cache, const GURL& url,
110 AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
111 bool* found_network_namespace) {
112 DCHECK(cache && cache->is_complete());
114 // This layer of indirection is here to facilitate testing.
115 if (simulate_find_sub_resource_) {
116 *found_entry = simulated_found_entry_;
117 *found_fallback_entry = simulated_found_fallback_entry_;
118 *found_network_namespace = simulated_found_network_namespace_;
119 simulate_find_sub_resource_ = false;
120 return;
123 GURL fallback_namespace_not_used;
124 GURL intercept_namespace_not_used;
125 cache->FindResponseForRequest(
126 url, found_entry, &intercept_namespace_not_used,
127 found_fallback_entry, &fallback_namespace_not_used,
128 found_network_namespace);
131 void MockAppCacheStorage::MarkEntryAsForeign(
132 const GURL& entry_url, int64 cache_id) {
133 AppCache* cache = working_set_.GetCache(cache_id);
134 if (cache) {
135 AppCacheEntry* entry = cache->GetEntry(entry_url);
136 DCHECK(entry);
137 if (entry)
138 entry->add_types(AppCacheEntry::FOREIGN);
142 void MockAppCacheStorage::MakeGroupObsolete(
143 AppCacheGroup* group, Delegate* delegate) {
144 DCHECK(group && delegate);
146 // Always make this method look async.
147 ScheduleTask(
148 base::Bind(&MockAppCacheStorage::ProcessMakeGroupObsolete,
149 weak_factory_.GetWeakPtr(), make_scoped_refptr(group),
150 make_scoped_refptr(GetOrCreateDelegateReference(delegate))));
153 AppCacheResponseReader* MockAppCacheStorage::CreateResponseReader(
154 const GURL& manifest_url, int64 group_id, int64 response_id) {
155 if (simulated_reader_.get())
156 return simulated_reader_.release();
157 return new AppCacheResponseReader(response_id, group_id, disk_cache());
160 AppCacheResponseWriter* MockAppCacheStorage::CreateResponseWriter(
161 const GURL& manifest_url, int64 group_id) {
162 return new AppCacheResponseWriter(NewResponseId(), group_id, disk_cache());
165 void MockAppCacheStorage::DoomResponses(
166 const GURL& manifest_url, const std::vector<int64>& response_ids) {
167 DeleteResponses(manifest_url, response_ids);
170 void MockAppCacheStorage::DeleteResponses(
171 const GURL& manifest_url, const std::vector<int64>& response_ids) {
172 // We don't bother with actually removing responses from the disk-cache,
173 // just keep track of which ids have been doomed or deleted
174 std::vector<int64>::const_iterator it = response_ids.begin();
175 while (it != response_ids.end()) {
176 doomed_response_ids_.insert(*it);
177 ++it;
181 void MockAppCacheStorage::ProcessGetAllInfo(
182 scoped_refptr<DelegateReference> delegate_ref) {
183 if (delegate_ref->delegate)
184 delegate_ref->delegate->OnAllInfo(simulated_appcache_info_);
187 void MockAppCacheStorage::ProcessLoadCache(
188 int64 id, scoped_refptr<DelegateReference> delegate_ref) {
189 AppCache* cache = working_set_.GetCache(id);
190 if (delegate_ref->delegate)
191 delegate_ref->delegate->OnCacheLoaded(cache, id);
194 void MockAppCacheStorage::ProcessLoadOrCreateGroup(
195 const GURL& manifest_url, scoped_refptr<DelegateReference> delegate_ref) {
196 scoped_refptr<AppCacheGroup> group(working_set_.GetGroup(manifest_url));
198 // Newly created groups are not put in the stored_groups collection
199 // until StoreGroupAndNewestCache is called.
200 if (!group)
201 group = new AppCacheGroup(service_, manifest_url, NewGroupId());
203 if (delegate_ref->delegate)
204 delegate_ref->delegate->OnGroupLoaded(group, manifest_url);
207 void MockAppCacheStorage::ProcessStoreGroupAndNewestCache(
208 scoped_refptr<AppCacheGroup> group,
209 scoped_refptr<AppCache> newest_cache,
210 scoped_refptr<DelegateReference> delegate_ref) {
211 Delegate* delegate = delegate_ref->delegate;
212 if (simulate_store_group_and_newest_cache_failure_) {
213 if (delegate)
214 delegate->OnGroupAndNewestCacheStored(group, newest_cache, false, false);
215 return;
218 AddStoredGroup(group);
219 if (newest_cache != group->newest_complete_cache()) {
220 newest_cache->set_complete(true);
221 group->AddCache(newest_cache);
222 AddStoredCache(newest_cache);
224 // Copy the collection prior to removal, on final release
225 // of a cache the group's collection will change.
226 AppCacheGroup::Caches copy = group->old_caches();
227 RemoveStoredCaches(copy);
230 if (delegate)
231 delegate->OnGroupAndNewestCacheStored(group, newest_cache, true, false);
234 namespace {
236 struct FoundCandidate {
237 GURL namespace_entry_url;
238 AppCacheEntry entry;
239 int64 cache_id;
240 int64 group_id;
241 GURL manifest_url;
242 bool is_cache_in_use;
244 FoundCandidate()
245 : cache_id(kNoCacheId), group_id(0), is_cache_in_use(false) {}
248 void MaybeTakeNewNamespaceEntry(
249 NamespaceType namespace_type,
250 const AppCacheEntry &entry,
251 const GURL& namespace_url,
252 bool cache_is_in_use,
253 FoundCandidate* best_candidate,
254 GURL* best_candidate_namespace,
255 AppCache* cache,
256 AppCacheGroup* group) {
257 DCHECK(entry.has_response_id());
259 bool take_new_entry = true;
261 // Does the new candidate entry trump our current best candidate?
262 if (best_candidate->entry.has_response_id()) {
263 // Longer namespace prefix matches win.
264 size_t candidate_length =
265 namespace_url.spec().length();
266 size_t best_length =
267 best_candidate_namespace->spec().length();
269 if (candidate_length > best_length) {
270 take_new_entry = true;
271 } else if (candidate_length == best_length &&
272 cache_is_in_use && !best_candidate->is_cache_in_use) {
273 take_new_entry = true;
274 } else {
275 take_new_entry = false;
279 if (take_new_entry) {
280 if (namespace_type == FALLBACK_NAMESPACE) {
281 best_candidate->namespace_entry_url =
282 cache->GetFallbackEntryUrl(namespace_url);
283 } else {
284 best_candidate->namespace_entry_url =
285 cache->GetInterceptEntryUrl(namespace_url);
287 best_candidate->entry = entry;
288 best_candidate->cache_id = cache->cache_id();
289 best_candidate->group_id = group->group_id();
290 best_candidate->manifest_url = group->manifest_url();
291 best_candidate->is_cache_in_use = cache_is_in_use;
292 *best_candidate_namespace = namespace_url;
295 } // namespace
297 void MockAppCacheStorage::ProcessFindResponseForMainRequest(
298 const GURL& url, scoped_refptr<DelegateReference> delegate_ref) {
299 if (simulate_find_main_resource_) {
300 simulate_find_main_resource_ = false;
301 if (delegate_ref->delegate) {
302 delegate_ref->delegate->OnMainResponseFound(
303 url, simulated_found_entry_,
304 simulated_found_fallback_url_, simulated_found_fallback_entry_,
305 simulated_found_cache_id_, simulated_found_group_id_,
306 simulated_found_manifest_url_);
308 return;
311 // This call has no persistent side effects, if the delegate has gone
312 // away, we can just bail out early.
313 if (!delegate_ref->delegate)
314 return;
316 // TODO(michaeln): The heuristics around choosing amoungst
317 // multiple candidates is under specified, and just plain
318 // not fully understood. Refine these over time. In particular,
319 // * prefer candidates from newer caches
320 // * take into account the cache associated with the document
321 // that initiated the navigation
322 // * take into account the cache associated with the document
323 // currently residing in the frame being navigated
324 FoundCandidate found_candidate;
325 GURL found_intercept_candidate_namespace;
326 FoundCandidate found_fallback_candidate;
327 GURL found_fallback_candidate_namespace;
329 for (StoredGroupMap::const_iterator it = stored_groups_.begin();
330 it != stored_groups_.end(); ++it) {
331 AppCacheGroup* group = it->second.get();
332 AppCache* cache = group->newest_complete_cache();
333 if (group->is_obsolete() || !cache ||
334 (url.GetOrigin() != group->manifest_url().GetOrigin())) {
335 continue;
338 AppCacheEntry found_entry;
339 AppCacheEntry found_fallback_entry;
340 GURL found_intercept_namespace;
341 GURL found_fallback_namespace;
342 bool ignore_found_network_namespace = false;
343 bool found = cache->FindResponseForRequest(
344 url, &found_entry, &found_intercept_namespace,
345 &found_fallback_entry, &found_fallback_namespace,
346 &ignore_found_network_namespace);
348 // 6.11.1 Navigating across documents, Step 10.
349 // Network namespacing doesn't apply to main resource loads,
350 // and foreign entries are excluded.
351 if (!found || ignore_found_network_namespace ||
352 (found_entry.has_response_id() && found_entry.IsForeign()) ||
353 (found_fallback_entry.has_response_id() &&
354 found_fallback_entry.IsForeign())) {
355 continue;
358 // We have a bias for hits from caches that are in use.
359 bool is_in_use = IsCacheStored(cache) && !cache->HasOneRef();
361 if (found_entry.has_response_id() &&
362 found_intercept_namespace.is_empty()) {
363 found_candidate.namespace_entry_url = GURL();
364 found_candidate.entry = found_entry;
365 found_candidate.cache_id = cache->cache_id();
366 found_candidate.group_id = group->group_id();
367 found_candidate.manifest_url = group->manifest_url();
368 found_candidate.is_cache_in_use = is_in_use;
369 if (is_in_use)
370 break; // We break out of the loop with this direct hit.
371 } else if (found_entry.has_response_id() &&
372 !found_intercept_namespace.is_empty()) {
373 MaybeTakeNewNamespaceEntry(
374 INTERCEPT_NAMESPACE,
375 found_entry, found_intercept_namespace, is_in_use,
376 &found_candidate, &found_intercept_candidate_namespace,
377 cache, group);
378 } else {
379 DCHECK(found_fallback_entry.has_response_id());
380 MaybeTakeNewNamespaceEntry(
381 FALLBACK_NAMESPACE,
382 found_fallback_entry, found_fallback_namespace, is_in_use,
383 &found_fallback_candidate, &found_fallback_candidate_namespace,
384 cache, group);
388 // Found a direct hit or an intercept namespace hit.
389 if (found_candidate.entry.has_response_id()) {
390 delegate_ref->delegate->OnMainResponseFound(
391 url, found_candidate.entry, found_candidate.namespace_entry_url,
392 AppCacheEntry(), found_candidate.cache_id, found_candidate.group_id,
393 found_candidate.manifest_url);
394 return;
397 // Found a fallback namespace.
398 if (found_fallback_candidate.entry.has_response_id()) {
399 delegate_ref->delegate->OnMainResponseFound(
400 url, AppCacheEntry(),
401 found_fallback_candidate.namespace_entry_url,
402 found_fallback_candidate.entry,
403 found_fallback_candidate.cache_id,
404 found_fallback_candidate.group_id,
405 found_fallback_candidate.manifest_url);
406 return;
409 // Didn't find anything.
410 delegate_ref->delegate->OnMainResponseFound(
411 url, AppCacheEntry(), GURL(), AppCacheEntry(), kNoCacheId, 0, GURL());
414 void MockAppCacheStorage::ProcessMakeGroupObsolete(
415 scoped_refptr<AppCacheGroup> group,
416 scoped_refptr<DelegateReference> delegate_ref) {
417 if (simulate_make_group_obsolete_failure_) {
418 if (delegate_ref->delegate)
419 delegate_ref->delegate->OnGroupMadeObsolete(group, false);
420 return;
423 RemoveStoredGroup(group);
424 if (group->newest_complete_cache())
425 RemoveStoredCache(group->newest_complete_cache());
427 // Copy the collection prior to removal, on final release
428 // of a cache the group's collection will change.
429 AppCacheGroup::Caches copy = group->old_caches();
430 RemoveStoredCaches(copy);
432 group->set_obsolete(true);
434 // Also remove from the working set, caches for an 'obsolete' group
435 // may linger in use, but the group itself cannot be looked up by
436 // 'manifest_url' in the working set any longer.
437 working_set()->RemoveGroup(group);
439 if (delegate_ref->delegate)
440 delegate_ref->delegate->OnGroupMadeObsolete(group, true);
443 void MockAppCacheStorage::ScheduleTask(const base::Closure& task) {
444 pending_tasks_.push_back(task);
445 MessageLoop::current()->PostTask(
446 FROM_HERE,
447 base::Bind(&MockAppCacheStorage::RunOnePendingTask,
448 weak_factory_.GetWeakPtr()));
451 void MockAppCacheStorage::RunOnePendingTask() {
452 DCHECK(!pending_tasks_.empty());
453 base::Closure task = pending_tasks_.front();
454 pending_tasks_.pop_front();
455 task.Run();
458 void MockAppCacheStorage::AddStoredCache(AppCache* cache) {
459 int64 cache_id = cache->cache_id();
460 if (stored_caches_.find(cache_id) == stored_caches_.end()) {
461 stored_caches_.insert(
462 StoredCacheMap::value_type(cache_id, make_scoped_refptr(cache)));
466 void MockAppCacheStorage::RemoveStoredCache(AppCache* cache) {
467 // Do not remove from the working set, active caches are still usable
468 // and may be looked up by id until they fall out of use.
469 stored_caches_.erase(cache->cache_id());
472 void MockAppCacheStorage::RemoveStoredCaches(
473 const AppCacheGroup::Caches& caches) {
474 AppCacheGroup::Caches::const_iterator it = caches.begin();
475 while (it != caches.end()) {
476 RemoveStoredCache(*it);
477 ++it;
481 void MockAppCacheStorage::AddStoredGroup(AppCacheGroup* group) {
482 const GURL& url = group->manifest_url();
483 if (stored_groups_.find(url) == stored_groups_.end()) {
484 stored_groups_.insert(
485 StoredGroupMap::value_type(url, make_scoped_refptr(group)));
489 void MockAppCacheStorage::RemoveStoredGroup(AppCacheGroup* group) {
490 stored_groups_.erase(group->manifest_url());
493 bool MockAppCacheStorage::ShouldGroupLoadAppearAsync(
494 const AppCacheGroup* group) {
495 // We'll have to query the database to see if a group for the
496 // manifest_url exists on disk. So return true for async.
497 if (!group)
498 return true;
500 // Groups without a newest cache can't have been put to disk yet, so
501 // we can synchronously return a reference we have in the working set.
502 if (!group->newest_complete_cache())
503 return false;
505 // The LoadGroup interface implies also loading the newest cache, so
506 // if loading the newest cache should appear async, so too must the
507 // loading of this group.
508 if (!ShouldCacheLoadAppearAsync(group->newest_complete_cache()))
509 return false;
512 // If any of the old caches are "in use", then the group must also
513 // be memory resident and not require async loading.
514 const AppCacheGroup::Caches& old_caches = group->old_caches();
515 AppCacheGroup::Caches::const_iterator it = old_caches.begin();
516 while (it != old_caches.end()) {
517 // "in use" caches don't require async loading
518 if (!ShouldCacheLoadAppearAsync(*it))
519 return false;
520 ++it;
523 return true;
526 bool MockAppCacheStorage::ShouldCacheLoadAppearAsync(const AppCache* cache) {
527 if (!cache)
528 return true;
530 // If the 'stored' ref is the only ref, real storage will have to load from
531 // the database.
532 return IsCacheStored(cache) && cache->HasOneRef();
535 } // namespace appcache