Changeset 220267 in webkit


Ignore:
Timestamp:
Aug 4, 2017 6:25:02 AM (7 years ago)
Author:
Antti Koivisto
Message:

Network cache should be usable as non-singleton
https://bugs.webkit.org/show_bug.cgi?id=175139

Reviewed by Sam Weinig.

We might want to use it as a non-singleton in the future (for example as a backend for the cache API).

This patch makes NetworkCache::Cache and NetworkCache::Storage refcounted objects and takes
care to ref them properly during asynchronous operations.

The patch doesn't actually create any non-shared instances, it just adds the capability.

  • NetworkProcess/NetworkConnectionToWebProcess.cpp:

(WebKit::NetworkConnectionToWebProcess::storeDerivedDataToCache):

  • NetworkProcess/NetworkProcess.cpp:

(WebKit::fetchDiskCacheEntries):
(WebKit::clearDiskCacheEntries):
(WebKit::NetworkProcess::setCacheModel):

  • NetworkProcess/NetworkProcess.h:

(WebKit::NetworkProcess::cache):

Move the shared cache instance to the network process singleton.

  • NetworkProcess/NetworkResourceLoader.cpp:

(WebKit::NetworkResourceLoader::NetworkResourceLoader):

Include shared cache as a reffed member for non-ephemeral instances.

(WebKit::NetworkResourceLoader::canUseCache const):
(WebKit::NetworkResourceLoader::retrieveCacheEntry):
(WebKit::NetworkResourceLoader::abort):
(WebKit::NetworkResourceLoader::didReceiveResponse):
(WebKit::NetworkResourceLoader::willSendRedirectedRequest):
(WebKit::NetworkResourceLoader::tryStoreAsCacheEntry):
(WebKit::NetworkResourceLoader::didRetrieveCacheEntry):

  • NetworkProcess/NetworkResourceLoader.h:
  • NetworkProcess/cache/NetworkCache.cpp:

(WebKit::NetworkCache::Cache::open):

Open now returns null if it fails.
Add RegisterNotify option to set up notify trigger for the shared instance.

(WebKit::NetworkCache::Cache::Cache):
(WebKit::NetworkCache::Cache::~Cache):

Add destructor.

(WebKit::NetworkCache::dumpFileChanged):
(WebKit::NetworkCache::Cache::setCapacity):
(WebKit::NetworkCache::Cache::retrieve):

Protect the cache instance during asynchronous operations.

(WebKit::NetworkCache::Cache::store):
(WebKit::NetworkCache::Cache::storeRedirect):
(WebKit::NetworkCache::Cache::remove):
(WebKit::NetworkCache::Cache::traverse):
(WebKit::NetworkCache::Cache::dumpContentsToFile):
(WebKit::NetworkCache::Cache::clear):
(WebKit::NetworkCache::Cache::recordsPath const):
(WebKit::NetworkCache::Cache::retrieveData):
(WebKit::NetworkCache::Cache::storeData):
(WebKit::NetworkCache::singleton): Deleted.
(WebKit::NetworkCache::Cache::initialize): Deleted.

  • NetworkProcess/cache/NetworkCache.h:

(WebKit::NetworkCache::Cache::canUseSharedMemoryForBodyData const):
(WebKit::NetworkCache::Cache::isEnabled const): Deleted.

Remove isEnabled() state as a cache object now always represents an enabled cache.

  • NetworkProcess/cache/NetworkCacheEntry.cpp:

(WebKit::NetworkCache::Entry::initializeShareableResourceHandleFromStorageRecord const):

  • NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp:

(WebKit::NetworkCache::SpeculativeLoad::willSendRedirectedRequest):
(WebKit::NetworkCache::SpeculativeLoad::didReceiveResponse):
(WebKit::NetworkCache::SpeculativeLoad::didFinishLoading):

  • NetworkProcess/cache/NetworkCacheStatistics.cpp:

(WebKit::NetworkCache::Statistics::initialize):
(WebKit::NetworkCache::Statistics::shrinkIfNeeded):

  • NetworkProcess/cache/NetworkCacheStorage.cpp:

(WebKit::NetworkCache::Storage::ReadOperation::ReadOperation):
(WebKit::NetworkCache::Storage::WriteOperation::WriteOperation):
(WebKit::NetworkCache::Storage::TraverseOperation::TraverseOperation):

Operations now ref the storage. They are already deleted in the main thread so
proper destruction is taken care of.

(WebKit::NetworkCache::Storage::open):
(WebKit::NetworkCache::Storage::~Storage):
(WebKit::NetworkCache::Storage::synchronize):

This and other asynchronous methods now protect the Storage instance.

(WebKit::NetworkCache::Storage::remove):
(WebKit::NetworkCache::Storage::retrieve):
(WebKit::NetworkCache::Storage::store):
(WebKit::NetworkCache::Storage::traverse):
(WebKit::NetworkCache::Storage::clear):
(WebKit::NetworkCache::Storage::shrink):
(WebKit::NetworkCache::Storage::deleteOldVersions):

  • NetworkProcess/cache/NetworkCacheStorage.h:
  • NetworkProcess/cocoa/NetworkProcessCocoa.mm:

(WebKit::NetworkProcess::platformInitializeNetworkProcessCocoa):
(WebKit::NetworkProcess::clearDiskCache):

  • NetworkProcess/cocoa/NetworkSessionCocoa.mm:

(WebKit::NetworkSessionCocoa::NetworkSessionCocoa):

  • NetworkProcess/soup/NetworkProcessSoup.cpp:

(WebKit::NetworkProcess::platformInitializeNetworkProcess):
(WebKit::NetworkProcess::clearDiskCache):

Location:
trunk/Source/WebKit
Files:
22 edited

Legend:

Unmodified
Added
Removed
  • trunk/Source/WebKit/ChangeLog

    r220261 r220267  
     12017-08-04  Antti Koivisto  <antti@apple.com>
     2
     3        Network cache should be usable as non-singleton
     4        https://bugs.webkit.org/show_bug.cgi?id=175139
     5
     6        Reviewed by Sam Weinig.
     7
     8        We might want to use it as a non-singleton in the future (for example as a backend for the cache API).
     9
     10        This patch makes NetworkCache::Cache and NetworkCache::Storage refcounted objects and takes
     11        care to ref them properly during asynchronous operations.
     12
     13        The patch doesn't actually create any non-shared instances, it just adds the capability.
     14
     15        * NetworkProcess/NetworkConnectionToWebProcess.cpp:
     16        (WebKit::NetworkConnectionToWebProcess::storeDerivedDataToCache):
     17        * NetworkProcess/NetworkProcess.cpp:
     18        (WebKit::fetchDiskCacheEntries):
     19        (WebKit::clearDiskCacheEntries):
     20        (WebKit::NetworkProcess::setCacheModel):
     21        * NetworkProcess/NetworkProcess.h:
     22        (WebKit::NetworkProcess::cache):
     23
     24            Move the shared cache instance to the network process singleton.
     25
     26        * NetworkProcess/NetworkResourceLoader.cpp:
     27        (WebKit::NetworkResourceLoader::NetworkResourceLoader):
     28
     29            Include shared cache as a reffed member for non-ephemeral instances.
     30
     31        (WebKit::NetworkResourceLoader::canUseCache const):
     32        (WebKit::NetworkResourceLoader::retrieveCacheEntry):
     33        (WebKit::NetworkResourceLoader::abort):
     34        (WebKit::NetworkResourceLoader::didReceiveResponse):
     35        (WebKit::NetworkResourceLoader::willSendRedirectedRequest):
     36        (WebKit::NetworkResourceLoader::tryStoreAsCacheEntry):
     37        (WebKit::NetworkResourceLoader::didRetrieveCacheEntry):
     38        * NetworkProcess/NetworkResourceLoader.h:
     39        * NetworkProcess/cache/NetworkCache.cpp:
     40        (WebKit::NetworkCache::Cache::open):
     41
     42            Open now returns null if it fails.
     43            Add RegisterNotify option to set up notify trigger for the shared instance.
     44
     45        (WebKit::NetworkCache::Cache::Cache):
     46        (WebKit::NetworkCache::Cache::~Cache):
     47
     48            Add destructor.
     49
     50        (WebKit::NetworkCache::dumpFileChanged):
     51        (WebKit::NetworkCache::Cache::setCapacity):
     52        (WebKit::NetworkCache::Cache::retrieve):
     53
     54            Protect the cache instance during asynchronous operations.
     55
     56        (WebKit::NetworkCache::Cache::store):
     57        (WebKit::NetworkCache::Cache::storeRedirect):
     58        (WebKit::NetworkCache::Cache::remove):
     59        (WebKit::NetworkCache::Cache::traverse):
     60        (WebKit::NetworkCache::Cache::dumpContentsToFile):
     61        (WebKit::NetworkCache::Cache::clear):
     62        (WebKit::NetworkCache::Cache::recordsPath const):
     63        (WebKit::NetworkCache::Cache::retrieveData):
     64        (WebKit::NetworkCache::Cache::storeData):
     65        (WebKit::NetworkCache::singleton): Deleted.
     66        (WebKit::NetworkCache::Cache::initialize): Deleted.
     67        * NetworkProcess/cache/NetworkCache.h:
     68        (WebKit::NetworkCache::Cache::canUseSharedMemoryForBodyData const):
     69        (WebKit::NetworkCache::Cache::isEnabled const): Deleted.
     70
     71            Remove isEnabled() state as a cache object now always represents an enabled cache.
     72
     73        * NetworkProcess/cache/NetworkCacheEntry.cpp:
     74        (WebKit::NetworkCache::Entry::initializeShareableResourceHandleFromStorageRecord const):
     75        * NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp:
     76        (WebKit::NetworkCache::SpeculativeLoad::willSendRedirectedRequest):
     77        (WebKit::NetworkCache::SpeculativeLoad::didReceiveResponse):
     78        (WebKit::NetworkCache::SpeculativeLoad::didFinishLoading):
     79        * NetworkProcess/cache/NetworkCacheStatistics.cpp:
     80        (WebKit::NetworkCache::Statistics::initialize):
     81        (WebKit::NetworkCache::Statistics::shrinkIfNeeded):
     82        * NetworkProcess/cache/NetworkCacheStorage.cpp:
     83        (WebKit::NetworkCache::Storage::ReadOperation::ReadOperation):
     84        (WebKit::NetworkCache::Storage::WriteOperation::WriteOperation):
     85        (WebKit::NetworkCache::Storage::TraverseOperation::TraverseOperation):
     86
     87            Operations now ref the storage. They are already deleted in the main thread so
     88            proper destruction is taken care of.
     89
     90        (WebKit::NetworkCache::Storage::open):
     91        (WebKit::NetworkCache::Storage::~Storage):
     92        (WebKit::NetworkCache::Storage::synchronize):
     93
     94            This and other asynchronous methods now protect the Storage instance.
     95
     96        (WebKit::NetworkCache::Storage::remove):
     97        (WebKit::NetworkCache::Storage::retrieve):
     98        (WebKit::NetworkCache::Storage::store):
     99        (WebKit::NetworkCache::Storage::traverse):
     100        (WebKit::NetworkCache::Storage::clear):
     101        (WebKit::NetworkCache::Storage::shrink):
     102        (WebKit::NetworkCache::Storage::deleteOldVersions):
     103        * NetworkProcess/cache/NetworkCacheStorage.h:
     104        * NetworkProcess/cocoa/NetworkProcessCocoa.mm:
     105        (WebKit::NetworkProcess::platformInitializeNetworkProcessCocoa):
     106        (WebKit::NetworkProcess::clearDiskCache):
     107        * NetworkProcess/cocoa/NetworkSessionCocoa.mm:
     108        (WebKit::NetworkSessionCocoa::NetworkSessionCocoa):
     109        * NetworkProcess/soup/NetworkProcessSoup.cpp:
     110        (WebKit::NetworkProcess::platformInitializeNetworkProcess):
     111        (WebKit::NetworkProcess::clearDiskCache):
     112
    11132017-08-04  Frederic Wang  <fwang@igalia.com>
    2114
  • trunk/Source/WebKit/NetworkProcess/NetworkConnectionToWebProcess.cpp

    r220105 r220267  
    410410void NetworkConnectionToWebProcess::storeDerivedDataToCache(const WebKit::NetworkCache::DataKey& dataKey, const IPC::DataReference& data)
    411411{
    412     NetworkCache::singleton().storeData(dataKey, data.data(), data.size());
     412    if (auto* cache = NetworkProcess::singleton().cache())
     413        cache->storeData(dataKey, data.data(), data.size());
    413414}
    414415
  • trunk/Source/WebKit/NetworkProcess/NetworkProcess.cpp

    r220105 r220267  
    329329{
    330330#if ENABLE(NETWORK_CACHE)
    331     if (NetworkCache::singleton().isEnabled()) {
     331    if (auto* cache = NetworkProcess::singleton().cache()) {
    332332        HashMap<SecurityOriginData, uint64_t> originsAndSizes;
    333         NetworkCache::singleton().traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
     333        cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
    334334            if (!traversalEntry) {
    335335                Vector<WebsiteData::Entry> entries;
     
    437437{
    438438#if ENABLE(NETWORK_CACHE)
    439     if (NetworkCache::singleton().isEnabled()) {
     439    if (auto* cache = NetworkProcess::singleton().cache()) {
    440440        HashSet<RefPtr<SecurityOrigin>> originsToDelete;
    441441        for (auto& origin : origins)
     
    443443
    444444        Vector<NetworkCache::Key> cacheKeysToDelete;
    445         NetworkCache::singleton().traverse([completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
     445        cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
    446446            if (traversalEntry) {
    447447                if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
     
    450450            }
    451451
    452             NetworkCache::singleton().remove(cacheKeysToDelete, WTFMove(completionHandler));
     452            cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
    453453            return;
    454454        });
     
    576576
    577577#if ENABLE(NETWORK_CACHE)
    578     auto& networkCache = NetworkCache::singleton();
    579     if (networkCache.isEnabled()) {
    580         networkCache.setCapacity(urlCacheDiskCapacity);
     578    if (m_cache) {
     579        m_cache->setCapacity(urlCacheDiskCapacity);
    581580        return;
    582581    }
  • trunk/Source/WebKit/NetworkProcess/NetworkProcess.h

    r220105 r220267  
    6464struct WebsiteDataStoreParameters;
    6565
     66namespace NetworkCache {
     67class Cache;
     68}
     69
    6670class NetworkProcess : public ChildProcess, private DownloadManager::Client {
    6771    WTF_MAKE_NONCOPYABLE(NetworkProcess);
     
    8791    AuthenticationManager& authenticationManager();
    8892    DownloadManager& downloadManager();
     93
     94    NetworkCache::Cache* cache() { return m_cache.get(); }
     95
    8996    bool canHandleHTTPSServerTrustEvaluation() const { return m_canHandleHTTPSServerTrustEvaluation; }
    9097
     
    221228    Seconds m_loadThrottleLatency;
    222229
     230    RefPtr<NetworkCache::Cache> m_cache;
     231
    223232    typedef HashMap<const char*, std::unique_ptr<NetworkProcessSupplement>, PtrHash<const char*>> NetworkProcessSupplementMap;
    224233    NetworkProcessSupplementMap m_supplements;
  • trunk/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp

    r220185 r220267  
    8787    , m_defersLoading(parameters.defersLoading)
    8888    , m_bufferingTimer(*this, &NetworkResourceLoader::bufferingTimerFired)
     89    , m_cache(sessionID().isEphemeral() ? nullptr : NetworkProcess::singleton().cache())
    8990{
    9091    ASSERT(RunLoop::isMain());
     
    122123bool NetworkResourceLoader::canUseCache(const ResourceRequest& request) const
    123124{
    124     if (!NetworkCache::singleton().isEnabled())
     125    if (!m_cache)
    125126        return false;
    126     if (sessionID().isEphemeral())
    127         return false;
     127    ASSERT(!sessionID().isEphemeral());
     128
    128129    if (!request.url().protocolIsInHTTPFamily())
    129130        return false;
     
    182183
    183184    RefPtr<NetworkResourceLoader> loader(this);
    184     NetworkCache::singleton().retrieve(request, { m_parameters.webPageID, m_parameters.webFrameID }, [this, loader = WTFMove(loader), request](auto entry) {
     185    m_cache->retrieve(request, { m_parameters.webPageID, m_parameters.webFrameID }, [this, loader = WTFMove(loader), request](auto entry) {
    185186        if (loader->hasOneRef()) {
    186187            // The loader has been aborted and is only held alive by this lambda.
     
    308309            // We might already have used data from this incomplete load. Ensure older versions don't remain in the cache after cancel.
    309310            if (!m_response.isNull())
    310                 NetworkCache::singleton().remove(m_networkLoad->currentRequest());
     311                m_cache->remove(m_networkLoad->currentRequest());
    311312        }
    312313#endif
     
    335336        bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
    336337        if (validationSucceeded) {
    337             m_cacheEntryForValidation = NetworkCache::singleton().update(originalRequest(), { m_parameters.webPageID, m_parameters.webFrameID }, *m_cacheEntryForValidation, m_response);
     338            m_cacheEntryForValidation = m_cache->update(originalRequest(), { m_parameters.webPageID, m_parameters.webFrameID }, *m_cacheEntryForValidation, m_response);
    338339            // If the request was conditional then this revalidation was not triggered by the network cache and we pass the 304 response to WebCore.
    339340            if (originalRequest().isConditional())
     
    471472#if ENABLE(NETWORK_CACHE)
    472473    if (canUseCachedRedirect(request))
    473         NetworkCache::singleton().storeRedirect(request, redirectResponse, redirectRequest);
     474        m_cache->storeRedirect(request, redirectResponse, redirectRequest);
    474475#else
    475476    UNUSED_PARAM(request);
     
    560561        return;
    561562
    562     NetworkCache::singleton().store(m_networkLoad->currentRequest(), m_response, WTFMove(m_bufferedDataForCache), [loader = makeRef(*this)](auto& mappedBody) mutable {
     563    m_cache->store(m_networkLoad->currentRequest(), m_response, WTFMove(m_bufferedDataForCache), [loader = makeRef(*this)](auto& mappedBody) mutable {
    563564#if ENABLE(SHAREABLE_RESOURCE)
    564565        if (mappedBody.shareableResourceHandle.isNull())
     
    589590        for (auto& type : m_parameters.derivedCachedDataTypesToRetrieve) {
    590591            NetworkCache::DataKey key { originalRequest().cachePartition(), type, bodyHash };
    591             NetworkCache::singleton().retrieveData(key, [loader = makeRef(*this), entryPtr, type, retrieveCount] (const uint8_t* data, size_t size) mutable {
     592            m_cache->retrieveData(key, [loader = makeRef(*this), entryPtr, type, retrieveCount] (const uint8_t* data, size_t size) mutable {
    592593                loader->m_retrievedDerivedDataCount++;
    593594                bool retrievedAll = loader->m_retrievedDerivedDataCount == retrieveCount;
  • trunk/Source/WebKit/NetworkProcess/NetworkResourceLoader.h

    r220185 r220267  
    161161    WebCore::Timer m_bufferingTimer;
    162162#if ENABLE(NETWORK_CACHE)
     163    RefPtr<NetworkCache::Cache> m_cache;
    163164    RefPtr<WebCore::SharedBuffer> m_bufferedDataForCache;
    164165    std::unique_ptr<NetworkCache::Entry> m_cacheEntryForValidation;
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCache.cpp

    r219249 r220267  
    11/*
    2  * Copyright (C) 2014-2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    6363}
    6464
    65 Cache& singleton()
    66 {
    67     static NeverDestroyed<Cache> instance;
    68     return instance;
     65RefPtr<Cache> Cache::open(const String& cachePath, OptionSet<Option> options)
     66{
     67    auto storage = Storage::open(cachePath, options.contains(Option::TestingMode) ? Storage::Mode::Testing : Storage::Mode::Normal);
     68
     69    LOG(NetworkCache, "(NetworkProcess) opened cache storage, success %d", !!storage);
     70
     71    if (!storage)
     72        return nullptr;
     73
     74    return adoptRef(*new Cache(storage.releaseNonNull(), options));
    6975}
    7076
     
    7682#endif
    7783
    78 bool Cache::initialize(const String& cachePath, OptionSet<Option> options)
    79 {
    80     m_storage = Storage::open(cachePath, options.contains(Option::TestingMode) ? Storage::Mode::Testing : Storage::Mode::Normal);
    81 
     84Cache::Cache(Ref<Storage>&& storage, OptionSet<Option> options)
     85    : m_storage(WTFMove(storage))
     86{
    8287#if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
    8388    if (options.contains(Option::SpeculativeRevalidation)) {
     
    8893            else {
    8994                ASSERT(!m_speculativeLoadManager);
    90                 m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*m_storage);
     95                m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
    9196            }
    9297        });
    9398        if (!m_lowPowerModeNotifier->isLowPowerModeEnabled())
    94             m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*m_storage);
     99            m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
    95100    }
    96101#endif
    97102
    98103    if (options.contains(Option::EfficacyLogging))
    99         m_statistics = Statistics::open(cachePath);
    100 
     104        m_statistics = Statistics::open(*this, m_storage->basePath());
     105
     106    if (options.contains(Option::RegisterNotify)) {
    101107#if PLATFORM(COCOA)
    102     // Triggers with "notifyutil -p com.apple.WebKit.Cache.dump".
    103     if (m_storage) {
     108        // Triggers with "notifyutil -p com.apple.WebKit.Cache.dump".
    104109        int token;
    105110        notify_register_dispatch("com.apple.WebKit.Cache.dump", &token, dispatch_get_main_queue(), ^(int) {
    106111            dumpContentsToFile();
    107112        });
    108     }
    109113#endif
    110114#if PLATFORM(GTK)
    111     // Triggers with "touch $cachePath/dump".
    112     if (m_storage) {
     115        // Triggers with "touch $cachePath/dump".
    113116        CString dumpFilePath = WebCore::fileSystemRepresentation(WebCore::pathByAppendingComponent(m_storage->basePath(), "dump"));
    114117        GRefPtr<GFile> dumpFile = adoptGRef(g_file_new_for_path(dumpFilePath.data()));
    115118        GFileMonitor* monitor = g_file_monitor_file(dumpFile.get(), G_FILE_MONITOR_NONE, nullptr, nullptr);
    116119        g_signal_connect_swapped(monitor, "changed", G_CALLBACK(dumpFileChanged), this);
    117     }
    118 #endif
    119 
    120     LOG(NetworkCache, "(NetworkProcess) opened cache storage, success %d", !!m_storage);
    121     return !!m_storage;
     120#endif
     121    }
     122}
     123
     124Cache::~Cache()
     125{
    122126}
    123127
    124128void Cache::setCapacity(size_t maximumSize)
    125129{
    126     if (!m_storage)
    127         return;
    128130    m_storage->setCapacity(maximumSize);
    129131}
     
    316318void Cache::retrieve(const WebCore::ResourceRequest& request, const GlobalFrameID& frameID, Function<void (std::unique_ptr<Entry>)>&& completionHandler)
    317319{
    318     ASSERT(isEnabled());
    319320    ASSERT(request.url().protocolIsInHTTPFamily());
    320321
     
    356357    auto priority = static_cast<unsigned>(request.priority());
    357358
    358     m_storage->retrieve(storageKey, priority, [this, request, completionHandler = WTFMove(completionHandler), startTime, storageKey, frameID](auto record) {
     359    m_storage->retrieve(storageKey, priority, [this, protectedThis = makeRef(*this), request, completionHandler = WTFMove(completionHandler), startTime, storageKey, frameID](auto record) {
    359360        if (!record) {
    360361            LOG(NetworkCache, "(NetworkProcess) not found in storage");
     
    409410std::unique_ptr<Entry> Cache::store(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData, Function<void (MappedBody&)>&& completionHandler)
    410411{
    411     ASSERT(isEnabled());
    412412    ASSERT(responseData);
    413413
     
    434434    auto record = cacheEntry->encodeAsStorageRecord();
    435435
    436     m_storage->store(record, [this, completionHandler = WTFMove(completionHandler)](const Data& bodyData) {
     436    m_storage->store(record, [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)](const Data& bodyData) {
    437437        MappedBody mappedBody;
    438438#if ENABLE(SHAREABLE_RESOURCE)
     
    454454std::unique_ptr<Entry> Cache::storeRedirect(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest)
    455455{
    456     ASSERT(isEnabled());
    457 
    458456    LOG(NetworkCache, "(NetworkProcess) storing redirect %s -> %s", request.url().string().latin1().data(), redirectRequest.url().string().latin1().data());
    459457
     
    496494void Cache::remove(const Key& key)
    497495{
    498     ASSERT(isEnabled());
    499 
    500496    m_storage->remove(key);
    501497}
     
    508504void Cache::remove(const Vector<Key>& keys, Function<void ()>&& completionHandler)
    509505{
    510     ASSERT(isEnabled());
    511 
    512506    m_storage->remove(keys, WTFMove(completionHandler));
    513507}
     
    515509void Cache::traverse(Function<void (const TraversalEntry*)>&& traverseHandler)
    516510{
    517     ASSERT(isEnabled());
    518 
    519511    // Protect against clients making excessive traversal requests.
    520512    const unsigned maximumTraverseCount = 3;
     
    530522    ++m_traverseCount;
    531523
    532     m_storage->traverse(resourceType(), 0, [this, traverseHandler = WTFMove(traverseHandler)](const Storage::Record* record, const Storage::RecordInfo& recordInfo) {
     524    m_storage->traverse(resourceType(), 0, [this, protectedThis = makeRef(*this), traverseHandler = WTFMove(traverseHandler)](const Storage::Record* record, const Storage::RecordInfo& recordInfo) {
    533525        if (!record) {
    534526            --m_traverseCount;
     
    553545void Cache::dumpContentsToFile()
    554546{
    555     if (!m_storage)
    556         return;
    557547    auto fd = WebCore::openFile(dumpFilePath(), WebCore::OpenForWrite);
    558548    if (!WebCore::isHandleValid(fd))
     
    621611        m_statistics->clear();
    622612
    623     if (!m_storage) {
    624         RunLoop::main().dispatch(WTFMove(completionHandler));
    625         return;
    626     }
    627613    String anyType;
    628614    m_storage->clear(anyType, modifiedSince, WTFMove(completionHandler));
     
    638624String Cache::recordsPath() const
    639625{
    640     return m_storage ? m_storage->recordsPath() : String();
     626    return m_storage->recordsPath();
    641627}
    642628
    643629void Cache::retrieveData(const DataKey& dataKey, Function<void (const uint8_t* data, size_t size)> completionHandler)
    644630{
    645     ASSERT(isEnabled());
    646 
    647631    Key key { dataKey, m_storage->salt() };
    648632    m_storage->retrieve(key, 4, [completionHandler = WTFMove(completionHandler)] (auto record) {
     
    658642void Cache::storeData(const DataKey& dataKey, const uint8_t* data, size_t size)
    659643{
    660     if (!m_storage)
    661         return;
    662644    Key key { dataKey, m_storage->salt() };
    663645    Storage::Record record { key, std::chrono::system_clock::now(), { }, Data { data, size }, { } };
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCache.h

    r219249 r220267  
    11/*
    2  * Copyright (C) 2014-2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2424 */
    2525
    26 #ifndef NetworkCache_h
    27 #define NetworkCache_h
     26#pragma once
    2827
    2928#if ENABLE(NETWORK_CACHE)
     
    5049class SpeculativeLoadManager;
    5150class Statistics;
    52 
    53 Cache& singleton();
    5451
    5552struct MappedBody {
     
    9289using GlobalFrameID = std::pair<uint64_t /*webPageID*/, uint64_t /*webFrameID*/>;
    9390
    94 class Cache {
    95     WTF_MAKE_NONCOPYABLE(Cache);
    96     friend class WTF::NeverDestroyed<Cache>;
     91class Cache : public RefCounted<Cache> {
    9792public:
    9893    enum class Option {
     
    10095        // In testing mode we try to eliminate sources of randomness. Cache does not shrink and there are no read timeouts.
    10196        TestingMode = 1 << 1,
     97        RegisterNotify = 1 << 2,
    10298#if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
    103         SpeculativeRevalidation = 1 << 2,
     99        SpeculativeRevalidation = 1 << 3,
    104100#endif
    105101    };
    106     bool initialize(const String& cachePath, OptionSet<Option>);
     102    static RefPtr<Cache> open(const String& cachePath, OptionSet<Option>);
     103
    107104    void setCapacity(size_t);
    108 
    109     bool isEnabled() const { return !!m_storage; }
    110105
    111106    // Completion handler may get called back synchronously on failure.
     
    136131
    137132    String recordsPath() const;
    138     bool canUseSharedMemoryForBodyData() const { return m_storage && m_storage->canUseSharedMemoryForBodyData(); }
     133    bool canUseSharedMemoryForBodyData() const { return m_storage->canUseSharedMemoryForBodyData(); }
    139134
    140135#if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
     
    142137#endif
    143138
     139    ~Cache();
     140
    144141private:
    145     Cache() = default;
    146     ~Cache() = delete;
     142    Cache(Ref<Storage>&&, OptionSet<Option> options);
    147143
    148144    Key makeCacheKey(const WebCore::ResourceRequest&);
     
    151147    void deleteDumpFile();
    152148
    153     std::unique_ptr<Storage> m_storage;
     149    Ref<Storage> m_storage;
     150
    154151#if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
    155152    std::unique_ptr<WebCore::LowPowerModeNotifier> m_lowPowerModeNotifier;
     
    164161}
    165162#endif
    166 #endif
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.cpp

    r212244 r220267  
    2929#include "Logging.h"
    3030#include "NetworkCacheCoders.h"
     31#include "NetworkProcess.h"
    3132#include <WebCore/ResourceRequest.h>
    3233#include <WebCore/SharedBuffer.h>
     
    147148void Entry::initializeShareableResourceHandleFromStorageRecord() const
    148149{
    149     if (!NetworkCache::singleton().canUseSharedMemoryForBodyData())
     150    auto* cache = NetworkProcess::singleton().cache();
     151    if (!cache || !cache->canUseSharedMemoryForBodyData())
    150152        return;
    151153
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp

    r215078 r220267  
    4242using namespace WebCore;
    4343
    44 SpeculativeLoad::SpeculativeLoad(const GlobalFrameID& frameID, const ResourceRequest& request, std::unique_ptr<NetworkCache::Entry> cacheEntryForValidation, RevalidationCompletionHandler&& completionHandler)
    45     : m_frameID(frameID)
     44SpeculativeLoad::SpeculativeLoad(Cache& cache, const GlobalFrameID& frameID, const ResourceRequest& request, std::unique_ptr<NetworkCache::Entry> cacheEntryForValidation, RevalidationCompletionHandler&& completionHandler)
     45    : m_cache(cache)
     46    , m_frameID(frameID)
    4647    , m_completionHandler(WTFMove(completionHandler))
    4748    , m_originalRequest(request)
     
    7273    LOG(NetworkCacheSpeculativePreloading, "Speculative redirect %s -> %s", request.url().string().utf8().data(), redirectRequest.url().string().utf8().data());
    7374
    74     m_cacheEntry = NetworkCache::singleton().storeRedirect(request, redirectResponse, redirectRequest);
     75    m_cacheEntry = m_cache->storeRedirect(request, redirectResponse, redirectRequest);
    7576    // Create a synthetic cache entry if we can't store.
    7677    if (!m_cacheEntry)
    77         m_cacheEntry = NetworkCache::singleton().makeRedirectEntry(request, redirectResponse, redirectRequest);
     78        m_cacheEntry = m_cache->makeRedirectEntry(request, redirectResponse, redirectRequest);
    7879
    7980    // Don't follow the redirect. The redirect target will be registered for speculative load when it is loaded.
     
    9091    bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
    9192    if (validationSucceeded && m_cacheEntry)
    92         m_cacheEntry = NetworkCache::singleton().update(m_originalRequest, m_frameID, *m_cacheEntry, m_response);
     93        m_cacheEntry = m_cache->update(m_originalRequest, m_frameID, *m_cacheEntry, m_response);
    9394    else
    9495        m_cacheEntry = nullptr;
     
    116117        return;
    117118    if (!m_cacheEntry && m_bufferedDataForCache) {
    118         m_cacheEntry = NetworkCache::singleton().store(m_originalRequest, m_response, m_bufferedDataForCache.copyRef(), [](auto& mappedBody) { });
     119        m_cacheEntry = m_cache->store(m_originalRequest, m_response, m_bufferedDataForCache.copyRef(), [](auto& mappedBody) { });
    119120        // Create a synthetic cache entry if we can't store.
    120121        if (!m_cacheEntry && isStatusCodeCacheableByDefault(m_response.httpStatusCode()))
    121             m_cacheEntry = NetworkCache::singleton().makeEntry(m_originalRequest, m_response, WTFMove(m_bufferedDataForCache));
     122            m_cacheEntry = m_cache->makeEntry(m_originalRequest, m_response, WTFMove(m_bufferedDataForCache));
    122123    }
    123124
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.h

    r218024 r220267  
    2424 */
    2525
    26 #ifndef NetworkCacheSpeculativeLoad_h
    27 #define NetworkCacheSpeculativeLoad_h
     26#pragma once
    2827
    2928#if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
     
    4645public:
    4746    typedef Function<void (std::unique_ptr<NetworkCache::Entry>)> RevalidationCompletionHandler;
    48     SpeculativeLoad(const GlobalFrameID&, const WebCore::ResourceRequest&, std::unique_ptr<NetworkCache::Entry>, RevalidationCompletionHandler&&);
     47    SpeculativeLoad(Cache&, const GlobalFrameID&, const WebCore::ResourceRequest&, std::unique_ptr<NetworkCache::Entry>, RevalidationCompletionHandler&&);
    4948
    5049    virtual ~SpeculativeLoad();
     
    6766    void didComplete();
    6867
     68    Ref<Cache> m_cache;
    6969    GlobalFrameID m_frameID;
    7070    RevalidationCompletionHandler m_completionHandler;
     
    8484
    8585#endif // ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
    86 
    87 #endif // NetworkCacheSpeculativeLoad_h
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoadManager.cpp

    r217979 r220267  
    246246};
    247247
    248 SpeculativeLoadManager::SpeculativeLoadManager(Storage& storage)
    249     : m_storage(storage)
     248SpeculativeLoadManager::SpeculativeLoadManager(Cache& cache, Storage& storage)
     249    : m_cache(cache)
     250    , m_storage(storage)
    250251{
    251252}
     
    467468    LOG(NetworkCacheSpeculativePreloading, "(NetworkProcess) Speculatively revalidating '%s':", key.identifier().utf8().data());
    468469
    469     auto revalidator = std::make_unique<SpeculativeLoad>(frameID, revalidationRequest, WTFMove(entry), [this, key, revalidationRequest, frameID](std::unique_ptr<Entry> revalidatedEntry) {
     470    auto revalidator = std::make_unique<SpeculativeLoad>(m_cache, frameID, revalidationRequest, WTFMove(entry), [this, key, revalidationRequest, frameID](std::unique_ptr<Entry> revalidatedEntry) {
    470471        ASSERT(!revalidatedEntry || !revalidatedEntry->needsValidation());
    471472        ASSERT(!revalidatedEntry || revalidatedEntry->key() == key);
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoadManager.h

    r217947 r220267  
    4747    WTF_MAKE_FAST_ALLOCATED;
    4848public:
    49     explicit SpeculativeLoadManager(Storage&);
     49    explicit SpeculativeLoadManager(Cache&, Storage&);
    5050    ~SpeculativeLoadManager();
    5151
     
    7171    static bool canUsePendingPreload(const SpeculativeLoad&, const WebCore::ResourceRequest& actualRequest);
    7272
     73    Cache& m_cache;
    7374    Storage& m_storage;
    7475
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheStatistics.cpp

    r216841 r220267  
    7575}
    7676
    77 std::unique_ptr<Statistics> Statistics::open(const String& cachePath)
     77std::unique_ptr<Statistics> Statistics::open(Cache& cache, const String& cachePath)
    7878{
    7979    ASSERT(RunLoop::isMain());
    8080
    8181    String databasePath = WebCore::pathByAppendingComponent(cachePath, StatisticsDatabaseName);
    82     return std::make_unique<Statistics>(databasePath);
    83 }
    84 
    85 Statistics::Statistics(const String& databasePath)
    86     : m_serialBackgroundIOQueue(WorkQueue::create("com.apple.WebKit.Cache.Statistics.Background", WorkQueue::Type::Serial, WorkQueue::QOS::Background))
     82    return std::make_unique<Statistics>(cache, databasePath);
     83}
     84
     85Statistics::Statistics(Cache& cache, const String& databasePath)
     86    : m_cache(cache)
     87    , m_serialBackgroundIOQueue(WorkQueue::create("com.apple.WebKit.Cache.Statistics.Background", WorkQueue::Type::Serial, WorkQueue::QOS::Background))
    8788    , m_writeTimer(*this, &Statistics::writeTimerFired)
    8889{
     
    9697    auto startTime = std::chrono::system_clock::now();
    9798
    98     serialBackgroundIOQueue().dispatch([this, databasePath = databasePath.isolatedCopy(), networkCachePath = singleton().recordsPath().isolatedCopy(), startTime] {
     99    serialBackgroundIOQueue().dispatch([this, databasePath = databasePath.isolatedCopy(), networkCachePath = m_cache.recordsPath(), startTime] {
    99100        WebCore::SQLiteTransactionInProgressAutoCounter transactionCounter;
    100101
     
    179180    clear();
    180181
    181     serialBackgroundIOQueue().dispatch([this, networkCachePath = singleton().recordsPath().isolatedCopy()] {
     182    serialBackgroundIOQueue().dispatch([this, networkCachePath = m_cache.recordsPath()] {
    182183        bootstrapFromNetworkCache(networkCachePath);
    183184        LOG(NetworkCache, "(NetworkProcess) statistics cache shrink completed m_approximateEntryCount=%lu", static_cast<size_t>(m_approximateEntryCount));
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheStatistics.h

    r218024 r220267  
    4444class Statistics {
    4545public:
    46     static std::unique_ptr<Statistics> open(const String& cachePath);
    47     explicit Statistics(const String& databasePath);
     46    static std::unique_ptr<Statistics> open(Cache&, const String& cachePath);
     47    explicit Statistics(Cache&, const String& databasePath);
    4848
    4949    void clear();
     
    7878    };
    7979
     80    Cache& m_cache;
     81
    8082    std::atomic<size_t> m_approximateEntryCount { 0 };
    8183
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheStorage.cpp

    r219249 r220267  
    11/*
    2  * Copyright (C) 2014-2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5454    WTF_MAKE_FAST_ALLOCATED;
    5555public:
    56     ReadOperation(const Key& key, RetrieveCompletionHandler&& completionHandler)
    57         : key(key)
     56    ReadOperation(Storage& storage, const Key& key, RetrieveCompletionHandler&& completionHandler)
     57        : storage(storage)
     58        , key(key)
    5859        , completionHandler(WTFMove(completionHandler))
    5960    { }
     
    6162    void cancel();
    6263    bool finish();
     64
     65    Ref<Storage> storage;
    6366
    6467    const Key key;
     
    100103    WTF_MAKE_FAST_ALLOCATED;
    101104public:
    102     WriteOperation(const Record& record, MappedBodyHandler&& mappedBodyHandler)
    103         : record(record)
     105    WriteOperation(Storage& storage, const Record& record, MappedBodyHandler&& mappedBodyHandler)
     106        : storage(storage)
     107        , record(record)
    104108        , mappedBodyHandler(WTFMove(mappedBodyHandler))
    105109    { }
    106    
     110    Ref<Storage> storage;
     111
    107112    const Record record;
    108113    const MappedBodyHandler mappedBodyHandler;
     
    114119    WTF_MAKE_FAST_ALLOCATED;
    115120public:
    116     TraverseOperation(const String& type, TraverseFlags flags, TraverseHandler&& handler)
    117         : type(type)
     121    TraverseOperation(Storage& storage, const String& type, TraverseFlags flags, TraverseHandler&& handler)
     122        : storage(storage)
     123        , type(type)
    118124        , flags(flags)
    119125        , handler(WTFMove(handler))
    120126    { }
     127    Ref<Storage> storage;
    121128
    122129    const String type;
     
    150157}
    151158
    152 std::unique_ptr<Storage> Storage::open(const String& cachePath, Mode mode)
     159RefPtr<Storage> Storage::open(const String& cachePath, Mode mode)
    153160{
    154161    ASSERT(RunLoop::isMain());
     
    159166    if (!salt)
    160167        return nullptr;
    161     return std::unique_ptr<Storage>(new Storage(cachePath, mode, *salt));
     168    return adoptRef(new Storage(cachePath, mode, *salt));
    162169}
    163170
     
    227234Storage::~Storage()
    228235{
     236    ASSERT(RunLoop::isMain());
     237    ASSERT(m_activeReadOperations.isEmpty());
     238    ASSERT(m_activeWriteOperations.isEmpty());
     239    ASSERT(m_activeTraverseOperations.isEmpty());
     240    ASSERT(!m_synchronizationInProgress);
     241    ASSERT(!m_shrinkInProgress);
    229242}
    230243
     
    259272    LOG(NetworkCacheStorage, "(NetworkProcess) synchronizing cache");
    260273
    261     backgroundIOQueue().dispatch([this] {
     274    backgroundIOQueue().dispatch([this, protectedThis = makeRef(*this)] () mutable {
    262275        auto recordFilter = std::make_unique<ContentsFilter>();
    263276        auto blobFilter = std::make_unique<ContentsFilter>();
     
    310323
    311324        LOG(NetworkCacheStorage, "(NetworkProcess) cache synchronization completed size=%zu count=%u", recordsSize, count);
     325
     326        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis)] { });
    312327    });
    313328}
     
    555570    removeFromPendingWriteOperations(key);
    556571
    557     serialBackgroundIOQueue().dispatch([this, key] {
     572    serialBackgroundIOQueue().dispatch([this, protectedThis = makeRef(*this), key] () mutable {
    558573        deleteFiles(key);
     574        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis)] { });
    559575    });
    560576}
     
    574590    }
    575591
    576     serialBackgroundIOQueue().dispatch([this, keysToRemove = WTFMove(keysToRemove), completionHandler = WTFMove(completionHandler)] () mutable {
     592    serialBackgroundIOQueue().dispatch([this, protectedThis = makeRef(*this), keysToRemove = WTFMove(keysToRemove), completionHandler = WTFMove(completionHandler)] () mutable {
    577593        for (auto& key : keysToRemove)
    578594            deleteFiles(key);
    579595
    580         if (completionHandler)
    581             RunLoop::main().dispatch(WTFMove(completionHandler));
     596        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)] {
     597            if (completionHandler)
     598                completionHandler();
     599        });
    582600    });
    583601}
     
    806824        return;
    807825
    808     auto readOperation = std::make_unique<ReadOperation>(key, WTFMove(completionHandler));
     826    auto readOperation = std::make_unique<ReadOperation>(*this, key, WTFMove(completionHandler));
    809827    m_pendingReadOperationsByPriority[priority].prepend(WTFMove(readOperation));
    810828    dispatchPendingReadOperations();
     
    819837        return;
    820838
    821     auto writeOperation = std::make_unique<WriteOperation>(record, WTFMove(mappedBodyHandler));
     839    auto writeOperation = std::make_unique<WriteOperation>(*this, record, WTFMove(mappedBodyHandler));
    822840    m_pendingWriteOperations.prepend(WTFMove(writeOperation));
    823841
     
    841859    // Avoid non-thread safe Function copies.
    842860
    843     auto traverseOperationPtr = std::make_unique<TraverseOperation>(type, flags, WTFMove(traverseHandler));
     861    auto traverseOperationPtr = std::make_unique<TraverseOperation>(*this, type, flags, WTFMove(traverseHandler));
    844862    auto& traverseOperation = *traverseOperationPtr;
    845863    m_activeTraverseOperations.add(WTFMove(traverseOperationPtr));
     
    937955    m_approximateRecordsSize = 0;
    938956
    939     ioQueue().dispatch([this, modifiedSinceTime, completionHandler = WTFMove(completionHandler), type = type.isolatedCopy()] () mutable {
     957    ioQueue().dispatch([this, protectedThis = makeRef(*this), modifiedSinceTime, completionHandler = WTFMove(completionHandler), type = type.isolatedCopy()] () mutable {
    940958        auto recordsPath = this->recordsPath();
    941959        traverseRecordsFiles(recordsPath, type, [modifiedSinceTime](const String& fileName, const String& hashString, const String& type, bool isBlob, const String& recordDirectoryPath) {
     
    954972        m_blobStorage.synchronize();
    955973
    956         if (completionHandler) {
    957             RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
     974        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)] {
     975            if (completionHandler)
    958976                completionHandler();
    959             });
    960         }
     977        });
    961978    });
    962979}
     
    10201037    LOG(NetworkCacheStorage, "(NetworkProcess) shrinking cache approximateSize=%zu capacity=%zu", approximateSize(), m_capacity);
    10211038
    1022     backgroundIOQueue().dispatch([this] {
     1039    backgroundIOQueue().dispatch([this, protectedThis = makeRef(*this)] () mutable {
    10231040        auto recordsPath = this->recordsPath();
    10241041        String anyType;
     
    10441061        });
    10451062
    1046         RunLoop::main().dispatch([this] {
     1063        RunLoop::main().dispatch([this, protectedThis = WTFMove(protectedThis)] {
    10471064            m_shrinkInProgress = false;
    10481065            // We could synchronize during the shrink traversal. However this is fast and it is better to have just one code path.
     
    10561073void Storage::deleteOldVersions()
    10571074{
    1058     backgroundIOQueue().dispatch([this] {
     1075    backgroundIOQueue().dispatch([this, protectedThis = makeRef(*this)] () mutable {
    10591076        auto cachePath = basePath();
    10601077        traverseDirectory(cachePath, [&cachePath](const String& subdirName, DirectoryEntryType type) {
     
    10801097            deleteDirectoryRecursively(oldVersionPath);
    10811098        });
     1099
     1100        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis)] { });
    10821101    });
    10831102}
  • trunk/Source/WebKit/NetworkProcess/cache/NetworkCacheStorage.h

    r219249 r220267  
    11/*
    2  * Copyright (C) 2014-2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2424 */
    2525
    26 #ifndef NetworkCacheStorage_h
    27 #define NetworkCacheStorage_h
     26#pragma once
    2827
    2928#if ENABLE(NETWORK_CACHE)
     
    4645class IOChannel;
    4746
    48 class Storage {
    49     WTF_MAKE_NONCOPYABLE(Storage);
     47class Storage : public ThreadSafeRefCounted<Storage> {
    5048public:
    5149    enum class Mode { Normal, Testing };
    52     static std::unique_ptr<Storage> open(const String& cachePath, Mode);
     50    static RefPtr<Storage> open(const String& cachePath, Mode);
    5351
    5452    struct Record {
     
    194192}
    195193#endif
    196 #endif
  • trunk/Source/WebKit/NetworkProcess/cocoa/NetworkProcessCocoa.mm

    r220243 r220267  
    8585    NetworkSessionCocoa::setSourceApplicationSecondaryIdentifier(parameters.sourceApplicationSecondaryIdentifier);
    8686    NetworkSessionCocoa::setAllowsCellularAccess(parameters.allowsCellularAccess);
     87    NetworkSessionCocoa::setUsesNetworkCache(parameters.shouldEnableNetworkCache);
    8788#if PLATFORM(IOS)
    8889    NetworkSessionCocoa::setCTDataConnectionServiceType(parameters.ctDataConnectionServiceType);
     
    109110#if ENABLE(NETWORK_CACHE)
    110111        if (parameters.shouldEnableNetworkCache) {
    111             OptionSet<NetworkCache::Cache::Option> cacheOptions;
     112            OptionSet<NetworkCache::Cache::Option> cacheOptions { NetworkCache::Cache::Option::RegisterNotify };
    112113            if (parameters.shouldEnableNetworkCacheEfficacyLogging)
    113114                cacheOptions |= NetworkCache::Cache::Option::EfficacyLogging;
     
    118119                cacheOptions |= NetworkCache::Cache::Option::SpeculativeRevalidation;
    119120#endif
    120             if (NetworkCache::singleton().initialize(m_diskCacheDirectory, cacheOptions)) {
     121            m_cache = NetworkCache::Cache::open(m_diskCacheDirectory, cacheOptions);
     122
     123            if (m_cache) {
     124                // Disable NSURLCache.
    121125                auto urlCache(adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]));
    122126                [NSURLCache setSharedURLCache:urlCache.get()];
     
    188192
    189193#if ENABLE(NETWORK_CACHE)
    190     auto group = m_clearCacheDispatchGroup;
    191     dispatch_group_async(group, dispatch_get_main_queue(), BlockPtr<void()>::fromCallable([group, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
    192         NetworkCache::singleton().clear(modifiedSince, [group, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
    193             // FIXME: Probably not necessary.
    194             clearNSURLCache(group, modifiedSince, WTFMove(completionHandler));
    195         });
    196     }).get());
    197 #else
     194    if (auto* cache = NetworkProcess::singleton().cache()) {
     195        auto group = m_clearCacheDispatchGroup;
     196        dispatch_group_async(group, dispatch_get_main_queue(), BlockPtr<void()>::fromCallable([cache, group, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
     197            cache->clear(modifiedSince, [group, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
     198                // FIXME: Probably not necessary.
     199                clearNSURLCache(group, modifiedSince, WTFMove(completionHandler));
     200            });
     201        }).get());
     202        return;
     203    }
     204#endif
    198205    clearNSURLCache(m_clearCacheDispatchGroup, modifiedSince, WTFMove(completionHandler));
    199 #endif
    200206}
    201207
  • trunk/Source/WebKit/NetworkProcess/cocoa/NetworkSessionCocoa.h

    r213747 r220267  
    5353    static void setSourceApplicationSecondaryIdentifier(const String&);
    5454    static void setAllowsCellularAccess(bool);
     55    static void setUsesNetworkCache(bool);
    5556#if PLATFORM(IOS)
    5657    static void setCTDataConnectionServiceType(const String&);
  • trunk/Source/WebKit/NetworkProcess/cocoa/NetworkSessionCocoa.mm

    r220243 r220267  
    3434#import "LegacyCustomProtocolManager.h"
    3535#import "Logging.h"
    36 #import "NetworkCache.h"
    3736#import "NetworkLoad.h"
    3837#import "NetworkProcess.h"
     
    450449   
    451450static bool allowsCellularAccess { true };
     451static bool usesNetworkCache { false };
    452452static LegacyCustomProtocolManager* legacyCustomProtocolManager;
    453453
     
    521521}
    522522
     523void NetworkSessionCocoa::setUsesNetworkCache(bool value)
     524{
     525    usesNetworkCache = value;
     526}
     527
    523528#if PLATFORM(IOS)
    524529void NetworkSessionCocoa::setCTDataConnectionServiceType(const String& type)
     
    554559    if (!allowsCellularAccess)
    555560        configuration.allowsCellularAccess = NO;
    556    
    557     if (NetworkCache::singleton().isEnabled())
     561
     562    if (usesNetworkCache)
    558563        configuration.URLCache = nil;
    559    
     564
    560565    if (auto& data = globalSourceApplicationAuditTokenData())
    561566        configuration._sourceApplicationAuditTokenData = (NSData *)data.get();
  • trunk/Source/WebKit/NetworkProcess/ios/NetworkProcessIOS.mm

    r220243 r220267  
    8080        return;
    8181#if ENABLE(NETWORK_CACHE)
    82     NetworkCache::singleton().clear();
     82    if (m_cache)
     83        m_cache->clear();
    8384#endif
    8485}
  • trunk/Source/WebKit/NetworkProcess/soup/NetworkProcessSoup.cpp

    r218985 r220267  
    113113    SoupNetworkSession::clearOldSoupCache(WebCore::directoryName(m_diskCacheDirectory));
    114114
    115     OptionSet<NetworkCache::Cache::Option> cacheOptions;
     115    OptionSet<NetworkCache::Cache::Option> cacheOptions { NetworkCache::Cache::Option::RegisterNotify };
    116116    if (parameters.shouldEnableNetworkCacheEfficacyLogging)
    117117        cacheOptions |= NetworkCache::Cache::Option::EfficacyLogging;
     
    121121#endif
    122122
    123     NetworkCache::singleton().initialize(m_diskCacheDirectory, cacheOptions);
     123    m_cache = NetworkCache::Cache::open(m_diskCacheDirectory, cacheOptions);
    124124
    125125    if (!parameters.cookiePersistentStoragePath.isEmpty()) {
     
    159159void NetworkProcess::clearDiskCache(std::chrono::system_clock::time_point modifiedSince, Function<void ()>&& completionHandler)
    160160{
    161     NetworkCache::singleton().clear(modifiedSince, WTFMove(completionHandler));
     161    if (!m_cache)
     162        return;
     163    m_cache->clear(modifiedSince, WTFMove(completionHandler));
    162164}
    163165
Note: See TracChangeset for help on using the changeset viewer.