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); }
209 bool sendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
211 virtual void destroyDecodedData() { }
213 void setOwningCachedResourceLoader(CachedResourceLoader* cachedResourceLoader) { m_owningCachedResourceLoader = cachedResourceLoader; }
215 // MemoryCache does not destroy the decoded data of a CachedResource if the decoded data will be likely used.
216 virtual bool likelyToBeUsedSoon() { return false; }
218 bool isPreloaded() const { return m_preloadCount; }
219 void increasePreloadCount() { ++m_preloadCount; }
220 void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
222 void registerHandle(CachedResourceHandleBase* h);
223 void unregisterHandle(CachedResourceHandleBase* h);
225 bool canUseCacheValidator() const;
226 bool mustRevalidateDueToCacheHeaders(CachePolicy) const;
227 bool isCacheValidator() const { return m_resourceToRevalidate; }
228 CachedResource* resourceToRevalidate() const { return m_resourceToRevalidate; }
230 bool isPurgeable() const;
231 bool wasPurged() const;
233 // This is used by the archive machinery to get at a purged resource without
234 // triggering a load. We should make it protected again if we can find a
235 // better way to handle the archive case.
236 bool makePurgeable(bool purgeable);
238 // HTTP revalidation support methods for CachedResourceLoader.
239 void setResourceToRevalidate(CachedResource*);
240 void switchClientsToRevalidatedResource();
241 void clearResourceToRevalidate();
242 void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
244 virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
245 #if PLATFORM(CHROMIUM)
246 virtual void didDownloadData(int) { }
249 void setLoadFinishTime(double finishTime) { m_loadFinishTime = finishTime; }
250 double loadFinishTime() const { return m_loadFinishTime; }
255 void setEncodedSize(unsigned);
256 void setDecodedSize(unsigned);
257 void didAccessDecodedData(double timeStamp);
259 bool isSafeToMakePurgeable() const;
261 HashCountedSet<CachedResourceClient*> m_clients;
263 class CachedResourceCallback {
265 static PassOwnPtr<CachedResourceCallback> schedule(CachedResource* resource, CachedResourceClient* client) { return adoptPtr(new CachedResourceCallback(resource, client)); }
268 CachedResourceCallback(CachedResource*, CachedResourceClient*);
269 void timerFired(Timer<CachedResourceCallback>*);
271 CachedResource* m_resource;
272 CachedResourceClient* m_client;
273 Timer<CachedResourceCallback> m_callbackTimer;
275 HashMap<CachedResourceClient*, OwnPtr<CachedResourceCallback> > m_clientsAwaitingCallback;
277 bool hasClient(CachedResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
279 ResourceRequest m_resourceRequest;
281 RefPtr<SubresourceLoader> m_loader;
282 ResourceLoaderOptions m_options;
283 ResourceLoadPriority m_loadPriority;
285 ResourceResponse m_response;
286 double m_responseTimestamp;
288 RefPtr<SharedBuffer> m_data;
289 OwnPtr<PurgeableBuffer> m_purgeableData;
290 Timer<CachedResource> m_decodedDataDeletionTimer;
293 bool addClientToSet(CachedResourceClient*);
294 void decodedDataDeletionTimerFired(Timer<CachedResource>*);
296 virtual PurgePriority purgePriority() const { return PurgeDefault; }
298 double currentAge() const;
299 double freshnessLifetime() const;
301 RefPtr<CachedMetadata> m_cachedMetadata;
303 double m_lastDecodedAccessTime; // Used as a "thrash guard" in the cache
304 double m_loadFinishTime;
306 unsigned m_encodedSize;
307 unsigned m_decodedSize;
308 unsigned m_accessCount;
309 unsigned m_handleCount;
310 unsigned m_preloadCount;
312 unsigned m_preloadResult : 2; // PreloadResult
314 bool m_inLiveDecodedResourcesList : 1;
315 bool m_requestedFromNetworkingLayer : 1;
320 bool m_switchingClientsToRevalidatedResource : 1;
322 unsigned m_type : 4; // Type
323 unsigned m_status : 3; // Status
330 CachedResource* m_nextInAllResourcesList;
331 CachedResource* m_prevInAllResourcesList;
333 CachedResource* m_nextInLiveResourcesList;
334 CachedResource* m_prevInLiveResourcesList;
336 CachedResourceLoader* m_owningCachedResourceLoader; // only non-0 for resources that are not in the cache
338 // 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
339 // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
340 // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
341 // resources becomes normal resource load.
342 CachedResource* m_resourceToRevalidate;
344 // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
345 CachedResource* m_proxyResource;
347 // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
348 HashSet<CachedResourceHandleBase*> m_handlesToRevalidate;