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