ladybird/Services/RequestServer/Cache/DiskCache.h
Timothy Flynn b2c112c41a LibWebView+RequestServer: Add a simple test mode for the HTTP disk cache
This mode allows us to test the HTTP disk cache with two mechanisms:

1. If RequestServer is launched with --http-disk-cache-mode=testing, it
   will cache requests with a X-Ladybird-Enable-Disk-Cache header.

2. In test mode, RS will include a X-Ladybird-Disk-Cache-Status response
   header indicating how the response was handled by the cache. There is
   no standard way for a web request to know what happened with respect
   to the disk cache, so this fills that hole for testing.

This mode is not exposed to users.
2025-11-20 09:33:49 +01:00

66 lines
1.8 KiB
C++

/*
* Copyright (c) 2025, Tim Flynn <trflynn89@ladybird.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Error.h>
#include <AK/LexicalPath.h>
#include <AK/Optional.h>
#include <AK/StringView.h>
#include <AK/Time.h>
#include <AK/Types.h>
#include <LibDatabase/Database.h>
#include <LibURL/Forward.h>
#include <RequestServer/Cache/CacheEntry.h>
#include <RequestServer/Cache/CacheIndex.h>
namespace RequestServer {
class DiskCache {
public:
enum class Mode {
Normal,
// In test mode, we only enable caching of responses on a per-request basis, signified by a request header. The
// response headers will include some status on how the request was handled.
Testing,
};
static ErrorOr<DiskCache> create(Mode);
Mode mode() const { return m_mode; }
struct CacheHasOpenEntry { };
Variant<Optional<CacheEntryWriter&>, CacheHasOpenEntry> create_entry(Request&);
Variant<Optional<CacheEntryReader&>, CacheHasOpenEntry> open_entry(Request&);
Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since) const;
void remove_entries_accessed_since(UnixDateTime since);
LexicalPath const& cache_directory() { return m_cache_directory; }
void cache_entry_closed(Badge<CacheEntry>, CacheEntry const&);
private:
DiskCache(Mode, NonnullRefPtr<Database::Database>, LexicalPath cache_directory, CacheIndex);
enum class CheckReaderEntries {
No,
Yes,
};
bool check_if_cache_has_open_entry(Request&, u64 cache_key, CheckReaderEntries);
Mode m_mode;
NonnullRefPtr<Database::Database> m_database;
HashMap<u64, Vector<NonnullOwnPtr<CacheEntry>, 1>> m_open_cache_entries;
HashMap<u64, Vector<WeakPtr<Request>, 1>> m_requests_waiting_completion;
LexicalPath m_cache_directory;
CacheIndex m_index;
};
}