#ifndef CONTENT_BROWSER_CACHE_STORAGE_CACHE_STORAGE_CACHE_H_
#define CONTENT_BROWSER_CACHE_STORAGE_CACHE_STORAGE_CACHE_H_
#include <stdint.h>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "components/services/storage/public/cpp/buckets/bucket_locator.h"
#include "components/services/storage/public/cpp/quota_error_or.h"
#include "components/services/storage/public/mojom/cache_storage_control.mojom.h"
#include "content/browser/cache_storage/blob_storage_context_wrapper.h"
#include "content/browser/cache_storage/cache_storage_cache_handle.h"
#include "content/browser/cache_storage/cache_storage_handle.h"
#include "content/browser/cache_storage/cache_storage_scheduler_types.h"
#include "content/browser/cache_storage/scoped_writable_entry.h"
#include "content/common/content_export.h"
#include "net/base/completion_once_callback.h"
#include "net/base/io_buffer.h"
#include "net/disk_cache/disk_cache.h"
#include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h"
#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
namespace storage {
class QuotaManagerProxy;
}
namespace content {
class CacheStorageBlobToDiskCache;
class CacheStorageCacheEntryHandler;
class CacheStorageCacheObserver;
class CacheStorageScheduler;
class CacheStorage;
struct PutContext;
namespace proto {
class CacheMetadata;
}
namespace cache_storage_cache_unittest {
class TestCacheStorageCache;
class CacheStorageCacheTest;
}
class CONTENT_EXPORT CacheStorageCache {
public:
using CacheEntriesCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
std::vector<blink::mojom::CacheEntryPtr>)>;
using ErrorCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError)>;
using VerboseErrorCallback =
base::OnceCallback<void(blink::mojom::CacheStorageVerboseErrorPtr)>;
using BadMessageCallback = base::OnceCallback<void()>;
using ResponseCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
blink::mojom::FetchAPIResponsePtr)>;
using ResponsesCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
std::vector<blink::mojom::FetchAPIResponsePtr>)>;
using Requests = std::vector<blink::mojom::FetchAPIRequestPtr>;
using RequestsCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
std::unique_ptr<Requests>)>;
using SizeCallback = base::OnceCallback<void(int64_t)>;
using SizePaddingCallback = base::OnceCallback<void(int64_t, int64_t)>;
enum EntryIndex {
INDEX_INVALID = -1,
INDEX_HEADERS = 0,
INDEX_RESPONSE_BODY,
INDEX_SIDE_DATA
};
static std::unique_ptr<CacheStorageCache> CreateMemoryCache(
const storage::BucketLocator& bucket_locator,
storage::mojom::CacheStorageOwner owner,
const std::u16string& cache_name,
CacheStorage* cache_storage,
scoped_refptr<base::SequencedTaskRunner> scheduler_task_runner,
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy,
scoped_refptr<BlobStorageContextWrapper> blob_storage_context);
static std::unique_ptr<CacheStorageCache> CreatePersistentCache(
const storage::BucketLocator& bucket_locator,
storage::mojom::CacheStorageOwner owner,
const std::u16string& cache_name,
CacheStorage* cache_storage,
const base::FilePath& path,
scoped_refptr<base::SequencedTaskRunner> scheduler_task_runner,
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy,
scoped_refptr<BlobStorageContextWrapper> blob_storage_context,
int64_t cache_size,
int64_t cache_padding);
static int32_t GetResponsePaddingVersion();
void Match(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr match_options,
CacheStorageSchedulerPriority priority,
int64_t trace_id,
ResponseCallback callback);
void MatchAll(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr match_options,
int64_t trace_id,
ResponsesCallback callback);
void WriteSideData(ErrorCallback callback,
const GURL& url,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len);
void BatchOperation(std::vector<blink::mojom::BatchOperationPtr> operations,
int64_t trace_id,
VerboseErrorCallback callback,
BadMessageCallback bad_message_callback);
void BatchDidGetBucketSpaceRemaining(
std::vector<blink::mojom::BatchOperationPtr> operations,
int64_t trace_id,
VerboseErrorCallback callback,
BadMessageCallback bad_message_callback,
std::optional<std::string> message,
uint64_t space_required,
uint64_t side_data_size,
storage::QuotaErrorOr<int64_t> space_remaining);
void Keys(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr options,
int64_t trace_id,
RequestsCallback callback);
void Close(base::OnceClosure callback);
void Size(SizeCallback callback);
void GetSizeThenClose(SizeCallback callback);
void Put(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::FetchAPIResponsePtr response,
int64_t trace_id,
ErrorCallback callback);
void GetAllMatchedEntries(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr match_options,
int64_t trace_id,
CacheEntriesCallback callback);
enum class InitState { Unknown, Initializing, Initialized };
InitState GetInitState() const;
CacheStorageCache(const CacheStorageCache&) = delete;
CacheStorageCache& operator=(const CacheStorageCache&) = delete;
virtual ~CacheStorageCache();
base::FilePath path() const { return path_; }
std::u16string cache_name() const { return cache_name_; }
int64_t cache_size() const { return cache_size_; }
int64_t cache_padding() const { return cache_padding_; }
int64_t PaddedCacheSize() const;
void SetObserver(CacheStorageCacheObserver* observer);
static size_t EstimatedStructSize(
const blink::mojom::FetchAPIRequestPtr& request);
base::WeakPtr<CacheStorageCache> AsWeakPtr();
CacheStorageCacheHandle CreateHandle();
void AddHandleRef();
void DropHandleRef();
bool IsUnreferenced() const;
void SetSchedulerForTesting(std::unique_ptr<CacheStorageScheduler> scheduler);
static CacheStorageCache* From(const CacheStorageCacheHandle& handle) {
return static_cast<CacheStorageCache*>(handle.value());
}
private:
enum QueryCacheFlags {
QUERY_CACHE_REQUESTS = 0x1,
QUERY_CACHE_RESPONSES_WITH_BODIES = 0x2,
QUERY_CACHE_RESPONSES_NO_BODIES = 0x4,
QUERY_CACHE_ENTRIES = 0x8,
};
enum BackendState {
BACKEND_UNINITIALIZED,
BACKEND_OPEN,
BACKEND_CLOSED
};
friend class base::RefCounted<CacheStorageCache>;
friend class cache_storage_cache_unittest::TestCacheStorageCache;
friend class cache_storage_cache_unittest::CacheStorageCacheTest;
struct QueryCacheContext;
struct QueryCacheResult;
struct BatchInfo;
using QueryTypes = int32_t;
using QueryCacheResults = std::vector<QueryCacheResult>;
using QueryCacheCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
std::unique_ptr<QueryCacheResults>)>;
using Entries = std::vector<disk_cache::Entry*>;
using BlobToDiskCacheIDMap =
base::IDMap<std::unique_ptr<CacheStorageBlobToDiskCache>>;
CacheStorageCache(
const storage::BucketLocator& bucket_locator,
storage::mojom::CacheStorageOwner owner,
const std::u16string& cache_name,
const base::FilePath& path,
CacheStorage* cache_storage,
scoped_refptr<base::SequencedTaskRunner> scheduler_task_runner,
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy,
scoped_refptr<BlobStorageContextWrapper> blob_storage_context,
int64_t cache_size,
int64_t cache_padding);
void BatchDidOneOperation(BatchInfo& batch_status,
blink::mojom::CacheStorageError error);
void QueryCache(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr options,
QueryTypes query_types,
CacheStorageSchedulerPriority priority,
QueryCacheCallback callback);
void QueryCacheDidOpenFastPath(
std::unique_ptr<QueryCacheContext> query_cache_context,
disk_cache::EntryResult result);
void QueryCacheOpenNextEntry(
std::unique_ptr<QueryCacheContext> query_cache_context);
void QueryCacheFilterEntry(
std::unique_ptr<QueryCacheContext> query_cache_context,
disk_cache::EntryResult result);
void QueryCacheDidReadMetadata(
std::unique_ptr<QueryCacheContext> query_cache_context,
disk_cache::ScopedEntryPtr entry,
std::unique_ptr<proto::CacheMetadata> metadata);
void QueryCacheUpgradePadding(
std::unique_ptr<QueryCacheContext> query_cache_context,
disk_cache::ScopedEntryPtr entry,
std::unique_ptr<proto::CacheMetadata> metadata);
static bool QueryCacheResultCompare(const QueryCacheResult& lhs,
const QueryCacheResult& rhs);
static size_t EstimatedResponseSizeWithoutBlob(
const blink::mojom::FetchAPIResponse& response);
void MatchImpl(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr match_options,
int64_t trace_id,
CacheStorageSchedulerPriority priority,
ResponseCallback callback);
void MatchDidMatchAll(
ResponseCallback callback,
blink::mojom::CacheStorageError match_all_error,
std::vector<blink::mojom::FetchAPIResponsePtr> match_all_responses);
void MatchAllImpl(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr options,
int64_t trace_id,
CacheStorageSchedulerPriority priority,
ResponsesCallback callback);
void MatchAllDidQueryCache(
ResponsesCallback callback,
int64_t trace_id,
blink::mojom::CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results);
using WriteMetadataCallback =
base::OnceCallback<void(int exepected_bytes, int rv)>;
void WriteMetadata(disk_cache::Entry* entry,
const proto::CacheMetadata& metadata,
WriteMetadataCallback callback);
void WriteSideDataDidGetBucketSpaceRemaining(
ErrorCallback callback,
const GURL& url,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len,
storage::QuotaErrorOr<int64_t> space_remaining);
void WriteSideDataImpl(ErrorCallback callback,
const GURL& url,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len);
void WriteSideDataDidGetUsageAndQuota(
ErrorCallback callback,
const GURL& url,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len,
blink::mojom::QuotaStatusCode status_code,
int64_t usage,
int64_t quota);
void WriteSideDataDidOpenEntry(ErrorCallback callback,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len,
disk_cache::EntryResult result);
void WriteSideDataDidReadMetaData(
ErrorCallback callback,
base::Time expected_response_time,
int64_t trace_id,
scoped_refptr<net::IOBuffer> buffer,
int buf_len,
ScopedWritableEntry entry,
std::unique_ptr<proto::CacheMetadata> headers);
void WriteSideDataDidWrite(
ErrorCallback callback,
ScopedWritableEntry entry,
int expected_bytes,
std::unique_ptr<content::proto::CacheMetadata> metadata,
int64_t trace_id,
int rv);
void WriteSideDataDidWriteMetadata(ErrorCallback callback,
ScopedWritableEntry entry,
int64_t padding,
int64_t side_data_padding,
int expected_bytes,
int rv);
void WriteSideDataComplete(ErrorCallback callback,
ScopedWritableEntry entry,
int64_t padding,
int64_t side_data_padding,
blink::mojom::CacheStorageError error);
void Put(blink::mojom::BatchOperationPtr operation,
int64_t trace_id,
ErrorCallback callback);
void PutImpl(std::unique_ptr<PutContext> put_context);
void PutDidDeleteEntry(std::unique_ptr<PutContext> put_context,
blink::mojom::CacheStorageError error);
void PutDidGetUsageAndQuota(std::unique_ptr<PutContext> put_context,
blink::mojom::QuotaStatusCode status_code,
int64_t usage,
int64_t quota);
void PutDidCreateEntry(std::unique_ptr<PutContext> put_context,
disk_cache::EntryResult result);
void PutDidWriteHeaders(std::unique_ptr<PutContext> put_context,
int64_t padding,
int64_t side_data_padding,
int expected_bytes,
int rv);
void PutWriteBlobToCache(std::unique_ptr<PutContext> put_context,
int disk_cache_body_index);
void PutDidWriteBlobToCache(std::unique_ptr<PutContext> put_context,
BlobToDiskCacheIDMap::KeyType blob_to_cache_key,
int disk_cache_body_index,
ScopedWritableEntry entry,
bool success);
void PutWriteBlobToCacheComplete(std::unique_ptr<PutContext> put_context,
int disk_cache_body_index,
ScopedWritableEntry entry,
int rv);
void PutComplete(std::unique_ptr<PutContext> put_context,
blink::mojom::CacheStorageError error);
void UpdateCacheSize(base::OnceClosure callback);
void UpdateCacheSizeGotSize(CacheStorageCacheHandle,
base::OnceClosure callback,
int64_t current_cache_size);
void UpdateCacheSizeNotifiedStorageModified(base::OnceClosure callback);
void GetAllMatchedEntriesImpl(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr options,
int64_t trace_id,
CacheEntriesCallback callback);
void GetAllMatchedEntriesDidQueryCache(
int64_t trace_id,
CacheEntriesCallback callback,
blink::mojom::CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results);
void Delete(blink::mojom::BatchOperationPtr operation,
ErrorCallback callback);
void DeleteImpl(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr match_options,
ErrorCallback callback);
void DeleteDidQueryCache(
ErrorCallback callback,
blink::mojom::CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results);
void KeysImpl(blink::mojom::FetchAPIRequestPtr request,
blink::mojom::CacheQueryOptionsPtr options,
int64_t trace_id,
RequestsCallback callback);
void KeysDidQueryCache(
RequestsCallback callback,
int64_t trace_id,
blink::mojom::CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results);
void CloseImpl(base::OnceClosure callback);
void SizeImpl(SizeCallback callback);
void GetSizeThenCloseDidGetSize(SizeCallback callback, int64_t cache_size);
virtual void CreateBackend(ErrorCallback callback);
void CreateBackendDidCreate(ErrorCallback callback,
disk_cache::BackendResult result);
void CalculateCacheSizePadding(SizePaddingCallback callback);
void CalculateCacheSizePaddingGotSize(SizePaddingCallback callback,
int64_t cache_size);
void PaddingDidQueryCache(
SizePaddingCallback callback,
int64_t cache_size,
blink::mojom::CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results);
void CalculateCacheSize(net::Int64CompletionOnceCallback callback);
void InitBackend();
void InitDidCreateBackend(base::OnceClosure callback,
blink::mojom::CacheStorageError cache_create_error);
void InitGotCacheSize(base::OnceClosure callback,
blink::mojom::CacheStorageError cache_create_error,
int64_t cache_size);
void InitGotCacheSizeAndPadding(
base::OnceClosure callback,
blink::mojom::CacheStorageError cache_create_error,
int64_t cache_size,
int64_t cache_padding);
void DeleteBackendCompletedIO();
base::CheckedNumeric<uint64_t> CalculateRequiredSafeSpaceForPut(
const blink::mojom::BatchOperationPtr& operation);
base::CheckedNumeric<uint64_t> CalculateRequiredSafeSpaceForRequest(
const blink::mojom::FetchAPIRequestPtr& request);
base::CheckedNumeric<uint64_t> CalculateRequiredSafeSpaceForResponse(
const blink::mojom::FetchAPIResponsePtr& response);
template <typename... Args>
base::OnceCallback<void(Args...)> WrapCallbackWithHandle(
base::OnceCallback<void(Args...)> callback) {
return base::BindOnce(&CacheStorageCache::RunWithHandle<Args...>,
weak_ptr_factory_.GetWeakPtr(), CreateHandle(),
std::move(callback));
}
template <typename... Args>
void RunWithHandle(CacheStorageCacheHandle handle,
base::OnceCallback<void(Args...)> callback,
Args... args) {
std::move(callback).Run(std::forward<Args>(args)...);
}
std::unique_ptr<disk_cache::Backend> backend_;
const storage::BucketLocator bucket_locator_;
const storage::mojom::CacheStorageOwner owner_;
const std::u16string cache_name_;
const base::FilePath path_;
const raw_ptr<CacheStorage> cache_storage_;
CacheStorageHandle cache_storage_handle_;
const scoped_refptr<base::SequencedTaskRunner> scheduler_task_runner_;
const scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_;
BackendState backend_state_ = BACKEND_UNINITIALIZED;
std::unique_ptr<CacheStorageScheduler> scheduler_;
bool initializing_ = false;
int64_t cache_size_;
int64_t cache_padding_ = 0;
int64_t last_reported_size_ = 0;
size_t max_query_size_bytes_;
size_t handle_ref_count_ = 0;
int query_cache_recursive_depth_ = 0;
raw_ptr<CacheStorageCacheObserver> cache_observer_;
std::unique_ptr<CacheStorageCacheEntryHandler> cache_entry_handler_;
BlobToDiskCacheIDMap active_blob_to_disk_cache_writers_;
const bool memory_only_;
base::OnceClosure post_backend_closed_callback_;
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<CacheStorageCache> weak_ptr_factory_{this};
};
}
#endif