Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
21 changes: 19 additions & 2 deletions src/core/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
27 changes: 27 additions & 0 deletions src/core/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
50 changes: 39 additions & 11 deletions src/core/executor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,10 @@ bool IsRetryableStatus(int status_code)

} // namespace

Executor::Executor(const QueueConfig& config, std::weak_ptr<IHttpTransport> transport,
Clock& clock, std::weak_ptr<Logger> 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<IHttpTransport> transport,
Clock& clock, std::weak_ptr<Logger> 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)
{
}

Expand Down Expand Up @@ -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<CompletionHandler> handlers;
std::vector<Completion> completions;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}

Expand Down
43 changes: 36 additions & 7 deletions src/core/executor.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include <lootlocker/result.h>

#include "clock.h"
#include "rate_limiter.h"

#include <cstddef>
#include <cstdint>
Expand Down Expand Up @@ -60,15 +61,36 @@ struct Completion {

using CompletionHandler = std::function<void(const Completion&)>;

// 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<IHttpTransport> transport;

// The clock. Never null: the executor dereferences it, and a test supplies a fake.
Clock* clock = nullptr;

std::weak_ptr<Logger> 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<IHttpTransport> transport, Clock& clock,
std::weak_ptr<Logger> 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<IHttpTransport> transport, Clock& clock,
std::weak_ptr<Logger> logger, Error config_error);
explicit Executor(const ExecutorSettings& settings);
~Executor();

Executor(const Executor&) = delete;
Expand Down Expand Up @@ -171,6 +193,13 @@ class Executor {
Clock& m_clock;
std::weak_ptr<Logger> 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<RequestId, Entry> m_entries;

// Handlers for requests rejected at submit time. Bounded by how many the caller
Expand Down
Loading
Loading