Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / webkit / browser / appcache / appcache_storage.h
1 // Copyright (c) 2012 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.
4
5 #ifndef WEBKIT_BROWSER_APPCACHE_APPCACHE_STORAGE_H_
6 #define WEBKIT_BROWSER_APPCACHE_APPCACHE_STORAGE_H_
7
8 #include <map>
9 #include <vector>
10
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "net/base/completion_callback.h"
17 #include "webkit/browser/appcache/appcache_working_set.h"
18 #include "webkit/browser/webkit_storage_browser_export.h"
19
20 class GURL;
21
22 namespace appcache {
23
24 class AppCache;
25 class AppCacheEntry;
26 class AppCacheGroup;
27 class AppCacheResponseReader;
28 class AppCacheResponseWriter;
29 class AppCacheService;
30 struct AppCacheInfoCollection;
31 struct HttpResponseInfoIOBuffer;
32
33 class WEBKIT_STORAGE_BROWSER_EXPORT AppCacheStorage {
34  public:
35   typedef std::map<GURL, int64> UsageMap;
36
37   class WEBKIT_STORAGE_BROWSER_EXPORT Delegate {
38    public:
39     // If retrieval fails, 'collection' will be NULL.
40     virtual void OnAllInfo(AppCacheInfoCollection* collection) {}
41
42     // If a load fails the 'cache' will be NULL.
43     virtual void OnCacheLoaded(AppCache* cache, int64 cache_id) {}
44
45     // If a load fails the 'group' will be NULL.
46     virtual void OnGroupLoaded(
47         AppCacheGroup* group, const GURL& manifest_url) {}
48
49     // If successfully stored 'success' will be true.
50     virtual void OnGroupAndNewestCacheStored(
51         AppCacheGroup* group, AppCache* newest_cache, bool success,
52         bool would_exceed_quota) {}
53
54     // If the operation fails, success will be false.
55     virtual void OnGroupMadeObsolete(AppCacheGroup* group, bool success) {}
56
57     // If a load fails the 'response_info' will be NULL.
58     virtual void OnResponseInfoLoaded(
59         AppCacheResponseInfo* response_info, int64 response_id) {}
60
61     // If no response is found, entry.response_id() and
62     // fallback_entry.response_id() will be kNoResponseId.
63     // If the response is the entry for an intercept or fallback
64     // namespace, the url of the namespece entry is returned.
65     // If a response is found, the cache id and manifest url of the
66     // containing cache and group are also returned.
67     virtual void OnMainResponseFound(
68         const GURL& url, const AppCacheEntry& entry,
69         const GURL& namespace_entry_url, const AppCacheEntry& fallback_entry,
70         int64 cache_id, int64 group_id, const GURL& mainfest_url) {}
71
72    protected:
73     virtual ~Delegate() {}
74   };
75
76   explicit AppCacheStorage(AppCacheService* service);
77   virtual ~AppCacheStorage();
78
79   // Schedules a task to retrieve basic info about all groups and caches
80   // stored in the system. Upon completion the delegate will be called
81   // with the results.
82   virtual void GetAllInfo(Delegate* delegate) = 0;
83
84   // Schedules a cache to be loaded from storage. Upon load completion
85   // the delegate will be called back. If the cache already resides in
86   // memory, the delegate will be called back immediately without returning
87   // to the message loop. If the load fails, the delegate will be called
88   // back with a NULL cache pointer.
89   virtual void LoadCache(int64 id, Delegate* delegate) = 0;
90
91   // Schedules a group and its newest cache, if any, to be loaded from storage.
92   // Upon load completion the delegate will be called back. If the group
93   // and newest cache already reside in memory, the delegate will be called
94   // back immediately without returning to the message loop. If the load fails,
95   // the delegate will be called back with a NULL group pointer.
96   virtual void LoadOrCreateGroup(
97       const GURL& manifest_url, Delegate* delegate) = 0;
98
99   // Schedules response info to be loaded from storage.
100   // Upon load completion the delegate will be called back. If the data
101   // already resides in memory, the delegate will be called back
102   // immediately without returning to the message loop. If the load fails,
103   // the delegate will be called back with a NULL pointer.
104   virtual void LoadResponseInfo(
105       const GURL& manifest_url, int64 group_id, int64 response_id,
106       Delegate* delegate);
107
108   // Schedules a group and its newest complete cache to be initially stored or
109   // incrementally updated with new changes. Upon completion the delegate
110   // will be called back. A group without a newest cache cannot be stored.
111   // It's a programming error to call this method without a newest cache. A
112   // side effect of storing a new newest cache is the removal of the group's
113   // old caches and responses from persistent storage (although they may still
114   // linger in the in-memory working set until no longer needed). The new
115   // cache will be added as the group's newest complete cache only if storage
116   // succeeds.
117   virtual void StoreGroupAndNewestCache(
118       AppCacheGroup* group, AppCache* newest_cache, Delegate* delegate) = 0;
119
120   // Schedules a query to identify a response for a main request. Upon
121   // completion the delegate will be called back.
122   virtual void FindResponseForMainRequest(
123       const GURL& url,
124       const GURL& preferred_manifest_url,
125       Delegate* delegate) = 0;
126
127   // Performs an immediate lookup of the in-memory cache to
128   // identify a response for a sub resource request.
129   virtual void FindResponseForSubRequest(
130       AppCache* cache, const GURL& url,
131       AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
132       bool* found_network_namespace) = 0;
133
134   // Immediately updates in-memory storage, if the cache is in memory,
135   // and schedules a task to update persistent storage. If the cache is
136   // already scheduled to be loaded, upon loading completion the entry
137   // will be marked. There is no delegate completion callback.
138   virtual void MarkEntryAsForeign(const GURL& entry_url, int64 cache_id) = 0;
139
140   // Schedules a task to update persistent storage and doom the group and all
141   // related caches and responses for deletion. Upon completion the in-memory
142   // instance is marked as obsolete and the delegate callback is called.
143   virtual void MakeGroupObsolete(
144       AppCacheGroup* group, Delegate* delegate) = 0;
145
146   // Cancels all pending callbacks for the delegate. The delegate callbacks
147   // will not be invoked after, however any scheduled operations will still
148   // take place. The callbacks for subsequently scheduled operations are
149   // unaffected.
150   void CancelDelegateCallbacks(Delegate* delegate) {
151     DelegateReference* delegate_reference = GetDelegateReference(delegate);
152     if (delegate_reference)
153       delegate_reference->CancelReference();
154   }
155
156   // Creates a reader to read a response from storage.
157   virtual AppCacheResponseReader* CreateResponseReader(
158       const GURL& manifest_url, int64 group_id, int64 response_id) = 0;
159
160   // Creates a writer to write a new response to storage. This call
161   // establishes a new response id.
162   virtual AppCacheResponseWriter* CreateResponseWriter(
163       const GURL& manifest_url, int64 group_id) = 0;
164
165   // Schedules the lazy deletion of responses and saves the ids
166   // persistently such that the responses will be deleted upon restart
167   // if they aren't deleted prior to shutdown.
168   virtual void DoomResponses(
169       const GURL& manifest_url, const std::vector<int64>& response_ids) = 0;
170
171   // Schedules the lazy deletion of responses without persistently saving
172   // the response ids.
173   virtual void DeleteResponses(
174       const GURL& manifest_url, const std::vector<int64>& response_ids) = 0;
175
176   // Generates unique storage ids for different object types.
177   int64 NewCacheId() {
178     return ++last_cache_id_;
179   }
180   int64 NewGroupId() {
181     return ++last_group_id_;
182   }
183
184   // The working set of object instances currently in memory.
185   AppCacheWorkingSet* working_set() { return &working_set_; }
186
187   // A map of origins to usage.
188   const UsageMap* usage_map() { return &usage_map_; }
189
190   // Simple ptr back to the service object that owns us.
191   AppCacheService* service() { return service_; }
192
193  protected:
194   friend class AppCacheQuotaClientTest;
195   friend class AppCacheResponseTest;
196   friend class AppCacheStorageTest;
197
198   // Helper to call a collection of delegates.
199   #define FOR_EACH_DELEGATE(delegates, func_and_args)                \
200     do {                                                             \
201       for (DelegateReferenceVector::iterator it = delegates.begin(); \
202            it != delegates.end(); ++it) {                            \
203         if (it->get()->delegate)                                     \
204           it->get()->delegate->func_and_args;                        \
205       }                                                              \
206     } while (0)
207
208   // Helper used to manage multiple references to a 'delegate' and to
209   // allow all pending callbacks to that delegate to be easily cancelled.
210   struct DelegateReference : public base::RefCounted<DelegateReference> {
211     Delegate* delegate;
212     AppCacheStorage* storage;
213
214     DelegateReference(Delegate* delegate, AppCacheStorage* storage);
215
216     void CancelReference() {
217       storage->delegate_references_.erase(delegate);
218       storage = NULL;
219       delegate = NULL;
220     }
221
222    private:
223     friend class base::RefCounted<DelegateReference>;
224
225     virtual ~DelegateReference();
226   };
227   typedef std::map<Delegate*, DelegateReference*> DelegateReferenceMap;
228   typedef std::vector<scoped_refptr<DelegateReference> >
229       DelegateReferenceVector;
230
231   // Helper used to manage an async LoadResponseInfo calls on behalf of
232   // multiple callers.
233   class ResponseInfoLoadTask {
234    public:
235     ResponseInfoLoadTask(const GURL& manifest_url, int64 group_id,
236                          int64 response_id, AppCacheStorage* storage);
237     ~ResponseInfoLoadTask();
238
239     int64 response_id() const { return response_id_; }
240     const GURL& manifest_url() const { return manifest_url_; }
241     int64 group_id() const { return group_id_; }
242
243     void AddDelegate(DelegateReference* delegate_reference) {
244       delegates_.push_back(delegate_reference);
245     }
246
247     void StartIfNeeded();
248
249    private:
250     void OnReadComplete(int result);
251
252     AppCacheStorage* storage_;
253     GURL manifest_url_;
254     int64 group_id_;
255     int64 response_id_;
256     scoped_ptr<AppCacheResponseReader> reader_;
257     DelegateReferenceVector delegates_;
258     scoped_refptr<HttpResponseInfoIOBuffer> info_buffer_;
259   };
260
261   typedef std::map<int64, ResponseInfoLoadTask*> PendingResponseInfoLoads;
262
263   DelegateReference* GetDelegateReference(Delegate* delegate) {
264     DelegateReferenceMap::iterator iter =
265         delegate_references_.find(delegate);
266     if (iter != delegate_references_.end())
267       return iter->second;
268     return NULL;
269   }
270
271   DelegateReference* GetOrCreateDelegateReference(Delegate* delegate) {
272     DelegateReference* reference = GetDelegateReference(delegate);
273     if (reference)
274       return reference;
275     return new DelegateReference(delegate, this);
276   }
277
278   ResponseInfoLoadTask* GetOrCreateResponseInfoLoadTask(
279       const GURL& manifest_url, int64 group_id, int64 response_id) {
280     PendingResponseInfoLoads::iterator iter =
281         pending_info_loads_.find(response_id);
282     if (iter != pending_info_loads_.end())
283       return iter->second;
284     return new ResponseInfoLoadTask(manifest_url, group_id, response_id, this);
285   }
286
287   // Should only be called when creating a new response writer.
288   int64 NewResponseId() {
289     return ++last_response_id_;
290   }
291
292   // Helpers to query and notify the QuotaManager.
293   void UpdateUsageMapAndNotify(const GURL& origin, int64 new_usage);
294   void ClearUsageMapAndNotify();
295   void NotifyStorageAccessed(const GURL& origin);
296
297   // The last storage id used for different object types.
298   int64 last_cache_id_;
299   int64 last_group_id_;
300   int64 last_response_id_;
301
302   UsageMap usage_map_;  // maps origin to usage
303   AppCacheWorkingSet working_set_;
304   AppCacheService* service_;
305   DelegateReferenceMap delegate_references_;
306   PendingResponseInfoLoads pending_info_loads_;
307
308   // The set of last ids must be retrieved from storage prior to being used.
309   static const int64 kUnitializedId;
310
311   FRIEND_TEST_ALL_PREFIXES(AppCacheStorageTest, DelegateReferences);
312   FRIEND_TEST_ALL_PREFIXES(AppCacheStorageTest, UsageMap);
313
314   DISALLOW_COPY_AND_ASSIGN(AppCacheStorage);
315 };
316
317 }  // namespace appcache
318
319 #endif  // WEBKIT_BROWSER_APPCACHE_APPCACHE_STORAGE_H_