2 Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3 Copyright (C) 2001 Dirk Mueller <mueller@kde.org>
4 Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
5 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public License
18 along with this library; see the file COPYING.LIB. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
23 #ifndef CachedResource_h
24 #define CachedResource_h
26 #include "CachePolicy.h"
27 #include "FrameLoaderTypes.h"
28 #include "PlatformString.h"
29 #include "PurgePriority.h"
30 #include "ResourceLoaderOptions.h"
31 #include "ResourceLoadPriority.h"
32 #include "ResourceRequest.h"
33 #include "ResourceResponse.h"
35 #include <wtf/HashCountedSet.h>
36 #include <wtf/HashSet.h>
37 #include <wtf/OwnPtr.h>
38 #include <wtf/Vector.h>
45 class CachedResourceClient;
46 class CachedResourceHandleBase;
47 class CachedResourceLoader;
49 class InspectorResource;
50 class PurgeableBuffer;
52 class SubresourceLoader;
54 // A resource that is held in the cache. Classes who want to use this object should derive
55 // from CachedResourceClient, to get the function calls in case the requested data has arrived.
56 // This class also does the actual communication with the loader to obtain the resource from the network.
57 class CachedResource {
58 WTF_MAKE_NONCOPYABLE(CachedResource); WTF_MAKE_FAST_ALLOCATED;
59 friend class MemoryCache;
60 friend class InspectorResource;
75 #if ENABLE(LINK_PREFETCH)
79 #if ENABLE(VIDEO_TRACK)
82 #if ENABLE(CSS_SHADERS)
88 Unknown, // let cache decide what to do with it
89 Pending, // only partially loaded
90 Cached, // regular case
96 CachedResource(const ResourceRequest&, Type);
97 virtual ~CachedResource();
99 virtual void load(CachedResourceLoader*, const ResourceLoaderOptions&);
101 virtual void setEncoding(const String&) { }
102 virtual String encoding() const { return String(); }
103 virtual void data(PassRefPtr<SharedBuffer> data, bool allDataReceived);
104 virtual void error(CachedResource::Status);
106 virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
108 ResourceRequest& resourceRequest() { return m_resourceRequest; }
109 const KURL& url() const { return m_resourceRequest.url();}
110 Type type() const { return static_cast<Type>(m_type); }
112 ResourceLoadPriority loadPriority() const { return m_loadPriority; }
113 void setLoadPriority(ResourceLoadPriority);
115 void addClient(CachedResourceClient*);
116 void removeClient(CachedResourceClient*);
117 bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
118 bool deleteIfPossible();
121 PreloadNotReferenced,
123 PreloadReferencedWhileLoading,
124 PreloadReferencedWhileComplete
126 PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
128 virtual void didAddClient(CachedResourceClient*);
129 virtual void didRemoveClient(CachedResourceClient*) { }
130 virtual void allClientsRemoved() { }
131 void destroyDecodedDataIfNeeded();
133 unsigned count() const { return m_clients.size(); }
135 Status status() const { return static_cast<Status>(m_status); }
136 void setStatus(Status status) { m_status = status; }
138 unsigned size() const { return encodedSize() + decodedSize() + overheadSize(); }
139 unsigned encodedSize() const { return m_encodedSize; }
140 unsigned decodedSize() const { return m_decodedSize; }
141 unsigned overheadSize() const;
143 bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
145 bool isLoading() const { return m_loading; }
146 void setLoading(bool b) { m_loading = b; }
148 virtual bool isImage() const { return false; }
149 bool ignoreForRequestCount() const
152 #if ENABLE(LINK_PREFETCH)
153 || type() == LinkPrefetch
154 || type() == LinkSubresource
156 || type() == RawResource;
159 unsigned accessCount() const { return m_accessCount; }
160 void increaseAccessCount() { m_accessCount++; }
162 // Computes the status of an object after loading.
163 // Updates the expire date on the cache entry file
166 bool passesAccessControlCheck(SecurityOrigin*);
168 // Called by the cache if the object has been removed from the cache
169 // while still being referenced. This means the object should delete itself
170 // if the number of clients observing it ever drops to 0.
171 // The resource can be brought back to cache after successful revalidation.
172 void setInCache(bool inCache) { m_inCache = inCache; }
173 bool inCache() const { return m_inCache; }
175 bool inLiveDecodedResourcesList() { return m_inLiveDecodedResourcesList; }
179 SharedBuffer* data() const { ASSERT(!m_purgeableData); return m_data.get(); }
181 virtual void willSendRequest(ResourceRequest&, const ResourceResponse&) { m_requestedFromNetworkingLayer = true; }
182 virtual void setResponse(const ResourceResponse&);
183 const ResourceResponse& response() const { return m_response; }
185 // Sets the serialized metadata retrieved from the platform's cache.
186 void setSerializedCachedMetadata(const char*, size_t);
188 // Caches the given metadata in association with this resource and suggests
189 // that the platform persist it. The dataTypeID is a pseudo-randomly chosen
190 // identifier that is used to distinguish data generated by the caller.
191 void setCachedMetadata(unsigned dataTypeID, const char*, size_t);
193 // Returns cached metadata of the given type associated with this resource.
194 CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
196 bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_resourceToRevalidate && !m_proxyResource; }
197 bool hasOneHandle() const { return m_handleCount == 1; }
199 bool isExpired() const;
201 // List of acceptable MIME types separated by ",".
202 // A MIME type may contain a wildcard, e.g. "text/*".
203 String accept() const { return m_accept; }
204 void setAccept(const String& accept) { m_accept = accept; }
206 bool wasCanceled() const { return m_status == Canceled; }
207 bool errorOccurred() const { return (m_status == LoadError || m_status == DecodeError); }
208 bool loadFailedOrCanceled() { return m_status == Canceled || m_status == LoadError; }
210 bool sendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
212 virtual void destroyDecodedData() { }
214 void setOwningCachedResourceLoader(CachedResourceLoader* cachedResourceLoader) { m_owningCachedResourceLoader = cachedResourceLoader; }
216 // MemoryCache does not destroy the decoded data of a CachedResource if the decoded data will be likely used.
217 virtual bool likelyToBeUsedSoon() { return false; }
219 bool isPreloaded() const { return m_preloadCount; }
220 void increasePreloadCount() { ++m_preloadCount; }
221 void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
223 void registerHandle(CachedResourceHandleBase* h);
224 void unregisterHandle(CachedResourceHandleBase* h);
226 bool canUseCacheValidator() const;
227 bool mustRevalidateDueToCacheHeaders(CachePolicy) const;
228 bool isCacheValidator() const { return m_resourceToRevalidate; }
229 CachedResource* resourceToRevalidate() const { return m_resourceToRevalidate; }
231 bool isPurgeable() const;
232 bool wasPurged() const;
234 // This is used by the archive machinery to get at a purged resource without
235 // triggering a load. We should make it protected again if we can find a
236 // better way to handle the archive case.
237 bool makePurgeable(bool purgeable);
239 // HTTP revalidation support methods for CachedResourceLoader.
240 void setResourceToRevalidate(CachedResource*);
241 void switchClientsToRevalidatedResource();
242 void clearResourceToRevalidate();
243 void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
245 virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
246 #if PLATFORM(CHROMIUM)
247 virtual void didDownloadData(int) { }
250 void setLoadFinishTime(double finishTime) { m_loadFinishTime = finishTime; }
251 double loadFinishTime() const { return m_loadFinishTime; }
256 void setEncodedSize(unsigned);
257 void setDecodedSize(unsigned);
258 void didAccessDecodedData(double timeStamp);
260 bool isSafeToMakePurgeable() const;
262 HashCountedSet<CachedResourceClient*> m_clients;
264 class CachedResourceCallback {
266 static PassOwnPtr<CachedResourceCallback> schedule(CachedResource* resource, CachedResourceClient* client) { return adoptPtr(new CachedResourceCallback(resource, client)); }
269 CachedResourceCallback(CachedResource*, CachedResourceClient*);
270 void timerFired(Timer<CachedResourceCallback>*);
272 CachedResource* m_resource;
273 CachedResourceClient* m_client;
274 Timer<CachedResourceCallback> m_callbackTimer;
276 HashMap<CachedResourceClient*, OwnPtr<CachedResourceCallback> > m_clientsAwaitingCallback;
278 bool hasClient(CachedResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
280 ResourceRequest m_resourceRequest;
282 RefPtr<SubresourceLoader> m_loader;
283 ResourceLoaderOptions m_options;
284 ResourceLoadPriority m_loadPriority;
286 ResourceResponse m_response;
287 double m_responseTimestamp;
289 RefPtr<SharedBuffer> m_data;
290 OwnPtr<PurgeableBuffer> m_purgeableData;
291 Timer<CachedResource> m_decodedDataDeletionTimer;
294 bool addClientToSet(CachedResourceClient*);
295 void decodedDataDeletionTimerFired(Timer<CachedResource>*);
297 virtual PurgePriority purgePriority() const { return PurgeDefault; }
299 double currentAge() const;
300 double freshnessLifetime() const;
302 RefPtr<CachedMetadata> m_cachedMetadata;
304 double m_lastDecodedAccessTime; // Used as a "thrash guard" in the cache
305 double m_loadFinishTime;
307 unsigned m_encodedSize;
308 unsigned m_decodedSize;
309 unsigned m_accessCount;
310 unsigned m_handleCount;
311 unsigned m_preloadCount;
313 unsigned m_preloadResult : 2; // PreloadResult
315 bool m_inLiveDecodedResourcesList : 1;
316 bool m_requestedFromNetworkingLayer : 1;
321 bool m_switchingClientsToRevalidatedResource : 1;
323 unsigned m_type : 4; // Type
324 unsigned m_status : 3; // Status
331 CachedResource* m_nextInAllResourcesList;
332 CachedResource* m_prevInAllResourcesList;
334 CachedResource* m_nextInLiveResourcesList;
335 CachedResource* m_prevInLiveResourcesList;
337 CachedResourceLoader* m_owningCachedResourceLoader; // only non-0 for resources that are not in the cache
339 // If this field is non-null we are using the resource as a proxy for checking whether an existing resource is still up to date
340 // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
341 // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
342 // resources becomes normal resource load.
343 CachedResource* m_resourceToRevalidate;
345 // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
346 CachedResource* m_proxyResource;
348 // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
349 HashSet<CachedResourceHandleBase*> m_handlesToRevalidate;