Haio 0.2.X
Homebrew Asset IO/CDN
Loading...
Searching...
No Matches
cache.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <haio_cache.hpp>
4
5#include <boost/asio/any_io_executor.hpp>
6#include <boost/asio/awaitable.hpp>
7
8#include <chrono>
9#include <map>
10#include <memory>
11#include <string>
12
13/** the pieces the cache is made of, none of which anything outside it needs */
15
16/**
17 * one producer per key, however many callers ask at once.
18 *
19 * it knows nothing about caching: a burst on a key reaches the producer once whether
20 * or not the answer is kept afterwards, which is why turning the cache off does not
21 * turn an amplifier back on.
22 */
24public:
25 using Producer = std::function<boost::asio::awaitable<Result<CacheEntry>>()>;
26
27 explicit SingleFlight(boost::asio::any_io_executor executor);
28
29 /** runs the producer, or waits for whoever is already running it for this key */
30 boost::asio::awaitable<Result<CacheEntry>> run(const std::string& key, const Producer& produce);
31
32private:
33 struct Pending;
34 boost::asio::any_io_executor executor_;
35 std::map<std::string, std::shared_ptr<Pending>> inFlight_;
36};
37
38/**
39 * how many entries one address may create per window.
40 *
41 * the limit is on creating, never on reading: what it answers is one caller filling
42 * the cache with keys nobody else wants and evicting everyone else on the way.
43 */
45public:
46 ClientQuota(size_t perWindow, std::chrono::seconds window);
47
48 bool mayStore(const std::string& client);
49
50private:
51 struct Window {
52 size_t created = 0;
53 std::chrono::steady_clock::time_point resets;
54 };
55
56 static constexpr size_t clientsBeforePrune = 10000;
57 size_t perWindow_;
58 std::chrono::seconds window_;
59 std::map<std::string, Window> seen_;
60};
61
62}
bool mayStore(const std::string &client)
Definition quota.cpp:16
ClientQuota(size_t perWindow, std::chrono::seconds window)
Definition quota.cpp:7
SingleFlight(boost::asio::any_io_executor executor)
boost::asio::awaitable< Result< CacheEntry > > run(const std::string &key, const Producer &produce)
std::function< boost::asio::awaitable< Result< CacheEntry > >()> Producer
Definition cache.hpp:25