diff --git a/CMakeLists.txt b/CMakeLists.txt index b45f4ff..74c21c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -140,6 +140,7 @@ add_library(lootlocker_core STATIC src/core/config_obfuscation.cpp src/core/header_map.cpp src/core/request_id.cpp + src/core/rate_limiter.cpp src/core/executor.cpp src/core/client.cpp ) diff --git a/src/core/client.cpp b/src/core/client.cpp index 2836cb4..9ccb7af 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -77,8 +77,25 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } - m_impl->executor.reset(new core::Executor(config.queue, transport, m_impl->clock, logger, - m_impl->config_error)); + core::ExecutorSettings settings; + settings.queue = config.queue; + + // An invalid config means the policy was never validated, so it must not reach the + // limiter: a rejected 2-billion-second window would still derive 2 billion buckets and + // attempt a multi-gigabyte allocation during construction, which in a no-exceptions + // build terminates the client. The client is inert anyway, so a disabled limiter is + // exactly right. + settings.rate_limit = config.rate_limit; + if (!m_impl->config_error.Ok()) { + settings.rate_limit.enabled = false; + } + + settings.transport = transport; + settings.clock = &m_impl->clock; + settings.logger = logger; + settings.config_error = m_impl->config_error; + + m_impl->executor.reset(new core::Executor(settings)); } Client::~Client() = default; diff --git a/src/core/config.cpp b/src/core/config.cpp index 1767e02..d95bd10 100644 --- a/src/core/config.cpp +++ b/src/core/config.cpp @@ -221,6 +221,33 @@ Error ValidateConfig(const Config& config) return Invalid("rate_limit.moving_average_time_frames must be positive"); } + // The window must divide evenly into buckets. A non-divisible policy silently + // shortens the window - 60 s with 7 s buckets becomes an effective 56 s tripwire and + // a 168 s moving average - so the adopter gets a different rate limit than they + // asked for, with nothing to say so. + if (config.rate_limit.tripwire_window_seconds % config.rate_limit.seconds_per_bucket + != 0) { + return Invalid("rate_limit.tripwire_window_seconds must be a multiple of " + "seconds_per_bucket"); + } + + // The derived bucket count must be bounded, because it is an allocation. Without + // this, a large window with 1 s buckets asks for billions of buckets - gigabytes of + // atomics - and in a no-exceptions build that terminates the client during + // construction. + // + // The bound is generous: the defaults derive 36, and even a 1-hour window with 1 s + // buckets over 3 frames is 10,800. Anything past this is a typo rather than a policy. + const long long buckets_per_tripwire = + config.rate_limit.tripwire_window_seconds / config.rate_limit.seconds_per_bucket; + const long long bucket_count = + buckets_per_tripwire * config.rate_limit.moving_average_time_frames; + if (bucket_count > 100000) { + return Invalid("rate_limit settings derive " + std::to_string(bucket_count) + + " buckets, which exceeds the limit of 100000; raise " + "seconds_per_bucket or lower moving_average_time_frames"); + } + // The fraction must be finite and in (0, 1]. A NaN or an out-of-range value would // make PerBucketLimit() produce a nonsense threshold. const double f = config.rate_limit.moving_average_fraction; diff --git a/src/core/executor.cpp b/src/core/executor.cpp index b9f6657..2e95dfe 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -40,17 +40,10 @@ bool IsRetryableStatus(int status_code) } // namespace -Executor::Executor(const QueueConfig& config, std::weak_ptr transport, - Clock& clock, std::weak_ptr logger) - : m_config(config), m_transport(std::move(transport)), m_clock(clock), - m_logger(std::move(logger)) -{ -} - -Executor::Executor(const QueueConfig& config, std::weak_ptr transport, - Clock& clock, std::weak_ptr logger, Error config_error) - : m_config(config), m_config_error(std::move(config_error)), m_transport(std::move(transport)), - m_clock(clock), m_logger(std::move(logger)) +Executor::Executor(const ExecutorSettings& settings) + : m_config(settings.queue), m_config_error(settings.config_error), + m_transport(settings.transport), m_clock(*settings.clock), m_logger(settings.logger), + m_rate_limiter(settings.rate_limit, *settings.clock) { } @@ -352,6 +345,22 @@ bool Executor::Update() const std::int64_t now = m_clock.NowMs(); + // The executor is the one place that reads the clock, and it pushes the delta into every + // tickable component. A component that read the clock itself would advance only when + // someone happened to ask it something, which is how the limiter used to work. + // + // Initialisation is tracked separately from the timestamp. `Clock` only promises + // monotonic milliseconds, not a non-zero origin, so a clock that legitimately starts at 0 + // would otherwise leave `m_last_tick_ms` at 0 for ever and compute a delta of 0 every + // time - the limiter's buckets would never advance and held requests would stay blocked. + std::int64_t delta_ms = 0; + if (m_has_ticked) { + delta_ms = now - m_last_tick_ms; + } + m_has_ticked = true; + m_last_tick_ms = now; + m_rate_limiter.Tick(delta_ms); + std::vector handlers; std::vector completions; @@ -479,6 +488,20 @@ bool Executor::Update() break; } + // The client-side throttle (D25). A tripped request is **held, not dropped**: + // it stays queued and is promoted on a later `Update()` once the window clears. + // The caller sees nothing until then, because a rate limit is self-restraint, + // not an error. + // + // Checked here rather than at submit time, because the limiter counts requests + // that are actually sent. Counting at submit would throttle a caller for + // queueing work it never got to send. + if (!m_rate_limiter.CanAcquire()) { + // Nothing else can be promoted either: the limiter is a global gate, so + // breaking here is correct and avoids a pointless loop over the rest. + break; + } + const auto it = m_entries.find(id); if (it == m_entries.end()) { continue; @@ -518,6 +541,11 @@ bool Executor::Update() entry.transfer = transfer; entry.in_flight = true; + + // Recorded only now, after the transfer actually started. A `Start` that + // returned 0 sent nothing, so counting it would burn quota for a request that + // never left - and repeated failures could hold unrelated queued requests. + m_rate_limiter.Commit(); } } diff --git a/src/core/executor.h b/src/core/executor.h index f8836da..e0eb1d6 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -18,6 +18,7 @@ #include #include "clock.h" +#include "rate_limiter.h" #include #include @@ -60,15 +61,36 @@ struct Completion { using CompletionHandler = std::function; +// Everything the executor needs to be constructed. +// +// A struct rather than a parameter list, because the executor has five dependencies and +// three of them are optional. Three overloads existed to avoid naming the optional ones; +// with no users yet there is nothing to keep compatible, and one shape is easier to read +// and to extend than three that differ by a trailing argument. +struct ExecutorSettings { + QueueConfig queue; + + // The rate limiter's policy (D25). Defaults are the production values, so a caller that + // does not care gets the real limiter rather than a disabled one. + RateLimitConfig rate_limit; + + // The transport. Empty means "none available", which the executor reports rather than + // crashing on - a build without curl and no injected transport is a supported state. + std::weak_ptr transport; + + // The clock. Never null: the executor dereferences it, and a test supplies a fake. + Clock* clock = nullptr; + + std::weak_ptr logger; + + // Empty when the config was usable. A non-empty error makes every submission reject with + // it, which is how an inert client still delivers its handlers. + Error config_error; +}; + class Executor { public: - Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, - std::weak_ptr logger); - - // The same, plus the config error the client found. A non-empty error makes every - // submission reject with it, which is how an inert client still delivers its handlers. - Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, - std::weak_ptr logger, Error config_error); + explicit Executor(const ExecutorSettings& settings); ~Executor(); Executor(const Executor&) = delete; @@ -171,6 +193,13 @@ class Executor { Clock& m_clock; std::weak_ptr m_logger; + std::int64_t m_last_tick_ms = 0; + bool m_has_ticked = false; + + // The client-side throttle (D25). Held by value: it is small, it is ticked by `Update()`, + // and it has no reason to outlive the executor. + RateLimiter m_rate_limiter; + std::map m_entries; // Handlers for requests rejected at submit time. Bounded by how many the caller diff --git a/src/core/rate_limiter.cpp b/src/core/rate_limiter.cpp new file mode 100644 index 0000000..79d8b30 --- /dev/null +++ b/src/core/rate_limiter.cpp @@ -0,0 +1,261 @@ +#include "rate_limiter.h" + +#include + +namespace lootlocker { +namespace core { + +namespace { + +// The bucket count and the per-bucket limit are derived from the config rather than stored, +// so the fraction and the effective limit cannot disagree. `floor`, not round: the soft +// threshold must never be more permissive than the fraction says, or a client could sit +// above the intended rate indefinitely. +// +// Returns 0 for a configuration that cannot produce a usable window. That includes one whose +// product would overflow `int`: a large `moving_average_time_frames` with a large bucket +// count would otherwise wrap negative, and a negative bucket count takes the "disabled" fast +// path - silently turning the limiter off for a config that looked valid. +int DeriveBucketCount(const RateLimitConfig& config) +{ + if (config.seconds_per_bucket <= 0 || config.tripwire_window_seconds <= 0 + || config.moving_average_time_frames <= 0) { + return 0; + } + + // Reject a non-divisible policy rather than silently shortening the window. 60 s with + // 7 s buckets would otherwise become an effective 56 s tripwire and a 168 s moving + // average, while the config still advertises 60/180 - a different rate limit than the + // adopter asked for, with nothing to say so. + if (config.tripwire_window_seconds % config.seconds_per_bucket != 0) { + return 0; + } + + const int buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; + if (buckets_per_tripwire <= 0) { + return 0; + } + + // Checked before multiplying, not after: the multiply itself is the undefined behaviour. + const int max_int = 2147483647; + if (buckets_per_tripwire > max_int / config.moving_average_time_frames) { + return 0; + } + + return buckets_per_tripwire * config.moving_average_time_frames; +} + +} // namespace + +RateLimiter::RateLimiter(const RateLimitConfig& config, Clock& clock) + : m_config(config), m_clock(clock) +{ + // A disabled limiter derives and allocates nothing. Deriving first and guarding the + // allocation afterwards would still attempt the allocation for a disabled policy with a + // huge window, which in a no-exceptions build terminates the client. + if (!config.enabled) { + return; + } + + m_bucket_count = DeriveBucketCount(config); + if (m_bucket_count > 0) { + m_buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; + m_per_bucket_limit = config.PerBucketLimit(); + + // A fixed-size array, allocated once. `std::atomic` is neither copyable nor movable, + // so a vector cannot hold it. + m_buckets.reset(new std::atomic[static_cast(m_bucket_count)]); + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)] = 0; + } + } +} + +void RateLimiter::Reset() +{ + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)] = 0; + } + m_last_bucket = -1; + m_ms_into_bucket = 0; + m_started = false; + m_total = 0; + m_total_in_tripwire = 0; + m_limited = false; + m_ms_until_clear = 0; +} + +void RateLimiter::Tick(std::int64_t delta_ms) +{ + if (m_bucket_count <= 0) { + return; + } + + // The first tick initialises bucket 0, even with a zero delta. Without this the limiter + // would stay unstarted until time actually passed, and `Commit` would write to bucket -1. + if (!m_started) { + m_started = true; + m_last_bucket = 0; + m_ms_into_bucket = 0; + return; + } + + if (delta_ms <= 0) { + return; + } + + // The countdown to clearing is a duration, so it simply decreases. Clamped at zero so a + // long idle period cannot make it negative and then take a whole window to climb back. + if (m_limited) { + std::int64_t remaining = m_ms_until_clear - delta_ms; + if (remaining < 0) { + remaining = 0; + } + m_ms_until_clear = remaining; + } + + SlideWindow(delta_ms); +} + +void RateLimiter::SlideWindow(std::int64_t delta_ms) +{ + const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; + + const std::int64_t ms_into_bucket = m_ms_into_bucket + delta_ms; + + const std::int64_t numberOfBucketsTraversed = ms_into_bucket / bucket_ms; + if (numberOfBucketsTraversed == 0) { + m_ms_into_bucket = ms_into_bucket; + return; + } + + // Keep only the remainder, so sub-bucket time carries forward and cannot accumulate as + // drift over a long run. + m_ms_into_bucket = ms_into_bucket - numberOfBucketsTraversed * bucket_ms; + + const int last_bucket = m_last_bucket; + + // More buckets elapsed than exist: everything has aged out, so clear rather than looping + // over a window that is entirely stale. + if (numberOfBucketsTraversed >= m_bucket_count) { + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)] = 0; + } + m_total = 0; + m_total_in_tripwire = 0; + m_last_bucket = static_cast(numberOfBucketsTraversed % m_bucket_count); + return; + } + + int total = m_total; + int total_in_tripwire = m_total_in_tripwire; + + for (std::int64_t step = 1; step <= numberOfBucketsTraversed; ++step) { + const int bucket = static_cast((last_bucket + step) % m_bucket_count); + + // The bucket exactly one tripwire window behind this one is sliding out of the + // tripwire window, so its count leaves that total. + int leaving_tripwire = bucket - m_buckets_per_tripwire; + if (leaving_tripwire < 0) { + leaving_tripwire += m_bucket_count; + } + + total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)]; + total -= m_buckets[static_cast(bucket)]; + m_buckets[static_cast(bucket)] = 0; + } + + m_total = total; + m_total_in_tripwire = total_in_tripwire; + m_last_bucket = static_cast((last_bucket + numberOfBucketsTraversed) % m_bucket_count); +} + +bool RateLimiter::WouldTrip() const +{ + // Tripwire: this request would take the window to the cap. + if (m_total_in_tripwire + 1 + > m_config.max_requests_per_tripwire) { + return true; + } + + // Moving average: the per-bucket average across the whole window would exceed the + // derived limit. Integer division, matching the reference implementations. + const int projected = m_total + 1; + return (projected / m_bucket_count) > m_per_bucket_limit; +} + +bool RateLimiter::CanAcquire() const +{ + if (!m_config.enabled || m_bucket_count <= 0) { + return true; + } + + // While limited, nothing is counted. A held request has not been sent, so counting it + // would keep the limiter tripped by its own backlog - the window would never drain. + if (m_limited) { + return m_total <= 0; + } + + return !WouldTrip(); +} + +void RateLimiter::Commit() +{ + if (!m_config.enabled || m_bucket_count <= 0) { + return; + } + + // Defensive: `Tick` initialises bucket 0, so this cannot happen through the executor. + // But writing to `m_buckets[-1]` is a stack overrun rather than a wrong number, so the + // guard is worth the branch. + if (!m_started) { + return; + } + + // The window has drained, so the limit is lifted. `IsLimited()` derives from `m_total` + // as well, so this is belt-and-braces rather than the only place it clears. + if (m_limited && m_total <= 0) { + m_limited = false; + m_ms_until_clear = 0; + } + + const int last_bucket = m_last_bucket; + m_buckets[static_cast(last_bucket)].fetch_add(1, kRelaxed); + m_total.fetch_add(1, kRelaxed); + m_total_in_tripwire.fetch_add(1, kRelaxed); + + // `IsLimited()` reports whether the *next* request would be refused, which is what + // `CanAcquire()` will say. Recording it here keeps the two in agreement: without this, + // `CanAcquire()` would refuse while `IsLimited()` still said false. + // + // The request that *reaches* the cap is allowed - the cap is "more than 280", not "280" - + // so this is `WouldTrip()` after the increment, not before it. + if (WouldTrip()) { + m_limited = true; + + // The limit clears once everything currently counted has aged out of the window, + // plus whatever is left of the current bucket. + const std::int64_t window_ms = + static_cast(m_bucket_count) * m_config.seconds_per_bucket * 1000; + const std::int64_t bucket_ms = + static_cast(m_config.seconds_per_bucket) * 1000; + m_ms_until_clear = window_ms + (bucket_ms - m_ms_into_bucket); + } +} + +int RateLimiter::SecondsUntilClear() const +{ + if (!IsLimited()) { + return 0; + } + const std::int64_t remaining = m_ms_until_clear; + if (remaining <= 0) { + return 0; + } + // Round up, so a caller that waits this long is not still limited by a fraction of a + // second. + return static_cast((remaining + 999) / 1000); +} + +} // namespace core +} // namespace lootlocker \ No newline at end of file diff --git a/src/core/rate_limiter.h b/src/core/rate_limiter.h new file mode 100644 index 0000000..358cc26 --- /dev/null +++ b/src/core/rate_limiter.h @@ -0,0 +1,159 @@ +#pragma once + +// The client-side rate limiter (D25). Internal: `lootlocker::core::` is not on an adopter's +// include path (D18). +// +// A dual-threshold sliding window, ported from the Unreal and Unity SDKs, which share the +// algorithm. Two thresholds, because one is not enough: +// +// Tripwire - hard cap: more than `max_requests_per_tripwire` in any rolling +// `tripwire_window_seconds` window. +// Moving average - soft cap: the per-bucket average across the whole window exceeds +// `PerBucketLimit()`, i.e. sustained traffic above +// `moving_average_fraction` of the tripwire rate. +// +// The soft cap exists because a pure tripwire lets a client sit at 279 requests a minute +// for ever: abusive, but never tripping. The moving average catches sustained near-limit +// behaviour that the tripwire cannot see. +// +// **This is client-side self-restraint, not error handling.** A tripped request is held and +// sent later, never dropped and never reported as an error. A server-side 429 is a different +// thing entirely and is handled by the executor's retry policy - conflating the two is how +// the other SDKs ended up with a limiter that also tries to be a retry policy. + +#include + +#include "clock.h" + +#include +#include +#include +#include + +namespace lootlocker { +namespace core { + +// The memory order used throughout the limiter. +// +// Relaxed is deliberate: the requirement is that each field is read and written atomically, +// not that other threads observe any particular order between them. A stronger order would +// buy nothing here and cost on the hot path. +// +// Named once so the intent is stated in one place rather than repeated at every access, and +// so a future change to the ordering is one edit rather than forty. +constexpr std::memory_order kRelaxed = std::memory_order_relaxed; + +class RateLimiter { +public: + RateLimiter(const RateLimitConfig& config, Clock& clock); + + RateLimiter(const RateLimiter&) = delete; + RateLimiter& operator=(const RateLimiter&) = delete; + + // Advances the window by `delta_ms`. Called by the executor's tick, once per `Update()`, + // before anything is promoted. + // + // **Time is pushed in, not read here.** The limiter used to call the clock itself from + // inside `CanAcquire()`, which made a `const`-looking predicate mutate the whole module - + // and meant the window only advanced when someone happened to ask. A tickable component + // should be told how much time passed and do nothing else; the executor owns the clock + // and is the one place that reads it. + void Tick(std::int64_t delta_ms); + + // Whether a request may be sent now. **Const**: it reads the window and reports, and + // does not advance or record anything. + // + // Split from `Commit` so the executor can check *before* starting a transfer and record + // only if the transfer actually started. `IHttpTransport::Start` may return 0, and a + // start that failed sent nothing - counting it would burn quota for a request that never + // left, and repeated failures could hold unrelated queued requests. + bool CanAcquire() const; + + // Records one request against the window. Call only after `CanAcquire()` returned true + // and the transfer actually started. + void Commit(); + + // True while the limiter is holding requests back. + // + // Derived rather than stored: a stored flag has to be cleared by something, and the only + // method that runs after a successful check is `Commit` - so a caller that only ever + // checked would see a stale `true` for ever. Deriving it means `IsLimited()` and + // `CanAcquire()` cannot disagree. + bool IsLimited() const { return m_limited && m_total > 0; } + + // Seconds until the limit is expected to clear. 0 when not limited. + // + // An estimate, not a promise: it is derived from when the oldest counted request ages + // out of the window, and the executor uses it only to decide when to look again. + int SecondsUntilClear() const; + + // Requests counted in the tripwire window, for tests and logs. + int TripwireCount() const { return m_total_in_tripwire; } + + // Requests counted across the whole moving-average window, for tests and logs. + int WindowCount() const { return m_total; } + + // Drops all state. For test isolation and for a client that is being reset. + void Reset(); + +private: + // Zeroes the buckets that have slid out of the window and removes their counts from the + // running totals. + void SlideWindow(std::int64_t delta_ms); + + // Whether adding one more request would exceed either threshold. Used by `CanAcquire()` + // before anything is recorded, and by `Commit()` after, so the two agree. + bool WouldTrip() const; + + RateLimitConfig m_config; + Clock& m_clock; + + // Derived from the config at construction, so the arithmetic cannot disagree with + // itself later. + int m_bucket_count = 0; + int m_buckets_per_tripwire = 0; + int m_per_bucket_limit = 0; + + // **Atomics, because the SDK is single-threaded by contract but not by enforcement.** + // `Update()` is documented as the only entry point and callbacks fire on the calling + // thread (D5), so in a correct program nothing here is contended. But a game that calls + // `Update()` from two threads by mistake would otherwise corrupt the window silently, + // and a torn read of `m_total` is a wrong rate limit rather than a crash - the kind of + // bug that shows up as "the limiter randomly trips" months later. + // + // Relaxed ordering throughout: the requirement is that each field is read and written + // atomically, not that other threads observe any particular order between them. A + // stronger order would buy nothing here and cost on the hot path. + // + // Explicit locks are deliberately not used. There is no invariant that spans two fields + // - a torn read of `m_total` against `m_total_in_tripwire` gives a slightly stale + // decision, not a corrupt one - so a mutex would add contention to buy nothing. + // A heap array rather than a `std::vector`: `std::atomic` is neither copyable nor + // movable, so a vector cannot grow or reallocate. The size is fixed at construction, so + // an array is the right shape anyway. + std::unique_ptr[]> m_buckets; + + // Index of the most recently written bucket. -1 before the first tick. + std::atomic m_last_bucket{-1}; + + // Milliseconds accumulated since the current bucket became active. Kept as a remainder + // rather than an absolute timestamp, because the limiter is told deltas and never reads + // the clock: sub-bucket remainder carries forward, so it cannot accumulate as drift. + std::atomic m_ms_into_bucket{0}; + std::atomic m_started{false}; + + // Requests across every bucket in the array. + std::atomic m_total{0}; + + // Requests in the buckets that fall inside the current tripwire window. + std::atomic m_total_in_tripwire{0}; + + std::atomic m_limited{false}; + + // Milliseconds until the limit is expected to clear, counted down by `Tick`. A remaining + // duration rather than a deadline, for the same reason: no clock reads. + std::atomic m_ms_until_clear{0}; +}; + +} // namespace core +} // namespace lootlocker diff --git a/src/core/request_id.cpp b/src/core/request_id.cpp index cc962ab..ea8800e 100644 --- a/src/core/request_id.cpp +++ b/src/core/request_id.cpp @@ -27,10 +27,15 @@ RequestId RequestId::Next() // `fetch_add` it replaces. std::uint64_t current = g_next_request_id.load(std::memory_order_relaxed); for (;;) { - // Skip 0, which is the invalid id. Unreachable in practice - a uint64 at a million - // requests a second lasts longer than the hardware - but the loop makes the wrap - // safe by construction rather than by argument. - const std::uint64_t next = (current == 0) ? 1 : current + 1; + // Skip 0, which is the invalid id, and wrap from the maximum back to 1 rather than + // to 0. `current + 1` alone would store 0 at the wrap, and the *next* call would + // then return `RequestId(0)` - which is indistinguishable from a rejected + // submission and would collide with that map key. + // + // Unreachable in practice - a uint64 at a million requests a second lasts longer + // than the hardware - but the loop makes the invariant true by construction rather + // than by argument. + const std::uint64_t next = (current == 0 || current == UINT64_MAX) ? 1 : current + 1; if (g_next_request_id.compare_exchange_weak(current, next, std::memory_order_relaxed, std::memory_order_relaxed)) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c9f369c..ba1cda7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -54,6 +54,12 @@ target_link_libraries(test_executor PRIVATE LootLocker::core lootlocker_compile_ target_include_directories(test_executor PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME executor COMMAND test_executor) +# The rate limiter (T11a). Driven by a fake clock, so nothing sleeps. +add_executable(test_rate_limiter test_rate_limiter.cpp) +target_link_libraries(test_rate_limiter PRIVATE LootLocker::core lootlocker_compile_options) +target_include_directories(test_rate_limiter PRIVATE ${CMAKE_SOURCE_DIR}/src/core) +add_test(NAME rate_limiter COMMAND test_rate_limiter) + # The end-to-end transport test (T11, owner 2026-11-13): a real round trip through the real # curl transport against a loopback server, plus the proof that `Config::transport` is # actually consulted. diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 7ff1e51..43d9801 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -30,6 +30,7 @@ class FakeClock : public Clock { public: std::int64_t NowMs() override { return m_now; } void Advance(std::int64_t ms) { m_now += ms; } + void AdvanceSeconds(int seconds) { m_now += static_cast(seconds) * 1000; } private: std::int64_t m_now = 1000; // non-zero, so "not set" is distinguishable @@ -86,7 +87,12 @@ struct Fixture { explicit Fixture(QueueConfig config = DefaultQueue()) : transport(std::make_shared()), logger(std::make_shared()) { - executor.reset(new Executor(config, transport, clock, logger)); + ExecutorSettings settings; + settings.queue = config; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + executor.reset(new Executor(settings)); } std::shared_ptr transport; @@ -651,7 +657,13 @@ void TestInvalidConfigRejectsThroughUpdate() auto transport = std::make_shared(); auto logger = std::make_shared(); FakeClock clock; - Executor executor(DefaultQueue(), transport, clock, logger, config_error); + ExecutorSettings settings; + settings.queue = DefaultQueue(); + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + settings.config_error = config_error; + Executor executor(settings); int delivered = 0; Completion last; @@ -1004,6 +1016,247 @@ void TestRequestIdNextIsUniqueUnderConcurrency() CHECK(all.front() != 0); } +// --- The rate limiter's integration with the queue (T11a) ------------------------------ + +// A fixture whose limiter is tight enough to trip in a few requests, so the integration is +// testable without 280 submissions. +struct LimitedFixture { + LimitedFixture() + : transport(std::make_shared()), + logger(std::make_shared()) + { + QueueConfig queue = DefaultQueue(); + queue.max_in_flight = 50; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + executor.reset(new Executor(settings)); + } + + std::shared_ptr transport; + std::shared_ptr logger; + FakeClock clock; + std::unique_ptr executor; +}; + +void TestTrippedRequestIsHeldThenDelivered() +{ + LimitedFixture f; + + int delivered = 0; + for (int i = 0; i < 5; ++i) { + f.executor->Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // The limiter allows 3 in the window, so only 3 are sent. The other 2 are held, not + // dropped and not failed. + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 3); + CHECK_EQ_INT(delivered, 0); + + // Complete the three that went out. + for (const auto transfer : f.transport->Order()) { + f.transport->Complete(transfer, 200, "{}"); + } + CHECK(f.executor->Update()); + CHECK_EQ_INT(delivered, 3); + + // The two held requests are still queued, and `Update()` still reports work to do - + // which is what stops a `while (Update())` loop from exiting early and losing them. + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 3); + + // Once the window clears they are sent, without the caller doing anything. + f.clock.AdvanceSeconds(11); + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 5); + + for (const auto transfer : f.transport->Order()) { + f.transport->Complete(transfer, 200, "{}"); + } + CHECK(!f.executor->Update()); + CHECK_EQ_INT(delivered, 5); +} + +void TestServerRateLimitIsHandledByRetryNotTheLimiter() +{ + // The limiter is disabled, so a 429 can only be handled by the retry policy. This is + // the separation D25 insists on: the limiter is client-side self-restraint, and a + // server 429 is a different thing entirely. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 2; + + RateLimitConfig limit; + limit.enabled = false; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + FakeClock clock; + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); + + int delivered = 0; + Completion last; + executor.Submit(Get("https://example.test/a"), [&](const Completion& c) { + ++delivered; + last = c; + }); + + CHECK(executor.Update()); + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(executor.Update()); + + // Retried by the retry policy, not held by the limiter. + CHECK_EQ_INT(delivered, 0); + clock.Advance(50); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 2); + + // Attempt 2 fails the same way, so it is requeued again with a doubled delay. + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(executor.Update()); + CHECK_EQ_INT(delivered, 0); + clock.Advance(100); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 3); + + // Attempt 3 exhausts the budget, so the failure is delivered. It is `RateLimited` + // because the server said so - the limiter is disabled and had no part in it. + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(!executor.Update()); + + CHECK_EQ_INT(delivered, 1); + CHECK(last.error.code == ErrorCode::RateLimited); + CHECK_EQ_INT(last.attempts, 3); +} + +// A transport that refuses to start anything, so the executor's start-failure path can be +// exercised. +class RefusingTransport : public IHttpTransport { +public: + TransferId Start(const Request&) override { return 0; } + bool Poll(TransferId, Response&) override { return false; } + void Cancel(TransferId) override {} +}; + +void TestFailedStartDoesNotBurnQuota() +{ + // The limiter allows 3 in the window. Every start fails, so nothing is ever sent - and + // nothing should be counted. Counting a failed start would burn quota for a request that + // never left, and repeated failures could hold unrelated queued requests. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 0; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + FakeClock clock; + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); + + int delivered = 0; + for (int i = 0; i < 10; ++i) { + executor.Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // Every one fails to start, so every one is delivered as a transport failure rather than + // being held by a limiter that thinks it sent something. + executor.Update(); + CHECK_EQ_INT(delivered, 10); +} +// A clock that starts at 0, which `Clock` permits: it only promises monotonic milliseconds, +// not a non-zero origin. +class ZeroOriginClock : public Clock { +public: + std::int64_t NowMs() override { return m_now; } + void Advance(std::int64_t ms) { m_now += ms; } + +private: + std::int64_t m_now = 0; +}; + +void TestZeroOriginClockStillAdvances() +{ + // The executor used 0 as its "no previous tick" sentinel, so a clock that legitimately + // started at 0 left `m_last_tick_ms` at 0 for ever and computed a delta of 0 every time - + // the limiter's buckets never advanced and held requests stayed blocked indefinitely. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 0; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + ZeroOriginClock clock; + + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); + + int delivered = 0; + for (int i = 0; i < 5; ++i) { + executor.Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // Three go out, two are held. + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 3); + + for (const auto transfer : transport->Order()) { + transport->Complete(transfer, 200, "{}"); + } + executor.Update(); + CHECK_EQ_INT(delivered, 3); + + // The clock starts at 0, so this is the case that used to never advance. Past the window, + // the held two must be sent. + clock.Advance(11000); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 5); +} + void TestAbandonCancelsInFlightWithoutCallingBack() { Fixture f; @@ -1062,6 +1315,10 @@ int main() TestRequestIdsAreUniqueAcrossClients(); TestRequestIdNextIsMonotonic(); TestRequestIdNextIsUniqueUnderConcurrency(); + TestTrippedRequestIsHeldThenDelivered(); + TestServerRateLimitIsHandledByRetryNotTheLimiter(); + TestFailedStartDoesNotBurnQuota(); + TestZeroOriginClockStillAdvances(); TestAbandonCancelsInFlightWithoutCallingBack(); return testing::Report(); diff --git a/tests/test_rate_limiter.cpp b/tests/test_rate_limiter.cpp new file mode 100644 index 0000000..24a07f4 --- /dev/null +++ b/tests/test_rate_limiter.cpp @@ -0,0 +1,435 @@ +// The rate limiter (T11a, D25). +// +// Driven by a fake clock, so every timing assertion is exact and nothing sleeps. The +// algorithm is ported from the Unreal and Unity SDKs, so the tests are written against the +// behaviour those implementations have, not against a re-derivation of it. + +#include + +#include "clock.h" +#include "rate_limiter.h" +#include "test_harness.h" + +#include + +using namespace lootlocker; +using namespace lootlocker::core; + +namespace { + +class FakeClock : public Clock { +public: + std::int64_t NowMs() override { return m_now; } + void Advance(std::int64_t ms) { m_now += ms; } + void AdvanceSeconds(int seconds) { m_now += static_cast(seconds) * 1000; } + +private: + std::int64_t m_now = 1000000; // non-zero, so "not set" is distinguishable +}; + +// The limiter is told deltas and never reads the clock, so a test drives it by ticking. +// +// `Acquire` is the old `TryAcquire` shape - tick, check, commit - which is what the executor +// does across an `Update()`. Keeping it here rather than in the limiter is deliberate: the +// limiter has no business deciding when time passes. +bool Acquire(RateLimiter& limiter, FakeClock& clock, std::int64_t delta_ms = 0) +{ + clock.Advance(delta_ms); + limiter.Tick(delta_ms); + if (!limiter.CanAcquire()) { + return false; + } + limiter.Commit(); + return true; +} + +void Advance(RateLimiter& limiter, FakeClock& clock, int seconds) +{ + const std::int64_t delta_ms = static_cast(seconds) * 1000; + clock.Advance(delta_ms); + limiter.Tick(delta_ms); +} + +RateLimitConfig Defaults() +{ + RateLimitConfig config; + config.enabled = true; + config.tripwire_window_seconds = 60; + config.max_requests_per_tripwire = 280; + config.seconds_per_bucket = 5; + config.moving_average_fraction = 0.8; + config.moving_average_time_frames = 3; + return config; +} + +// The derived values the defaults must produce, asserted once so a change to the derivation +// is visible rather than silently shifting every threshold. +void TestDerivedConstants() +{ + const RateLimitConfig config = Defaults(); + + // 280 * 0.8 * 5 / 60 = 18.67, floored to 18. + CHECK_EQ_INT(config.PerBucketLimit(), 18); +} + +// --- The tripwire ---------------------------------------------------------------------- + +void TestBurstTripsTheTripwire() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 280 requests in one bucket is allowed: the cap is "more than 280". + int allowed = 0; + for (int i = 0; i < 280; ++i) { + if (Acquire(limiter, clock)) { + ++allowed; + } + } + CHECK_EQ_INT(allowed, 280); + + // `IsLimited()` reports whether the *next* request would be refused, so it is already + // true here - the 281st is the one that trips. + CHECK(limiter.IsLimited()); + + // The 281st is refused. + CHECK(!Acquire(limiter, clock)); + CHECK(limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 280); +} + +void TestTripwireClearsWhenTheWindowSlides() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!Acquire(limiter, clock)); + CHECK(limiter.IsLimited()); + + // The tripwire window is 60 s, but the limiter does not clear when the tripwire window + // slides - it clears when every counted request has aged out of the *moving-average* + // window, which is 36 buckets of 5 s = 180 s. That is the reference behaviour in both + // the Unreal and Unity SDKs, and it is deliberately conservative: a burst that tripped + // the hard cap backs the client off for the full window rather than resuming the + // instant the 60 s count drops. + Advance(limiter, clock, 59); + CHECK(!Acquire(limiter, clock)); + CHECK(limiter.IsLimited()); + + Advance(limiter, clock, 60); + CHECK(!Acquire(limiter, clock)); + CHECK(limiter.IsLimited()); + + // Past the full window, the counted requests have aged out and the limiter clears. + Advance(limiter, clock, 62); + CHECK(limiter.CanAcquire()); + CHECK(!limiter.IsLimited()); +} + +// --- The moving average ---------------------------------------------------------------- + +void TestSustainedTrafficTripsTheMovingAverage() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 18 requests per 5 s bucket is exactly the derived limit, so it must NOT trip: the + // check is "average exceeds 18", not "reaches 18". + // + // 36 buckets of 5 s is the whole window, so this is 3 minutes of traffic at exactly the + // soft cap. + for (int bucket = 0; bucket < 36; ++bucket) { + for (int i = 0; i < 18; ++i) { + CHECK(Acquire(limiter, clock)); + } + Advance(limiter, clock, 5); + } + CHECK(!limiter.IsLimited()); + + // One more per bucket pushes the average over 18 and trips the soft cap, even though + // the tripwire (280 per 60 s) is nowhere near. + for (int bucket = 0; bucket < 36; ++bucket) { + for (int i = 0; i < 19; ++i) { + if (!Acquire(limiter, clock)) { + // Tripped partway through, which is the expected outcome. + CHECK(limiter.IsLimited()); + return; + } + } + Advance(limiter, clock, 5); + } + + // Reaching here means it never tripped, which is the failure. + CHECK(limiter.IsLimited()); +} + +void TestMovingAverageTripsBelowTheTripwire() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 19 per bucket is 228 per 60 s, comfortably under the 280 tripwire. The soft cap is + // what catches it, which is the whole reason the soft cap exists. + bool tripped = false; + for (int bucket = 0; bucket < 36 && !tripped; ++bucket) { + for (int i = 0; i < 19; ++i) { + if (!Acquire(limiter, clock)) { + tripped = true; + break; + } + } + Advance(limiter, clock, 5); + } + + CHECK(tripped); + CHECK(limiter.IsLimited()); + + // And the tripwire count never reached its cap, so it was the average that caught it. + CHECK(limiter.TripwireCount() < 280); +} + +// --- A tripped request is held, not dropped -------------------------------------------- + +void TestHeldRequestsAreNotCounted() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!Acquire(limiter, clock)); + CHECK_EQ_INT(limiter.TripwireCount(), 280); + + // A held request must not count against the window, or the limiter would keep itself + // tripped by its own backlog and the window would never drain. + for (int i = 0; i < 100; ++i) { + CHECK(!Acquire(limiter, clock)); + } + CHECK_EQ_INT(limiter.TripwireCount(), 280); + + // So it still clears on schedule - the full moving-average window, not the tripwire + // window. + Advance(limiter, clock, 181); + CHECK(Acquire(limiter, clock)); +} + +void TestSecondsUntilClearIsAnEstimateThatExpires() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); + + for (int i = 0; i < 280; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!Acquire(limiter, clock)); + + // The window is 3 minutes (36 buckets of 5 s), plus whatever is left of the current + // bucket - so the estimate is bounded by 180 s plus one bucket. + const int estimate = limiter.SecondsUntilClear(); + CHECK(estimate > 0); + CHECK(estimate <= 185); + + // Waiting the estimate out clears it. + Advance(limiter, clock, estimate); + CHECK(Acquire(limiter, clock)); + CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); +} + +// --- Disabled, and the config edge cases ----------------------------------------------- + +void TestDisabledLimiterAlwaysAllows() +{ + RateLimitConfig config = Defaults(); + config.enabled = false; + + FakeClock clock; + RateLimiter limiter(config, clock); + + // Far past every threshold, and still allowed. + for (int i = 0; i < 10000; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!limiter.IsLimited()); +} + +void TestResetClearsEverything() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!Acquire(limiter, clock)); + CHECK(limiter.IsLimited()); + + limiter.Reset(); + + CHECK(!limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 0); + CHECK_EQ_INT(limiter.WindowCount(), 0); + CHECK(Acquire(limiter, clock)); +} + +void TestLongIdlePeriodClearsWithoutIterating() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!Acquire(limiter, clock)); + + // A day of idleness is far more buckets than exist. The limiter must clear rather than + // loop over a window that is entirely stale. + Advance(limiter, clock, 86400); + CHECK(limiter.CanAcquire()); + CHECK(!limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 0); +} + +void TestCustomConstantsAreHonoured() +{ + // The constants are policy, not a constexpr in a header, so a different policy must + // work. 10 per 10 s, one bucket per 10 s, one frame. + RateLimitConfig config; + config.enabled = true; + config.tripwire_window_seconds = 10; + config.max_requests_per_tripwire = 10; + config.seconds_per_bucket = 10; + config.moving_average_fraction = 1.0; + config.moving_average_time_frames = 1; + FakeClock clock; + RateLimiter limiter(config, clock); + + int allowed = 0; + for (int i = 0; i < 10; ++i) { + if (Acquire(limiter, clock)) { + ++allowed; + } + } + CHECK_EQ_INT(allowed, 10); + CHECK(!Acquire(limiter, clock)); + + Advance(limiter, clock, 11); + CHECK(Acquire(limiter, clock)); +} + +void TestNonDivisiblePolicyIsRejected() +{ + // 60 s with 7 s buckets does not divide. Silently shortening it would give an effective + // 56 s tripwire and a 168 s moving average while the config still advertises 60/180 - + // a different rate limit than the adopter asked for, with nothing to say so. + // + // Rejected at validation, not just at construction: a `Client` built from this config + // must fail rather than silently run unthrottled. + RateLimitConfig config = Defaults(); + config.seconds_per_bucket = 7; + + Config full; + full.domain_key = "1g9glch3"; + full.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + full.game_version = "1.2.1"; + full.rate_limit = config; + + const Error error = ValidateConfig(full); + CHECK(!error.Ok()); + CHECK(error.code == ErrorCode::InvalidConfig); + CHECK(error.message.find("multiple") != std::string::npos); +} + +void TestOverflowingBucketCountIsRejected() +{ + // A large window with 1 s buckets asks for billions of buckets - gigabytes of atomics - + // and in a no-exceptions build that terminates the client during construction. Rejected + // at validation so it cannot reach the allocator. + RateLimitConfig config = Defaults(); + config.tripwire_window_seconds = 2000000000; + config.seconds_per_bucket = 1; + config.moving_average_time_frames = 1; + + Config full; + full.domain_key = "1g9glch3"; + full.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + full.game_version = "1.2.1"; + full.rate_limit = config; + + const Error error = ValidateConfig(full); + CHECK(!error.Ok()); + CHECK(error.code == ErrorCode::InvalidConfig); + CHECK(error.message.find("buckets") != std::string::npos); +} + +void TestDisabledLimiterAllocatesNothing() +{ + // A disabled limiter must not derive or allocate a bucket array at all: the derivation + // happens before the allocation guard, so a disabled policy with a huge window would + // otherwise still try to allocate. + RateLimitConfig config = Defaults(); + config.enabled = false; + config.tripwire_window_seconds = 2000000000; + config.seconds_per_bucket = 1; + config.moving_average_time_frames = 1; + + FakeClock clock; + RateLimiter limiter(config, clock); + + for (int i = 0; i < 1000; ++i) { + CHECK(Acquire(limiter, clock)); + } + CHECK(!limiter.IsLimited()); +} +void TestCommitIsSeparateFromTheCheck() +{ + // The executor checks, starts the transfer, and only then commits - because a `Start` + // that returned 0 sent nothing. This is the primitive that makes that possible. + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // The first tick initialises bucket 0. Without it `Commit` has nowhere to write, which is + // why the executor ticks before promoting anything. + limiter.Tick(0); + + CHECK(limiter.CanAcquire()); + CHECK_EQ_INT(limiter.TripwireCount(), 0); // checking alone records nothing + + limiter.Commit(); + CHECK_EQ_INT(limiter.TripwireCount(), 1); + + // A check that is never committed leaves the window untouched, so a failed start cannot + // burn quota. + for (int i = 0; i < 500; ++i) { + CHECK(limiter.CanAcquire()); + } + CHECK_EQ_INT(limiter.TripwireCount(), 1); +} + +} // namespace + +int main() +{ + TestDerivedConstants(); + TestBurstTripsTheTripwire(); + TestTripwireClearsWhenTheWindowSlides(); + TestSustainedTrafficTripsTheMovingAverage(); + TestMovingAverageTripsBelowTheTripwire(); + TestHeldRequestsAreNotCounted(); + TestSecondsUntilClearIsAnEstimateThatExpires(); + TestDisabledLimiterAlwaysAllows(); + TestResetClearsEverything(); + TestLongIdlePeriodClearsWithoutIterating(); + TestCustomConstantsAreHonoured(); + TestNonDivisiblePolicyIsRejected(); + TestOverflowingBucketCountIsRejected(); + TestDisabledLimiterAllocatesNothing(); + TestCommitIsSeparateFromTheCheck(); + + return testing::Report(); +} diff --git a/tests/test_transport_e2e.cpp b/tests/test_transport_e2e.cpp index 325ec03..712b35b 100644 --- a/tests/test_transport_e2e.cpp +++ b/tests/test_transport_e2e.cpp @@ -312,6 +312,34 @@ void TestInvalidConfigMakesTheClientInert() CHECK_EQ_INT(static_cast(fake->StartCount()), 0); } +void TestInvalidPolicyDoesNotAllocateInTheClient() +{ + // `ValidateConfig` rejects an oversized policy, but the client used to pass it straight + // to the executor anyway - so a rejected 2-billion-second window still derived 2 billion + // buckets and attempted a multi-gigabyte allocation during construction. In a + // no-exceptions build that terminates the client, which defeats the point of validating. + Config config; + config.domain_key = "1g9glch3"; + config.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + config.game_version = "1.2.1"; + config.rate_limit.tripwire_window_seconds = 2000000000; + config.rate_limit.seconds_per_bucket = 1; + config.rate_limit.moving_average_time_frames = 1; + + auto fake = std::make_shared(); + config.transport = fake; + + // The assertion is that this returns at all rather than exhausting memory. + Client client(config); + + CHECK(!client.ConfigError().Ok()); + CHECK(client.ConfigError().code == ErrorCode::InvalidConfig); + + // And it is inert, as an invalid client should be. + CHECK(!client.Update()); + CHECK_EQ_INT(static_cast(fake->StartCount()), 0); +} + } // namespace int main() @@ -319,6 +347,7 @@ int main() TestInjectedTransportIsUsedByTheClient(); TestSetTransportReplacesTheInjectedOne(); TestInvalidConfigMakesTheClientInert(); + TestInvalidPolicyDoesNotAllocateInTheClient(); #if defined(LOOTLOCKER_HAVE_CURL) TestRealRoundTripThroughCurl();