a6ba2b2ad0a80effae6a1bf5b7003ba810f4bdf8
[WebKit-https.git] / Source / WebKit / NetworkProcess / cache / NetworkCache.cpp
1 /*
2  * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "NetworkCache.h"
28
29 #include "Logging.h"
30 #include "NetworkCacheSpeculativeLoadManager.h"
31 #include "NetworkCacheStatistics.h"
32 #include "NetworkCacheStorage.h"
33 #include "NetworkProcess.h"
34 #include <WebCore/CacheValidation.h>
35 #include <WebCore/HTTPHeaderNames.h>
36 #include <WebCore/LowPowerModeNotifier.h>
37 #include <WebCore/NetworkStorageSession.h>
38 #include <WebCore/ResourceRequest.h>
39 #include <WebCore/ResourceResponse.h>
40 #include <WebCore/SharedBuffer.h>
41 #include <wtf/FileSystem.h>
42 #include <wtf/MainThread.h>
43 #include <wtf/NeverDestroyed.h>
44 #include <wtf/RunLoop.h>
45 #include <wtf/text/StringBuilder.h>
46
47 #if PLATFORM(COCOA)
48 #include <notify.h>
49 #endif
50
51 namespace WebKit {
52 namespace NetworkCache {
53
54 using namespace FileSystem;
55
56 static const AtomicString& resourceType()
57 {
58     ASSERT(WTF::RunLoop::isMain());
59     static NeverDestroyed<const AtomicString> resource("Resource", AtomicString::ConstructFromLiteral);
60     return resource;
61 }
62
63 RefPtr<Cache> Cache::open(NetworkProcess& networkProcess, const String& cachePath, OptionSet<Option> options)
64 {
65     auto storage = Storage::open(cachePath, options.contains(Option::TestingMode) ? Storage::Mode::AvoidRandomness : Storage::Mode::Normal);
66
67     LOG(NetworkCache, "(NetworkProcess) opened cache storage, success %d", !!storage);
68
69     if (!storage)
70         return nullptr;
71
72     return adoptRef(*new Cache(networkProcess, storage.releaseNonNull(), options));
73 }
74
75 #if PLATFORM(GTK)
76 static void dumpFileChanged(Cache* cache)
77 {
78     cache->dumpContentsToFile();
79 }
80 #endif
81
82 Cache::Cache(NetworkProcess& networkProcess, Ref<Storage>&& storage, OptionSet<Option> options)
83     : m_storage(WTFMove(storage))
84     , m_networkProcess(networkProcess)
85 {
86 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
87     if (options.contains(Option::SpeculativeRevalidation)) {
88         m_lowPowerModeNotifier = std::make_unique<WebCore::LowPowerModeNotifier>([this](bool isLowPowerModeEnabled) {
89             ASSERT(WTF::RunLoop::isMain());
90             if (isLowPowerModeEnabled)
91                 m_speculativeLoadManager = nullptr;
92             else {
93                 ASSERT(!m_speculativeLoadManager);
94                 m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
95             }
96         });
97         if (!m_lowPowerModeNotifier->isLowPowerModeEnabled())
98             m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
99     }
100 #endif
101
102     if (options.contains(Option::EfficacyLogging))
103         m_statistics = Statistics::open(*this, m_storage->basePath());
104
105     if (options.contains(Option::RegisterNotify)) {
106 #if PLATFORM(COCOA)
107         // Triggers with "notifyutil -p com.apple.WebKit.Cache.dump".
108         int token;
109         notify_register_dispatch("com.apple.WebKit.Cache.dump", &token, dispatch_get_main_queue(), ^(int) {
110             dumpContentsToFile();
111         });
112 #endif
113 #if PLATFORM(GTK)
114         // Triggers with "touch $cachePath/dump".
115         CString dumpFilePath = fileSystemRepresentation(pathByAppendingComponent(m_storage->basePath(), "dump"));
116         GRefPtr<GFile> dumpFile = adoptGRef(g_file_new_for_path(dumpFilePath.data()));
117         GFileMonitor* monitor = g_file_monitor_file(dumpFile.get(), G_FILE_MONITOR_NONE, nullptr, nullptr);
118         g_signal_connect_swapped(monitor, "changed", G_CALLBACK(dumpFileChanged), this);
119 #endif
120     }
121 }
122
123 Cache::~Cache()
124 {
125 }
126
127 void Cache::setCapacity(size_t maximumSize)
128 {
129     m_storage->setCapacity(maximumSize);
130 }
131
132 Key Cache::makeCacheKey(const WebCore::ResourceRequest& request)
133 {
134     // FIXME: This implements minimal Range header disk cache support. We don't parse
135     // ranges so only the same exact range request will be served from the cache.
136     String range = request.httpHeaderField(WebCore::HTTPHeaderName::Range);
137     return { request.cachePartition(), resourceType(), range, request.url().string(), m_storage->salt() };
138 }
139
140 static bool cachePolicyAllowsExpired(WebCore::ResourceRequestCachePolicy policy)
141 {
142     switch (policy) {
143     case WebCore::ResourceRequestCachePolicy::ReturnCacheDataElseLoad:
144     case WebCore::ResourceRequestCachePolicy::ReturnCacheDataDontLoad:
145         return true;
146     case WebCore::ResourceRequestCachePolicy::UseProtocolCachePolicy:
147     case WebCore::ResourceRequestCachePolicy::ReloadIgnoringCacheData:
148     case WebCore::ResourceRequestCachePolicy::RefreshAnyCacheData:
149         return false;
150     case WebCore::ResourceRequestCachePolicy::DoNotUseAnyCache:
151         ASSERT_NOT_REACHED();
152         return false;
153     }
154     return false;
155 }
156
157 static bool responseHasExpired(const WebCore::ResourceResponse& response, WallTime timestamp, Optional<Seconds> maxStale)
158 {
159     if (response.cacheControlContainsNoCache())
160         return true;
161
162     auto age = WebCore::computeCurrentAge(response, timestamp);
163     auto lifetime = WebCore::computeFreshnessLifetimeForHTTPFamily(response, timestamp);
164
165     auto maximumStaleness = maxStale ? maxStale.value() : 0_ms;
166     bool hasExpired = age - lifetime > maximumStaleness;
167
168 #ifndef LOG_DISABLED
169     if (hasExpired)
170         LOG(NetworkCache, "(NetworkProcess) needsRevalidation hasExpired age=%f lifetime=%f max-stale=%g", age, lifetime, maxStale);
171 #endif
172
173     return hasExpired;
174 }
175
176 static bool responseNeedsRevalidation(const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& request, WallTime timestamp)
177 {
178     auto requestDirectives = WebCore::parseCacheControlDirectives(request.httpHeaderFields());
179     if (requestDirectives.noCache)
180         return true;
181     // For requests we ignore max-age values other than zero.
182     if (requestDirectives.maxAge && requestDirectives.maxAge.value() == 0_ms)
183         return true;
184
185     return responseHasExpired(response, timestamp, requestDirectives.maxStale);
186 }
187
188 static UseDecision makeUseDecision(NetworkProcess& networkProcess, const Entry& entry, const WebCore::ResourceRequest& request)
189 {
190     // The request is conditional so we force revalidation from the network. We merely check the disk cache
191     // so we can update the cache entry.
192     if (request.isConditional() && !entry.redirectRequest())
193         return UseDecision::Validate;
194
195     if (!WebCore::verifyVaryingRequestHeaders(networkProcess.defaultStorageSession(), entry.varyingRequestHeaders(), request))
196         return UseDecision::NoDueToVaryingHeaderMismatch;
197
198     // We never revalidate in the case of a history navigation.
199     if (cachePolicyAllowsExpired(request.cachePolicy()))
200         return UseDecision::Use;
201
202     if (!responseNeedsRevalidation(entry.response(), request, entry.timeStamp()))
203         return UseDecision::Use;
204
205     if (!entry.response().hasCacheValidatorFields())
206         return UseDecision::NoDueToMissingValidatorFields;
207
208     return entry.redirectRequest() ? UseDecision::NoDueToExpiredRedirect : UseDecision::Validate;
209 }
210
211 static RetrieveDecision makeRetrieveDecision(const WebCore::ResourceRequest& request)
212 {
213     ASSERT(request.cachePolicy() != WebCore::ResourceRequestCachePolicy::DoNotUseAnyCache);
214
215     // FIXME: Support HEAD requests.
216     if (request.httpMethod() != "GET")
217         return RetrieveDecision::NoDueToHTTPMethod;
218     if (request.cachePolicy() == WebCore::ResourceRequestCachePolicy::ReloadIgnoringCacheData && !request.isConditional())
219         return RetrieveDecision::NoDueToReloadIgnoringCache;
220
221     return RetrieveDecision::Yes;
222 }
223
224 static bool isMediaMIMEType(const String& type)
225 {
226     return startsWithLettersIgnoringASCIICase(type, "video/") || startsWithLettersIgnoringASCIICase(type, "audio/");
227 }
228
229 static StoreDecision makeStoreDecision(const WebCore::ResourceRequest& originalRequest, const WebCore::ResourceResponse& response, size_t bodySize)
230 {
231     if (!originalRequest.url().protocolIsInHTTPFamily() || !response.isHTTP())
232         return StoreDecision::NoDueToProtocol;
233
234     if (originalRequest.httpMethod() != "GET")
235         return StoreDecision::NoDueToHTTPMethod;
236
237     auto requestDirectives = WebCore::parseCacheControlDirectives(originalRequest.httpHeaderFields());
238     if (requestDirectives.noStore)
239         return StoreDecision::NoDueToNoStoreRequest;
240
241     if (response.cacheControlContainsNoStore())
242         return StoreDecision::NoDueToNoStoreResponse;
243
244     if (!WebCore::isStatusCodeCacheableByDefault(response.httpStatusCode())) {
245         // http://tools.ietf.org/html/rfc7234#section-4.3.2
246         bool hasExpirationHeaders = response.expires() || response.cacheControlMaxAge();
247         bool expirationHeadersAllowCaching = WebCore::isStatusCodePotentiallyCacheable(response.httpStatusCode()) && hasExpirationHeaders;
248         if (!expirationHeadersAllowCaching)
249             return StoreDecision::NoDueToHTTPStatusCode;
250     }
251
252     bool isMainResource = originalRequest.requester() == WebCore::ResourceRequest::Requester::Main;
253     bool storeUnconditionallyForHistoryNavigation = isMainResource || originalRequest.priority() == WebCore::ResourceLoadPriority::VeryHigh;
254     if (!storeUnconditionallyForHistoryNavigation) {
255         auto now = WallTime::now();
256         bool hasNonZeroLifetime = !response.cacheControlContainsNoCache() && WebCore::computeFreshnessLifetimeForHTTPFamily(response, now) > 0_ms;
257
258         bool possiblyReusable = response.hasCacheValidatorFields() || hasNonZeroLifetime;
259         if (!possiblyReusable)
260             return StoreDecision::NoDueToUnlikelyToReuse;
261     }
262
263     // Media loaded via XHR is likely being used for MSE streaming (YouTube and Netflix for example).
264     // Streaming media fills the cache quickly and is unlikely to be reused.
265     // FIXME: We should introduce a separate media cache partition that doesn't affect other resources.
266     // FIXME: We should also make sure make the MSE paths are copy-free so we can use mapped buffers from disk effectively.
267     auto requester = originalRequest.requester();
268     bool isDefinitelyStreamingMedia = requester == WebCore::ResourceRequest::Requester::Media;
269     bool isLikelyStreamingMedia = requester == WebCore::ResourceRequest::Requester::XHR && isMediaMIMEType(response.mimeType());
270     if (isLikelyStreamingMedia || isDefinitelyStreamingMedia)
271         return StoreDecision::NoDueToStreamingMedia;
272
273     return StoreDecision::Yes;
274 }
275
276 void Cache::retrieve(const WebCore::ResourceRequest& request, const GlobalFrameID& frameID, RetrieveCompletionHandler&& completionHandler)
277 {
278     ASSERT(request.url().protocolIsInHTTPFamily());
279
280     LOG(NetworkCache, "(NetworkProcess) retrieving %s priority %d", request.url().string().ascii().data(), static_cast<int>(request.priority()));
281
282     if (m_statistics)
283         m_statistics->recordRetrievalRequest(frameID.first);
284
285     Key storageKey = makeCacheKey(request);
286     auto priority = static_cast<unsigned>(request.priority());
287
288     RetrieveInfo info;
289     info.startTime = MonotonicTime::now();
290     info.priority = priority;
291
292 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
293     bool canUseSpeculativeRevalidation = m_speculativeLoadManager && !request.isConditional() && !cachePolicyAllowsExpired(request.cachePolicy());
294     if (canUseSpeculativeRevalidation)
295         m_speculativeLoadManager->registerLoad(frameID, request, storageKey);
296 #endif
297
298     auto retrieveDecision = makeRetrieveDecision(request);
299     if (retrieveDecision != RetrieveDecision::Yes) {
300         if (m_statistics)
301             m_statistics->recordNotUsingCacheForRequest(frameID.first, storageKey, request, retrieveDecision);
302
303         completeRetrieve(WTFMove(completionHandler), nullptr, info);
304         return;
305     }
306
307 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
308     if (canUseSpeculativeRevalidation && m_speculativeLoadManager->canRetrieve(storageKey, request, frameID)) {
309         m_speculativeLoadManager->retrieve(storageKey, [networkProcess = makeRef(networkProcess()), request, completionHandler = WTFMove(completionHandler), info = WTFMove(info)](std::unique_ptr<Entry> entry) mutable {
310             info.wasSpeculativeLoad = true;
311             if (entry && WebCore::verifyVaryingRequestHeaders(networkProcess->defaultStorageSession(), entry->varyingRequestHeaders(), request))
312                 completeRetrieve(WTFMove(completionHandler), WTFMove(entry), info);
313             else
314                 completeRetrieve(WTFMove(completionHandler), nullptr, info);
315         });
316         return;
317     }
318 #endif
319
320     m_storage->retrieve(storageKey, priority, [this, protectedThis = makeRef(*this), request, completionHandler = WTFMove(completionHandler), info = WTFMove(info), storageKey, frameID, networkProcess = makeRef(networkProcess())](auto record, auto timings) mutable {
321         info.storageTimings = timings;
322
323         if (!record) {
324             LOG(NetworkCache, "(NetworkProcess) not found in storage");
325
326             if (m_statistics)
327                 m_statistics->recordRetrievalFailure(frameID.first, storageKey, request);
328
329             completeRetrieve(WTFMove(completionHandler), nullptr, info);
330             return false;
331         }
332
333         ASSERT(record->key == storageKey);
334
335         auto entry = Entry::decodeStorageRecord(*record);
336
337         auto useDecision = entry ? makeUseDecision(networkProcess, *entry, request) : UseDecision::NoDueToDecodeFailure;
338         switch (useDecision) {
339         case UseDecision::Use:
340             break;
341         case UseDecision::Validate:
342             entry->setNeedsValidation(true);
343             break;
344         default:
345             entry = nullptr;
346         };
347
348 #if !LOG_DISABLED
349         auto elapsed = MonotonicTime::now() - info.startTime;
350         LOG(NetworkCache, "(NetworkProcess) retrieve complete useDecision=%d priority=%d time=%" PRIi64 "ms", static_cast<int>(useDecision), static_cast<int>(request.priority()), elapsed.millisecondsAs<int64_t>());
351 #endif
352         completeRetrieve(WTFMove(completionHandler), WTFMove(entry), info);
353
354         if (m_statistics)
355             m_statistics->recordRetrievedCachedEntry(frameID.first, storageKey, request, useDecision);
356         return useDecision != UseDecision::NoDueToDecodeFailure;
357     });
358 }
359
360 void Cache::completeRetrieve(RetrieveCompletionHandler&& handler, std::unique_ptr<Entry> entry, RetrieveInfo& info)
361 {
362     info.completionTime = MonotonicTime::now();
363     handler(WTFMove(entry), info);
364 }
365     
366 std::unique_ptr<Entry> Cache::makeEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData)
367 {
368     return std::make_unique<Entry>(makeCacheKey(request), response, WTFMove(responseData), WebCore::collectVaryingRequestHeaders(networkProcess().defaultStorageSession(), request, response));
369 }
370
371 std::unique_ptr<Entry> Cache::makeRedirectEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest)
372 {
373     return std::make_unique<Entry>(makeCacheKey(request), response, redirectRequest, WebCore::collectVaryingRequestHeaders(networkProcess().defaultStorageSession(), request, response));
374 }
375
376 std::unique_ptr<Entry> Cache::store(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData, Function<void(MappedBody&)>&& completionHandler)
377 {
378     ASSERT(responseData);
379
380     LOG(NetworkCache, "(NetworkProcess) storing %s, partition %s", request.url().string().latin1().data(), makeCacheKey(request).partition().latin1().data());
381
382     StoreDecision storeDecision = makeStoreDecision(request, response, responseData ? responseData->size() : 0);
383     if (storeDecision != StoreDecision::Yes) {
384         LOG(NetworkCache, "(NetworkProcess) didn't store, storeDecision=%d", static_cast<int>(storeDecision));
385         auto key = makeCacheKey(request);
386
387         auto isSuccessfulRevalidation = response.httpStatusCode() == 304;
388         if (!isSuccessfulRevalidation) {
389             // Make sure we don't keep a stale entry in the cache.
390             remove(key);
391         }
392
393         if (m_statistics)
394             m_statistics->recordNotCachingResponse(key, storeDecision);
395
396         return nullptr;
397     }
398
399     auto cacheEntry = makeEntry(request, response, WTFMove(responseData));
400     auto record = cacheEntry->encodeAsStorageRecord();
401
402     m_storage->store(record, [protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)](const Data& bodyData) mutable {
403         MappedBody mappedBody;
404 #if ENABLE(SHAREABLE_RESOURCE)
405         if (auto sharedMemory = bodyData.tryCreateSharedMemory()) {
406             mappedBody.shareableResource = ShareableResource::create(sharedMemory.releaseNonNull(), 0, bodyData.size());
407             ASSERT(mappedBody.shareableResource);
408             mappedBody.shareableResource->createHandle(mappedBody.shareableResourceHandle);
409         }
410 #endif
411         completionHandler(mappedBody);
412         LOG(NetworkCache, "(NetworkProcess) stored");
413     });
414
415     return cacheEntry;
416 }
417
418 std::unique_ptr<Entry> Cache::storeRedirect(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest, Optional<Seconds> maxAgeCap)
419 {
420     LOG(NetworkCache, "(NetworkProcess) storing redirect %s -> %s", request.url().string().latin1().data(), redirectRequest.url().string().latin1().data());
421
422     StoreDecision storeDecision = makeStoreDecision(request, response, 0);
423     if (storeDecision != StoreDecision::Yes) {
424         LOG(NetworkCache, "(NetworkProcess) didn't store redirect, storeDecision=%d", static_cast<int>(storeDecision));
425         auto key = makeCacheKey(request);
426         if (m_statistics)
427             m_statistics->recordNotCachingResponse(key, storeDecision);
428
429         return nullptr;
430     }
431
432     auto cacheEntry = makeRedirectEntry(request, response, redirectRequest);
433
434 #if ENABLE(RESOURCE_LOAD_STATISTICS)
435     if (maxAgeCap) {
436         LOG(NetworkCache, "(NetworkProcess) capping max age for redirect %s -> %s", request.url().string().latin1().data(), redirectRequest.url().string().latin1().data());
437         cacheEntry->capMaxAge(maxAgeCap.value());
438     }
439 #else
440     UNUSED_PARAM(maxAgeCap);
441 #endif
442
443     auto record = cacheEntry->encodeAsStorageRecord();
444
445     m_storage->store(record, nullptr);
446     
447     return cacheEntry;
448 }
449
450 std::unique_ptr<Entry> Cache::update(const WebCore::ResourceRequest& originalRequest, const GlobalFrameID& frameID, const Entry& existingEntry, const WebCore::ResourceResponse& validatingResponse)
451 {
452     LOG(NetworkCache, "(NetworkProcess) updating %s", originalRequest.url().string().latin1().data());
453
454     WebCore::ResourceResponse response = existingEntry.response();
455     WebCore::updateResponseHeadersAfterRevalidation(response, validatingResponse);
456
457     auto updateEntry = std::make_unique<Entry>(existingEntry.key(), response, existingEntry.buffer(), WebCore::collectVaryingRequestHeaders(networkProcess().defaultStorageSession(), originalRequest, response));
458     auto updateRecord = updateEntry->encodeAsStorageRecord();
459
460     m_storage->store(updateRecord, { });
461
462     if (m_statistics)
463         m_statistics->recordRevalidationSuccess(frameID.first, existingEntry.key(), originalRequest);
464
465     return updateEntry;
466 }
467
468 void Cache::remove(const Key& key)
469 {
470     m_storage->remove(key);
471 }
472
473 void Cache::remove(const WebCore::ResourceRequest& request)
474 {
475     remove(makeCacheKey(request));
476 }
477
478 void Cache::remove(const Vector<Key>& keys, Function<void()>&& completionHandler)
479 {
480     m_storage->remove(keys, WTFMove(completionHandler));
481 }
482
483 void Cache::traverse(Function<void(const TraversalEntry*)>&& traverseHandler)
484 {
485     // Protect against clients making excessive traversal requests.
486     const unsigned maximumTraverseCount = 3;
487     if (m_traverseCount >= maximumTraverseCount) {
488         WTFLogAlways("Maximum parallel cache traverse count exceeded. Ignoring traversal request.");
489
490         RunLoop::main().dispatch([traverseHandler = WTFMove(traverseHandler)] () mutable {
491             traverseHandler(nullptr);
492         });
493         return;
494     }
495
496     ++m_traverseCount;
497
498     m_storage->traverse(resourceType(), { }, [this, protectedThis = makeRef(*this), traverseHandler = WTFMove(traverseHandler)] (const Storage::Record* record, const Storage::RecordInfo& recordInfo) mutable {
499         if (!record) {
500             --m_traverseCount;
501             traverseHandler(nullptr);
502             return;
503         }
504
505         auto entry = Entry::decodeStorageRecord(*record);
506         if (!entry) {
507             traverseHandler(nullptr);
508             return;
509         }
510
511         TraversalEntry traversalEntry { *entry, recordInfo };
512         traverseHandler(&traversalEntry);
513     });
514 }
515
516 String Cache::dumpFilePath() const
517 {
518     return pathByAppendingComponent(m_storage->versionPath(), "dump.json");
519 }
520
521 void Cache::dumpContentsToFile()
522 {
523     auto fd = openFile(dumpFilePath(), FileOpenMode::Write);
524     if (!isHandleValid(fd))
525         return;
526     auto prologue = String("{\n\"entries\": [\n").utf8();
527     writeToFile(fd, prologue.data(), prologue.length());
528
529     struct Totals {
530         unsigned count { 0 };
531         double worth { 0 };
532         size_t bodySize { 0 };
533     };
534     Totals totals;
535     auto flags = { Storage::TraverseFlag::ComputeWorth, Storage::TraverseFlag::ShareCount };
536     size_t capacity = m_storage->capacity();
537     m_storage->traverse(resourceType(), flags, [fd, totals, capacity](const Storage::Record* record, const Storage::RecordInfo& info) mutable {
538         if (!record) {
539             StringBuilder epilogue;
540             epilogue.appendLiteral("{}\n],\n");
541             epilogue.appendLiteral("\"totals\": {\n");
542             epilogue.appendLiteral("\"capacity\": ");
543             epilogue.appendNumber(capacity);
544             epilogue.appendLiteral(",\n");
545             epilogue.appendLiteral("\"count\": ");
546             epilogue.appendNumber(totals.count);
547             epilogue.appendLiteral(",\n");
548             epilogue.appendLiteral("\"bodySize\": ");
549             epilogue.appendNumber(totals.bodySize);
550             epilogue.appendLiteral(",\n");
551             epilogue.appendLiteral("\"averageWorth\": ");
552             epilogue.appendFixedPrecisionNumber(totals.count ? totals.worth / totals.count : 0);
553             epilogue.appendLiteral("\n");
554             epilogue.appendLiteral("}\n}\n");
555             auto writeData = epilogue.toString().utf8();
556             writeToFile(fd, writeData.data(), writeData.length());
557             closeFile(fd);
558             return;
559         }
560         auto entry = Entry::decodeStorageRecord(*record);
561         if (!entry)
562             return;
563         ++totals.count;
564         totals.worth += info.worth;
565         totals.bodySize += info.bodySize;
566
567         StringBuilder json;
568         entry->asJSON(json, info);
569         json.appendLiteral(",\n");
570         auto writeData = json.toString().utf8();
571         writeToFile(fd, writeData.data(), writeData.length());
572     });
573 }
574
575 void Cache::deleteDumpFile()
576 {
577     WorkQueue::create("com.apple.WebKit.Cache.delete")->dispatch([path = dumpFilePath().isolatedCopy()] {
578         deleteFile(path);
579     });
580 }
581
582 void Cache::clear(WallTime modifiedSince, Function<void()>&& completionHandler)
583 {
584     LOG(NetworkCache, "(NetworkProcess) clearing cache");
585
586     if (m_statistics)
587         m_statistics->clear();
588
589     String anyType;
590     m_storage->clear(anyType, modifiedSince, WTFMove(completionHandler));
591
592     deleteDumpFile();
593 }
594
595 void Cache::clear()
596 {
597     clear(-WallTime::infinity(), nullptr);
598 }
599
600 String Cache::recordsPath() const
601 {
602     return m_storage->recordsPath();
603 }
604
605 void Cache::retrieveData(const DataKey& dataKey, Function<void(const uint8_t*, size_t)> completionHandler)
606 {
607     Key key { dataKey, m_storage->salt() };
608     m_storage->retrieve(key, 4, [completionHandler = WTFMove(completionHandler)] (auto record, auto) mutable {
609         if (!record || !record->body.size()) {
610             completionHandler(nullptr, 0);
611             return true;
612         }
613         completionHandler(record->body.data(), record->body.size());
614         return true;
615     });
616 }
617
618 void Cache::storeData(const DataKey& dataKey, const uint8_t* data, size_t size)
619 {
620     Key key { dataKey, m_storage->salt() };
621     Storage::Record record { key, WallTime::now(), { }, Data { data, size }, { } };
622     m_storage->store(record, { });
623 }
624
625 }
626 }