Files
palemoon27/netwerk/cache2/CacheStorageService.h
T
roytam1 fe3519e975 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1257611 - Fix wrong CondVar::Wait() and Monitor::Wait() usage in netwerk/cache2, r=honzab (54f1a79f43)
- Bug 1239687 - Leak invalid/doomed file handles immediately after HTTP cache shutdown. r=michal (a20bcf662b)
- Bug 996836 - Merge CLOSE and WRITE priority in cache2 I/O thread. r=michal (8b0af50593)
- Bug 1265243 - Do not initialize CacheObserver in the child process, r=honzab (87f69529d2)
- Bug 1247432 - Don't do any unnecessary I/O in cache2 after shutdown. r=michal (7c5a2b89ac)
- Bug 1220272 - Fix signalling in HTTP cache test code suspender. r=michal (293a16731d)
- Bug 1160368 - Part 2: Clean up some cruft in nsCookie.h from PRBool/bool conversions. r=jdm (aa873f2dcc)
- Bug 1160368 - Part 5: Clean up some confusing browser_storage_listings.js checks. r=jdm (b27f5930a9)
- Bug 866380 - Null check for amlogic libc implementation. r=valentin (c3a487af9c)
- Bug 1257320 - Disable C4577 to unblock compilation on VS2015; r=mayhemer (2f800ca85c)
- Bug 1229726 - fix the data copy from sockaddr to NetAddr on OSX/FreeBSD. r=mcmanus. (fde11e004e)
- Bug 1241368 - provide JS implemented MDNS service as a fallback. r=nwgh,nalexander. (afe1445eb8)
- Bug 571126: Remove NECKO_SEPARATE_STACKS support, r=jduell (fb5b87bb3a)
- Bug 1057689 - Add xpcshell test checking correct notifications and app-offline state r=jduell (89946b44ba)
- Bug 1259459 - h2 0 length options puts end-stream on headers r=hurley (618480a609)
- Bug 1234251 - Remove HttpChannelChild::mSynthesizedResponseHead; r=jdm (20981affea)
- Bug 904559 - Veto redirect when target channel doesn't implement nsIParentRedirectingChannel. r=jduell (b3da2fae91)
- Bug 1261784 Make sure InterceptedChannel body streams are always closed. r=jdm (cd50b1a52b)
- Bug 1224508 - Use URI path without reference as the callback key. r=valentin. (b8a953f23a)
- Bug 1226760 - ViewSource doesn't work for packaged app resources r=mcmanus (ec9b0297de)
- Bug 1254061 - Rewrite nsHttp::ParseInt64 using strtoll r=mcmanus (2125b8ae6f)
- Bug 1241565 - nsIHttpChannelInternal should be a builtinclass, r=honzab.moz (d24da6a95a)
- Bug 1252386 - Removed debugging printf,r=me (c5d89f353c)
- bug 277813 - autogenerated expires needs max r=mayhemer (6aa7c255a5)
- Bug 1225384 - Change how the default resource "host names" are handled. r=michal (868732baab)
- Bug 719905: Fix resolution of resource: URLs containing : and / characters. r=valentin (f60f4baacf)
- Bug 1195173 - Convert ExtensionProtocolHandler to use channel->Open2() (r=maglione) (063f5d5d10)
- Bug 1226909 followup to fix bustage. Make sure that the channel returned by NS_NewChannel doesn't have a loadinfo that indicates that the channel has already been opened (42ebe0f44e)
- Bug 241698 - Fixed init and use of nsDirIndex::mLastModified (-1LL) + built in nullptr checks where they were missing. r=dragana (e9c2277a3d)
- Bug 1261318 - make sure brotli context is created in onstoprequest r=bagder (6646fed64d)
- Bug 1212223 - Update |bufLen| as well when we probed the multipart preamble. r=valentin. (ec878c5b0f)
- Bug 1259561: Increase CRAZY_COORD (threshold for debug build layout warnings) by an order of magnitude. r=mats (c05c16dd85)
- Bug 1261698. Make ReparentFrameViewTo return void because it always returns NS_OK. r=mats (e806d6abcb)
- Bug 1261698. Remove comment that is not relevant in nsContainerFrame.cpp. (f570189d15)
- Bug 1261698. Don't descend into child frames looking for views in ReparentFrameViewTo if the frame doesn't have the NS_FRAME_HAS_CHILD_WITH_VIEW bit set. r=mats (0d42befd46)
- Bug 1265154 - Fix compile error in MSVC 2013 caused by ArrayLength; r=heycam (1c962f2840)
- Bug 1260351 - Image: Enable ConvolveVertically/Horizontally in LS3 MMI. r=tnikkel (576b6bbdb3)
- Bug 1209780 (Part 1) - Mark DrawResult MOZ_MUST_USE. r=tn (e6c113bef2)
- Bug 1253753 - Remove unnecessary switch fallthrough to avoid -Wimplicit-fallthrough warning. r=karlt (96bd93fc5c)
- bug 1260178 null check pattern from -unico-border-gradient r=acomminos (f63c9c7ffb)
- Bug 1247796. Use keyboardFocusIndicatorColor for ActiveBorder system color keyword. r=mstange (7ed133de97)
- Bug 1248675 - Update the cached mBounds in nsChildView when its backing scale factor (display DPI) changes. r=mstange (8197274118)
- Bug 1256576 - Make sure texture is (re)initialized if the size changed. r=snorp (2c56790ca9)
- Bug 1242449 - Fix confusion among CSS, desktop and device pixel units in nsXULWindow position/size and window staggering so as to work consistently across mixed resolution displays. r=emk (f73d2fd41d)
- Bug 1255645 - Ensure nsXULWindow constrains the window to the bounds of its screen after applying intrinsic sizing (if appropriate), by re-doing positioning after the window has been sized properly. r=emk (e87e0cea81)
- Bug 1259492 - Ensure window position is constrained to the screen after it has been sized properly in nsXULWindow::OnChromeLoaded. r=emk (7cf599b39b)
- Bug 1832708 - Disable std::__throw_* wrapping on libc++ >= 14.0. r=firefox-build-system-reviewers,andi (29e0cc9319)
2024-08-09 14:38:26 +08:00

409 lines
12 KiB
C++

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef CacheStorageService__h__
#define CacheStorageService__h__
#include "nsICacheStorageService.h"
#include "nsIMemoryReporter.h"
#include "nsITimer.h"
#include "nsICacheTesting.h"
#include "nsClassHashtable.h"
#include "nsDataHashtable.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "nsProxyRelease.h"
#include "mozilla/Monitor.h"
#include "mozilla/Mutex.h"
#include "mozilla/Atomics.h"
#include "mozilla/TimeStamp.h"
#include "nsTArray.h"
class nsIURI;
class nsICacheEntryDoomCallback;
class nsICacheStorageVisitor;
class nsIRunnable;
class nsIThread;
class nsIEventTarget;
namespace mozilla {
namespace net {
class CacheStorageService;
class CacheStorage;
class CacheEntry;
class CacheEntryHandle;
class CacheMemoryConsumer
{
private:
friend class CacheStorageService;
uint32_t mReportedMemoryConsumption : 30;
uint32_t mFlags : 2;
private:
CacheMemoryConsumer() = delete;
protected:
enum {
// No special treatment, reports always to the disk-entries pool.
NORMAL = 0,
// This consumer is belonging to a memory-only cache entry, used to decide
// which of the two disk and memory pools count this consumption at.
MEMORY_ONLY = 1 << 0,
// Prevent reports of this consumer at all, used for disk data chunks since
// we throw them away as soon as the entry is not used by any consumer and
// don't want to make them wipe the whole pool out during their short life.
DONT_REPORT = 1 << 1
};
explicit CacheMemoryConsumer(uint32_t aFlags);
~CacheMemoryConsumer() { DoMemoryReport(0); }
void DoMemoryReport(uint32_t aCurrentSize);
};
class CacheStorageService final : public nsICacheStorageService
, public nsIMemoryReporter
, public nsITimerCallback
, public nsICacheTesting
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSICACHESTORAGESERVICE
NS_DECL_NSIMEMORYREPORTER
NS_DECL_NSITIMERCALLBACK
NS_DECL_NSICACHETESTING
CacheStorageService();
void Shutdown();
void DropPrivateBrowsingEntries();
// Takes care of deleting any pending trashes for both cache1 and cache2
// as well as the cache directory of an inactive cache version when requested.
static void CleaupCacheDirectories(uint32_t aVersion, uint32_t aActive);
static CacheStorageService* Self() { return sSelf; }
static nsISupports* SelfISupports() { return static_cast<nsICacheStorageService*>(Self()); }
nsresult Dispatch(nsIRunnable* aEvent);
static bool IsRunning() { return sSelf && !sSelf->mShutdown; }
static bool IsOnManagementThread();
already_AddRefed<nsIEventTarget> Thread() const;
mozilla::Mutex& Lock() { return mLock; }
// Tracks entries that may be forced valid in a pruned hashtable.
nsDataHashtable<nsCStringHashKey, TimeStamp> mForcedValidEntries;
void ForcedValidEntriesPrune(TimeStamp &now);
// Helper thread-safe interface to pass entry info, only difference from
// nsICacheStorageVisitor is that instead of nsIURI only the uri spec is
// passed.
class EntryInfoCallback {
public:
virtual void OnEntryInfo(const nsACString & aURISpec, const nsACString & aIdEnhance,
int64_t aDataSize, int32_t aFetchCount,
uint32_t aLastModifiedTime, uint32_t aExpirationTime,
bool aPinned) = 0;
};
// Invokes OnEntryInfo for the given aEntry, synchronously.
static void GetCacheEntryInfo(CacheEntry* aEntry, EntryInfoCallback *aVisitor);
// Memory reporting
size_t SizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
size_t SizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf)
private:
virtual ~CacheStorageService();
void ShutdownBackground();
private:
// The following methods may only be called on the management
// thread.
friend class CacheEntry;
/**
* Registers the entry in management ordered arrays, a mechanism
* helping with weighted purge of entries.
* Management arrays keep hard reference to the entry. Entry is
* responsible to remove it self or the service is responsible to
* remove the entry when it's no longer needed.
*/
void RegisterEntry(CacheEntry* aEntry);
/**
* Deregisters the entry from management arrays. References are
* then released.
*/
void UnregisterEntry(CacheEntry* aEntry);
/**
* Removes the entry from the related entry hash table, if still present.
*/
bool RemoveEntry(CacheEntry* aEntry, bool aOnlyUnreferenced = false);
/**
* Tells the storage service whether this entry is only to be stored in
* memory.
*/
void RecordMemoryOnlyEntry(CacheEntry* aEntry,
bool aOnlyInMemory,
bool aOverwrite);
/**
* Sets a cache entry valid (overrides the default loading behavior by loading
* directly from cache) for the given number of seconds
* See nsICacheEntry.idl for more details
*/
void ForceEntryValidFor(nsACString const &aContextKey,
nsACString const &aEntryKey,
uint32_t aSecondsToTheFuture);
/**
* Remove the validity info
*/
void RemoveEntryForceValid(nsACString const &aContextKey,
nsACString const &aEntryKey);
/**
* Retrieves the status of the cache entry to see if it has been forced valid
* (so it will loaded directly from cache without further validation)
*/
bool IsForcedValidEntry(nsACString const &aContextKey,
nsACString const &aEntryKey);
private:
friend class CacheIndex;
/**
* CacheIndex uses this to prevent a cache entry from being prememptively
* thrown away when forced valid
* See nsICacheEntry.idl for more details
*/
bool IsForcedValidEntry(nsACString const &aEntryKeyWithContext);
private:
// Following methods are thread safe to call.
friend class CacheStorage;
/**
* Get, or create when not existing and demanded, an entry for the storage
* and uri+id extension.
*/
nsresult AddStorageEntry(CacheStorage const* aStorage,
nsIURI* aURI,
const nsACString & aIdExtension,
bool aReplace,
CacheEntryHandle** aResult);
/**
* Check existance of an entry. This may throw NS_ERROR_NOT_AVAILABLE
* when the information cannot be obtained synchronously w/o blocking.
*/
nsresult CheckStorageEntry(CacheStorage const* aStorage,
nsIURI* aURI,
const nsACString & aIdExtension,
bool* aResult);
/**
* Removes the entry from the related entry hash table, if still present
* and returns it.
*/
nsresult DoomStorageEntry(CacheStorage const* aStorage,
nsIURI* aURI,
const nsACString & aIdExtension,
nsICacheEntryDoomCallback* aCallback);
/**
* Removes and returns entry table for the storage.
*/
nsresult DoomStorageEntries(CacheStorage const* aStorage,
nsICacheEntryDoomCallback* aCallback);
/**
* Walk all entiries beloging to the storage.
*/
nsresult WalkStorageEntries(CacheStorage const* aStorage,
bool aVisitEntries,
nsICacheStorageVisitor* aVisitor);
private:
friend class CacheFileIOManager;
/**
* CacheFileIOManager uses this method to notify CacheStorageService that
* an active entry was removed. This method is called even if the entry
* removal was originated by CacheStorageService.
*/
void CacheFileDoomed(nsILoadContextInfo* aLoadContextInfo,
const nsACString & aIdExtension,
const nsACString & aURISpec);
/**
* Tries to find an existing entry in the hashtables and synchronously call
* OnCacheEntryInfo of the aVisitor callback when found.
* @retuns
* true, when the entry has been found that also implies the callbacks has
* beem invoked
* false, when an entry has not been found
*/
bool GetCacheEntryInfo(nsILoadContextInfo* aLoadContextInfo,
const nsACString & aIdExtension,
const nsACString & aURISpec,
EntryInfoCallback *aCallback);
private:
friend class CacheMemoryConsumer;
/**
* When memory consumption of this entry radically changes, this method
* is called to reflect the size of allocated memory. This call may purge
* unspecified number of entries from memory (but not from disk).
*/
void OnMemoryConsumptionChange(CacheMemoryConsumer* aConsumer,
uint32_t aCurrentMemoryConsumption);
/**
* If not already pending, it schedules mPurgeTimer that fires after 1 second
* and dispatches PurgeOverMemoryLimit().
*/
void SchedulePurgeOverMemoryLimit();
/**
* Called on the management thread, removes all expired and then least used
* entries from the memory, first from the disk pool and then from the memory
* pool.
*/
void PurgeOverMemoryLimit();
private:
nsresult DoomStorageEntries(nsCSubstring const& aContextKey,
nsILoadContextInfo* aContext,
bool aDiskStorage,
bool aPin,
nsICacheEntryDoomCallback* aCallback);
nsresult AddStorageEntry(nsCSubstring const& aContextKey,
nsIURI* aURI,
const nsACString & aIdExtension,
bool aWriteToDisk,
bool aSkipSizeCheck,
bool aPin,
bool aReplace,
CacheEntryHandle** aResult);
static CacheStorageService* sSelf;
mozilla::Mutex mLock;
mozilla::Mutex mForcedValidEntriesLock;
bool mShutdown;
// Accessible only on the service thread
class MemoryPool
{
public:
enum EType
{
DISK,
MEMORY,
} mType;
explicit MemoryPool(EType aType);
~MemoryPool();
nsTArray<RefPtr<CacheEntry> > mFrecencyArray;
nsTArray<RefPtr<CacheEntry> > mExpirationArray;
Atomic<uint32_t, Relaxed> mMemorySize;
bool OnMemoryConsumptionChange(uint32_t aSavedMemorySize,
uint32_t aCurrentMemoryConsumption);
/**
* Purges entries from memory based on the frecency ordered array.
*/
void PurgeOverMemoryLimit();
void PurgeExpired();
void PurgeByFrecency(bool &aFrecencyNeedsSort, uint32_t aWhat);
void PurgeAll(uint32_t aWhat);
private:
uint32_t Limit() const;
MemoryPool() = delete;
};
MemoryPool mDiskPool;
MemoryPool mMemoryPool;
TimeStamp mLastPurgeTime;
MemoryPool& Pool(bool aUsingDisk)
{
return aUsingDisk ? mDiskPool : mMemoryPool;
}
MemoryPool const& Pool(bool aUsingDisk) const
{
return aUsingDisk ? mDiskPool : mMemoryPool;
}
nsCOMPtr<nsITimer> mPurgeTimer;
class PurgeFromMemoryRunnable : public nsRunnable
{
public:
PurgeFromMemoryRunnable(CacheStorageService* aService, uint32_t aWhat)
: mService(aService), mWhat(aWhat) { }
private:
virtual ~PurgeFromMemoryRunnable() { }
NS_IMETHOD Run() override;
RefPtr<CacheStorageService> mService;
uint32_t mWhat;
};
// nsICacheTesting
class IOThreadSuspender : public nsRunnable
{
public:
IOThreadSuspender() : mMon("IOThreadSuspender"), mSignaled(false) { }
void Notify();
private:
virtual ~IOThreadSuspender() { }
NS_IMETHOD Run() override;
Monitor mMon;
bool mSignaled;
};
RefPtr<IOThreadSuspender> mActiveIOSuspender;
};
template<class T>
void ProxyRelease(nsCOMPtr<T> &object, nsIThread* thread)
{
NS_ProxyRelease(thread, object.forget());
}
template<class T>
void ProxyReleaseMainThread(nsCOMPtr<T> &object)
{
nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
ProxyRelease(object, mainThread);
}
} // namespace net
} // namespace mozilla
#define NS_CACHE_STORAGE_SERVICE_CID \
{ 0xea70b098, 0x5014, 0x4e21, \
{ 0xae, 0xe1, 0x75, 0xe6, 0xb2, 0xc4, 0xb8, 0xe0 } } \
#define NS_CACHE_STORAGE_SERVICE_CONTRACTID \
"@mozilla.org/netwerk/cache-storage-service;1"
#define NS_CACHE_STORAGE_SERVICE_CONTRACTID2 \
"@mozilla.org/network/cache-storage-service;1"
#endif