Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(153)

Side by Side Diff: third_party/WebKit/Source/core/fetch/Resource.h

Issue 2584423002: Loading: move core/fetch to platform/loader/fetch (Closed)
Patch Set: rebase Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
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
6 rights reserved.
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public
10 License as published by the Free Software Foundation; either
11 version 2 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
17
18 You should have received a copy of the GNU Library General Public License
19 along with this library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.
22 */
23
24 #ifndef Resource_h
25 #define Resource_h
26
27 #include "core/CoreExport.h"
28 #include "core/fetch/CachedMetadataHandler.h"
29 #include "core/fetch/IntegrityMetadata.h"
30 #include "core/fetch/ResourceLoaderOptions.h"
31 #include "core/fetch/ResourceStatus.h"
32 #include "platform/MemoryCoordinator.h"
33 #include "platform/SharedBuffer.h"
34 #include "platform/Timer.h"
35 #include "platform/instrumentation/tracing/web_process_memory_dump.h"
36 #include "platform/network/ResourceError.h"
37 #include "platform/network/ResourceLoadPriority.h"
38 #include "platform/network/ResourceRequest.h"
39 #include "platform/network/ResourceResponse.h"
40 #include "public/platform/WebDataConsumerHandle.h"
41 #include "wtf/Allocator.h"
42 #include "wtf/AutoReset.h"
43 #include "wtf/HashCountedSet.h"
44 #include "wtf/HashSet.h"
45 #include "wtf/text/AtomicString.h"
46 #include "wtf/text/WTFString.h"
47 #include <memory>
48
49 namespace blink {
50
51 class FetchRequest;
52 class ResourceClient;
53 class ResourceFetcher;
54 class ResourceTimingInfo;
55 class ResourceLoader;
56 class SecurityOrigin;
57
58 // A resource that is held in the cache. Classes who want to use this object
59 // should derive from ResourceClient, to get the function calls in case the
60 // requested data has arrived. This class also does the actual communication
61 // with the loader to obtain the resource from the network.
62 class CORE_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
63 public MemoryCoordinatorClient {
64 USING_GARBAGE_COLLECTED_MIXIN(Resource);
65 WTF_MAKE_NONCOPYABLE(Resource);
66
67 public:
68 // |Type| enum values are used in UMAs, so do not change the values of
69 // existing |Type|. When adding a new |Type|, append it at the end and update
70 // |kLastResourceType|.
71 enum Type {
72 MainResource,
73 Image,
74 CSSStyleSheet,
75 Script,
76 Font,
77 Raw,
78 SVGDocument,
79 XSLStyleSheet,
80 LinkPrefetch,
81 TextTrack,
82 ImportResource,
83 Media, // Audio or video file requested by a HTML5 media element
84 Manifest,
85 Mock // Only for testing
86 };
87 static const int kLastResourceType = Mock + 1;
88
89 using Status = ResourceStatus;
90
91 // TODO(hiroshige): Remove the following declarations.
92 static constexpr Status NotStarted = ResourceStatus::NotStarted;
93 static constexpr Status Pending = ResourceStatus::Pending;
94 static constexpr Status Cached = ResourceStatus::Cached;
95 static constexpr Status LoadError = ResourceStatus::LoadError;
96 static constexpr Status DecodeError = ResourceStatus::DecodeError;
97
98 // Whether a resource client for a preload should mark the preload as
99 // referenced.
100 enum PreloadReferencePolicy {
101 MarkAsReferenced,
102 DontMarkAsReferenced,
103 };
104
105 // Used by reloadIfLoFiOrPlaceholderImage().
106 enum ReloadLoFiOrPlaceholderPolicy {
107 kReloadIfNeeded,
108 kReloadAlwaysWithExistingCachePolicy,
109 kReloadAlways,
110 };
111
112 virtual ~Resource();
113
114 DECLARE_VIRTUAL_TRACE();
115
116 virtual void setEncoding(const String&) {}
117 virtual String encoding() const { return String(); }
118 virtual void appendData(const char*, size_t);
119 virtual void error(const ResourceError&);
120 virtual void setCORSFailed() {}
121
122 void setNeedsSynchronousCacheHit(bool needsSynchronousCacheHit) {
123 m_needsSynchronousCacheHit = needsSynchronousCacheHit;
124 }
125
126 void setLinkPreload(bool isLinkPreload) { m_linkPreload = isLinkPreload; }
127 bool isLinkPreload() const { return m_linkPreload; }
128
129 void setPreloadDiscoveryTime(double preloadDiscoveryTime) {
130 m_preloadDiscoveryTime = preloadDiscoveryTime;
131 }
132
133 const ResourceError& resourceError() const { return m_error; }
134
135 void setIdentifier(unsigned long identifier) { m_identifier = identifier; }
136 unsigned long identifier() const { return m_identifier; }
137
138 virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
139
140 const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
141 const ResourceRequest& lastResourceRequest() const;
142
143 virtual void setRevalidatingRequest(const ResourceRequest&);
144
145 void setFetcherSecurityOrigin(SecurityOrigin* origin) {
146 m_fetcherSecurityOrigin = origin;
147 }
148
149 // This url can have a fragment, but it can match resources that differ by the
150 // fragment only.
151 const KURL& url() const { return m_resourceRequest.url(); }
152 Type getType() const { return static_cast<Type>(m_type); }
153 const ResourceLoaderOptions& options() const { return m_options; }
154 ResourceLoaderOptions& mutableOptions() { return m_options; }
155
156 void didChangePriority(ResourceLoadPriority, int intraPriorityValue);
157 virtual ResourcePriority priorityFromObservers() {
158 return ResourcePriority();
159 }
160
161 // The reference policy indicates that the client should not affect whether
162 // a preload is considered referenced or not. This allows for "passive"
163 // resource clients that simply observe the resource.
164 void addClient(ResourceClient*, PreloadReferencePolicy = MarkAsReferenced);
165 void removeClient(ResourceClient*);
166
167 enum PreloadResult {
168 PreloadNotReferenced,
169 PreloadReferenced,
170 PreloadReferencedWhileLoading,
171 PreloadReferencedWhileComplete
172 };
173 PreloadResult getPreloadResult() const { return m_preloadResult; }
174
175 Status getStatus() const { return m_status; }
176 void setStatus(Status status) { m_status = status; }
177
178 size_t size() const { return encodedSize() + decodedSize() + overheadSize(); }
179
180 // Returns the size of content (response body) before decoding. Adding a new
181 // usage of this function is not recommended (See the TODO below).
182 //
183 // TODO(hiroshige): Now encodedSize/decodedSize states are inconsistent and
184 // need to be refactored (crbug/643135).
185 size_t encodedSize() const { return m_encodedSize; }
186
187 // Returns the current memory usage for the encoded data. Adding a new usage
188 // of this function is not recommended as the same reason as |encodedSize()|.
189 //
190 // |encodedSize()| and |encodedSizeMemoryUsageForTesting()| can return
191 // different values, e.g., when ImageResource purges encoded image data after
192 // finishing loading.
193 size_t encodedSizeMemoryUsageForTesting() const {
194 return m_encodedSizeMemoryUsage;
195 }
196
197 size_t decodedSize() const { return m_decodedSize; }
198 size_t overheadSize() const { return m_overheadSize; }
199
200 bool isLoaded() const { return m_status > Pending; }
201
202 bool isLoading() const { return m_status == Pending; }
203 bool stillNeedsLoad() const { return m_status < Pending; }
204
205 void setLoader(ResourceLoader*);
206 ResourceLoader* loader() const { return m_loader.get(); }
207
208 virtual bool isImage() const { return false; }
209 bool shouldBlockLoadEvent() const;
210 bool isLoadEventBlockingResourceType() const;
211
212 // Computes the status of an object after loading. Updates the expire date on
213 // the cache entry file
214 virtual void finish(double finishTime);
215 void finish() { finish(0.0); }
216
217 bool passesAccessControlCheck(SecurityOrigin*) const;
218
219 virtual PassRefPtr<const SharedBuffer> resourceBuffer() const {
220 return m_data;
221 }
222 void setResourceBuffer(PassRefPtr<SharedBuffer>);
223
224 virtual bool willFollowRedirect(const ResourceRequest&,
225 const ResourceResponse&);
226
227 // Called when a redirect response was received but a decision has already
228 // been made to not follow it.
229 virtual void willNotFollowRedirect() {}
230
231 virtual void responseReceived(const ResourceResponse&,
232 std::unique_ptr<WebDataConsumerHandle>);
233 void setResponse(const ResourceResponse&);
234 const ResourceResponse& response() const { return m_response; }
235
236 virtual void reportResourceTimingToClients(const ResourceTimingInfo&) {}
237
238 // Sets the serialized metadata retrieved from the platform's cache.
239 virtual void setSerializedCachedMetadata(const char*, size_t);
240
241 // This may return nullptr when the resource isn't cacheable.
242 CachedMetadataHandler* cacheHandler();
243
244 AtomicString httpContentType() const;
245
246 bool wasCanceled() const { return m_error.isCancellation(); }
247 bool errorOccurred() const {
248 return m_status == LoadError || m_status == DecodeError;
249 }
250 bool loadFailedOrCanceled() const { return !m_error.isNull(); }
251
252 DataBufferingPolicy getDataBufferingPolicy() const {
253 return m_options.dataBufferingPolicy;
254 }
255 void setDataBufferingPolicy(DataBufferingPolicy);
256
257 // The isPreloaded() flag is using a counter in order to make sure that even
258 // when multiple ResourceFetchers are preloading the resource, it will remain
259 // marked as preloaded until *all* of them have used it.
260 bool isUnusedPreload() const {
261 return isPreloaded() && getPreloadResult() == PreloadNotReferenced;
262 }
263 bool isPreloaded() const { return m_preloadCount; }
264 void increasePreloadCount() { ++m_preloadCount; }
265 void decreasePreloadCount() {
266 DCHECK(m_preloadCount);
267 --m_preloadCount;
268 }
269
270 bool canReuseRedirectChain();
271 bool mustRevalidateDueToCacheHeaders();
272 bool canUseCacheValidator();
273 bool isCacheValidator() const { return m_isRevalidating; }
274 bool hasCacheControlNoStoreHeader() const;
275 bool hasVaryHeader() const;
276
277 bool isEligibleForIntegrityCheck(SecurityOrigin*) const;
278
279 void setIntegrityMetadata(const IntegrityMetadataSet& metadata) {
280 m_integrityMetadata = metadata;
281 }
282 const IntegrityMetadataSet& integrityMetadata() const {
283 return m_integrityMetadata;
284 }
285 // The argument must never be |NotChecked|.
286 void setIntegrityDisposition(ResourceIntegrityDisposition);
287 ResourceIntegrityDisposition integrityDisposition() const {
288 return m_integrityDisposition;
289 }
290 bool mustRefetchDueToIntegrityMetadata(const FetchRequest&) const;
291
292 double currentAge() const;
293 double freshnessLifetime();
294 double stalenessLifetime();
295
296 bool isAlive() const { return m_isAlive; }
297
298 void setCacheIdentifier(const String& cacheIdentifier) {
299 m_cacheIdentifier = cacheIdentifier;
300 }
301 String cacheIdentifier() const { return m_cacheIdentifier; }
302
303 virtual void didSendData(unsigned long long /* bytesSent */,
304 unsigned long long /* totalBytesToBeSent */) {}
305 virtual void didDownloadData(int) {}
306
307 double loadFinishTime() const { return m_loadFinishTime; }
308
309 void setEncodedDataLength(int64_t value) {
310 m_response.setEncodedDataLength(value);
311 }
312 void addToEncodedBodyLength(int value) {
313 m_response.addToEncodedBodyLength(value);
314 }
315 void addToDecodedBodyLength(int value) {
316 m_response.addToDecodedBodyLength(value);
317 }
318
319 virtual bool canReuse(const ResourceRequest&) const { return true; }
320
321 // If cache-aware loading is activated, this callback is called when the first
322 // disk-cache-only request failed due to cache miss. After this callback,
323 // cache-aware loading is deactivated and a reload with original request will
324 // be triggered right away in ResourceLoader.
325 virtual void willReloadAfterDiskCacheMiss() {}
326
327 // TODO(shaochuan): This is for saving back the actual ResourceRequest sent
328 // in ResourceFetcher::startLoad() for retry in cache-aware loading, remove
329 // once ResourceRequest is not modified in startLoad(). crbug.com/632580
330 void setResourceRequest(const ResourceRequest& resourceRequest) {
331 m_resourceRequest = resourceRequest;
332 }
333
334 // Used by the MemoryCache to reduce the memory consumption of the entry.
335 void prune();
336
337 virtual void onMemoryDump(WebMemoryDumpLevelOfDetail,
338 WebProcessMemoryDump*) const;
339
340 // If this Resource is ImageResource and has the Lo-Fi response headers or is
341 // a placeholder, reload the full original image with the Lo-Fi state set to
342 // off and optionally bypassing the cache.
343 virtual void reloadIfLoFiOrPlaceholderImage(ResourceFetcher*,
344 ReloadLoFiOrPlaceholderPolicy) {}
345
346 static const char* resourceTypeToString(
347 Type,
348 const AtomicString& fetchInitiatorName);
349
350 protected:
351 Resource(const ResourceRequest&, Type, const ResourceLoaderOptions&);
352
353 virtual void checkNotify();
354
355 void markClientFinished(ResourceClient*);
356
357 virtual bool hasClientsOrObservers() const {
358 return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty() ||
359 !m_finishedClients.isEmpty();
360 }
361 virtual void destroyDecodedDataForFailedRevalidation() {}
362
363 void setEncodedSize(size_t);
364 void setDecodedSize(size_t);
365
366 void finishPendingClients();
367
368 virtual void didAddClient(ResourceClient*);
369 void willAddClientOrObserver(PreloadReferencePolicy);
370
371 void didRemoveClientOrObserver();
372 virtual void allClientsAndObserversRemoved();
373
374 bool hasClient(ResourceClient* client) {
375 return m_clients.contains(client) ||
376 m_clientsAwaitingCallback.contains(client) ||
377 m_finishedClients.contains(client);
378 }
379
380 struct RedirectPair {
381 DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
382
383 public:
384 explicit RedirectPair(const ResourceRequest& request,
385 const ResourceResponse& redirectResponse)
386 : m_request(request), m_redirectResponse(redirectResponse) {}
387
388 ResourceRequest m_request;
389 ResourceResponse m_redirectResponse;
390 };
391 const Vector<RedirectPair>& redirectChain() const { return m_redirectChain; }
392
393 virtual void destroyDecodedDataIfPossible() {}
394
395 // Returns the memory dump name used for tracing. See Resource::onMemoryDump.
396 String getMemoryDumpName() const;
397
398 const HeapHashCountedSet<WeakMember<ResourceClient>>& clients() const {
399 return m_clients;
400 }
401
402 void setCachePolicyBypassingCache();
403 void setLoFiStateOff();
404 void clearRangeRequestHeader();
405
406 SharedBuffer* data() const { return m_data.get(); }
407 void clearData();
408
409 class ProhibitAddRemoveClientInScope : public AutoReset<bool> {
410 public:
411 ProhibitAddRemoveClientInScope(Resource* resource)
412 : AutoReset(&resource->m_isAddRemoveClientProhibited, true) {}
413 };
414
415 class RevalidationStartForbiddenScope : public AutoReset<bool> {
416 public:
417 RevalidationStartForbiddenScope(Resource* resource)
418 : AutoReset(&resource->m_isRevalidationStartForbidden, true) {}
419 };
420
421 private:
422 class ResourceCallback;
423 class CachedMetadataHandlerImpl;
424 class ServiceWorkerResponseCachedMetadataHandler;
425
426 void cancelTimerFired(TimerBase*);
427
428 void revalidationSucceeded(const ResourceResponse&);
429 void revalidationFailed();
430
431 size_t calculateOverheadSize() const;
432
433 String reasonNotDeletable() const;
434
435 // MemoryCoordinatorClient overrides:
436 void onMemoryStateChange(MemoryState) override;
437
438 Member<CachedMetadataHandlerImpl> m_cacheHandler;
439 RefPtr<SecurityOrigin> m_fetcherSecurityOrigin;
440
441 ResourceError m_error;
442
443 double m_loadFinishTime;
444
445 unsigned long m_identifier;
446
447 size_t m_encodedSize;
448 size_t m_encodedSizeMemoryUsage;
449 size_t m_decodedSize;
450
451 // Resource::calculateOverheadSize() is affected by changes in
452 // |m_resourceRequest.url()|, but |m_overheadSize| is not updated after
453 // initial |m_resourceRequest| is given, to reduce MemoryCache manipulation
454 // and thus potential bugs. crbug.com/594644
455 const size_t m_overheadSize;
456
457 unsigned m_preloadCount;
458
459 double m_preloadDiscoveryTime;
460
461 String m_cacheIdentifier;
462
463 PreloadResult m_preloadResult;
464 Type m_type;
465 Status m_status;
466
467 bool m_needsSynchronousCacheHit;
468 bool m_linkPreload;
469 bool m_isRevalidating;
470 bool m_isAlive;
471 bool m_isAddRemoveClientProhibited;
472 bool m_isRevalidationStartForbidden = false;
473
474 ResourceIntegrityDisposition m_integrityDisposition;
475 IntegrityMetadataSet m_integrityMetadata;
476
477 // Ordered list of all redirects followed while fetching this resource.
478 Vector<RedirectPair> m_redirectChain;
479
480 HeapHashCountedSet<WeakMember<ResourceClient>> m_clients;
481 HeapHashCountedSet<WeakMember<ResourceClient>> m_clientsAwaitingCallback;
482 HeapHashCountedSet<WeakMember<ResourceClient>> m_finishedClients;
483
484 ResourceLoaderOptions m_options;
485
486 double m_responseTimestamp;
487
488 TaskRunnerTimer<Resource> m_cancelTimer;
489
490 ResourceRequest m_resourceRequest;
491 Member<ResourceLoader> m_loader;
492 ResourceResponse m_response;
493
494 RefPtr<SharedBuffer> m_data;
495 };
496
497 class ResourceFactory {
498 STACK_ALLOCATED();
499
500 public:
501 virtual Resource* create(const ResourceRequest&,
502 const ResourceLoaderOptions&,
503 const String&) const = 0;
504 Resource::Type type() const { return m_type; }
505
506 protected:
507 explicit ResourceFactory(Resource::Type type) : m_type(type) {}
508
509 Resource::Type m_type;
510 };
511
512 #define DEFINE_RESOURCE_TYPE_CASTS(typeName) \
513 DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, \
514 resource->getType() == Resource::typeName, \
515 resource.getType() == Resource::typeName);
516
517 } // namespace blink
518
519 #endif
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698