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
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ add_library(lootlocker_core STATIC
src/core/text.cpp
src/core/config_obfuscation.cpp
src/core/header_map.cpp
src/core/executor.cpp
src/core/client.cpp
)

# The curl transport is only compiled when curl was found AND the option is on. Both
Expand Down
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,59 @@ Only what you name is compiled and linked. To declare a subset of modules withou
`-DLOOTLOCKER_MODULE_ONLY="auth;broadcasts"` — quoted, because an unquoted `;` ends the
`cmake` command on a POSIX shell.

## Driving it

Constructing a `Client` starts no thread and opens no socket. Requests move only when
someone calls `Update()`, which does a frame's worth of work and returns `false` when
nothing is in flight and nothing is queued:

```cpp
lootlocker::Config cfg;
cfg.domain_key = "1g9glch3";
cfg.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc";
cfg.game_version = "1.2.1";

lootlocker::Client ll(cfg);

// In your loop, once per frame:
ll.Update();
```

`Update()` polls in-flight transfers, applies the retry policy, promotes queued requests
under the concurrency cap, and delivers callbacks — all in one call, on the calling thread.
A `while (ll.Update())` loop therefore terminates once the last callback has fired, which is
what lets a program with no host loop exit.

A bad config does not throw and does not crash. `Client::ConfigError()` reports it, and the
client is inert: `Update()` returns `false` and nothing is ever sent.

### The queue's policy

`QueueConfig` is public and per-client, because a slow platform or a tight memory budget
needs different numbers:

| Field | Default | What it does |
| --- | --- | --- |
| `max_retries` | 5 | Retries after the first attempt |
| `initial_backoff_ms` | 50 | First delay; doubles each retry |
| `backoff_factor` | 2 | Multiplier per retry |
| `max_in_flight` | 50 | Concurrent transfers |
| `max_queue_size` | 5000 | Queued requests before the queue is "full" |
| `choke_warning_threshold` | 500 | When to warn that the queue is backing up |
| `request_timeout_seconds` | 300 | Whole-request budget |
| `deny_when_backed_up` | true | Reject on a full queue instead of stalling |

The retry policy, which is the part that bites:

- **Retried:** 5xx, 429, and a transport failure (no response at all).
- **Not retried:** any other 4xx. A 400 will be a 400 again.
- **`Retry-After` is obeyed exactly** when the server sends one, instead of guessing.
- **A non-idempotent request whose response was lost is never retried.** A POST that timed
out may have succeeded, and retrying it can double-grant. A 5xx on a POST *is* retried,
because the server told us it failed. This is set per request with
`PendingRequest::idempotent`, which defaults to `true` — every write must opt out
deliberately.

## The transport

The SDK never calls the network directly. Everything goes through `IHttpTransport`, and the
Expand Down
82 changes: 82 additions & 0 deletions include/lootlocker/client.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#pragma once

// The client (D5, D20). The only object an adopter owns.
//
// It is not a singleton, it starts no thread, and it exposes no feature methods: modules
// are namespaces of free functions that take it (D19). Constructing one starts nothing;
// requests move only when someone calls `Update()`.

#include <lootlocker/config.h>
#include <lootlocker/result.h>

#include <memory>

namespace lootlocker {

class Client;

namespace core {
class Executor;

// The internal access point a module uses to reach the queue.
//
// Declared here rather than in a `src/` header because a module target has to be able to
// name it, and a module may include `core`'s internals (D18). An adopter cannot use it:
// `src/` is not on their include path, so the definition is unreachable even though the
// declaration is visible.
//
// This is the seam `core::Send<Definition>()` is built on (T13). It is not test
// scaffolding.
Executor& GetExecutor(Client& client);
} // namespace core

class Client {
public:
// Validates the config and throws nothing: a bad config is reported through
// `ConfigError()`, because a constructor cannot return a `Result` and the SDK does not
// throw (D7).
//
// A client with an invalid config is inert: `Update()` returns false, every request is
// rejected with `InvalidConfig`, and nothing is sent. That is deliberate - a game that
// ships a bad config gets a clear error in its log rather than a crash at startup.
explicit Client(const Config& config);
~Client();

Client(const Client&) = delete; // one owner, no copies
Client& operator=(const Client&) = delete;

// Drives the queue. Returns false when nothing is in flight and nothing is queued.
//
// Does a frame's worth of work, not one item: it polls, retries, promotes and delivers
// in one call. Callbacks fire here, on the calling thread (D5).
bool Update();

// The config the client was built with, after validation.
const Config& GetConfig() const;

// Empty when the config was usable. Set when it was not, and the client is inert.
const Error& ConfigError() const;

// Replaces the transport. The client observes it through a `weak_ptr`, so the adopter
// keeps ownership and a transport that dies is detected rather than dereferenced.
//
// Returns false when the replacement was refused because requests are still in flight.
// An in-flight transfer id is meaningful only to the transport that issued it, so
// swapping underneath would strand the old transfer. Drain first, then replace.
bool SetTransport(std::weak_ptr<IHttpTransport> transport);

// The transport in use, for a test or a wrapper that needs to inspect it. Empty when
// the client has none, which happens when curl was not built in and nothing was
// injected.
std::weak_ptr<IHttpTransport> GetTransport() const;

private:
// The correct form: the function is declared in `core` above, so the friend
// declaration names it qualified rather than declaring a new one in this scope.
friend core::Executor& core::GetExecutor(Client& client);

struct Impl;
std::unique_ptr<Impl> m_impl;
};

} // namespace lootlocker
7 changes: 6 additions & 1 deletion include/lootlocker/result.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ struct Error {
std::string trace_id;

// From a Retry-After header, in seconds. 0 when absent.
int retry_after_seconds = 0;
//
// `retry_after_present` distinguishes "the server said 0" from "there was no header",
// because `Retry-After: 0` is a valid instruction to retry immediately and treating it
// as absent would apply the exponential back-off instead.
int retry_after_seconds = 0;
bool retry_after_present = false;

bool Ok() const { return code == ErrorCode::None; }
};
Expand Down
124 changes: 124 additions & 0 deletions src/core/client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#include <lootlocker/client.h>

#include <lootlocker/curl_http_transport.h>
#include <lootlocker/http_transport.h>
#include <lootlocker/log.h>

#include "clock.h"
#include "executor.h"

#include <utility>

namespace lootlocker {

struct Client::Impl {
Config config;
Error config_error;

// The default logger, owned here because `Config::logger` is a `weak_ptr` and the
// default has to live somewhere. Constructed lazily: a client that never logs should
// not pay for it.
std::shared_ptr<Logger> owned_logger;

// The default transport, owned here for the same reason. Empty when curl was not built
// in, which is a supported configuration: the adopter injects their own.
std::shared_ptr<IHttpTransport> owned_transport;

core::SteadyClock clock;
std::unique_ptr<core::Executor> executor;
};

namespace {

// The logger the client will use: the injected one if it is alive, otherwise the default.
std::weak_ptr<Logger> ResolveLogger(const Config& config, std::shared_ptr<Logger>& owned)
{
if (std::shared_ptr<Logger> injected = config.logger.lock()) {
return injected;
}
if (!owned) {
owned = std::make_shared<log::StderrLogger>(config.log_level);
}
return owned;
}

} // namespace

Client::Client(const Config& config) : m_impl(new Impl())
{
m_impl->config = config;
m_impl->config_error = ValidateConfig(config);

// A bad config leaves the client inert rather than half-built. The executor is still
// constructed so `Update()` and `Submit` behave predictably, but nothing is ever sent
// because every submission is rejected.
std::weak_ptr<Logger> logger = ResolveLogger(config, m_impl->owned_logger);

if (!m_impl->config_error.Ok()) {
if (std::shared_ptr<Logger> sink = logger.lock()) {
sink->Log(LogLevel::Error, "invalid configuration: " + m_impl->config_error.message);
}
}

// The transport: the injected one wins, otherwise the libcurl default when it was
// built. `Config::transport` is a `weak_ptr`, so an injected transport that has already
// died falls through to the default rather than leaving the client with nothing.
std::shared_ptr<IHttpTransport> transport = config.transport.lock();
if (!transport) {
#if defined(LOOTLOCKER_HAVE_CURL)
m_impl->owned_transport = std::make_shared<CurlHttpTransport>();
transport = m_impl->owned_transport;
#else
if (std::shared_ptr<Logger> sink = logger.lock()) {
sink->Log(LogLevel::Warning,
"no transport: libcurl was not built in and none was injected, so no "
"request can be sent");
}
#endif
}

m_impl->executor.reset(new core::Executor(config.queue, transport, m_impl->clock, logger,
m_impl->config_error));
}

Client::~Client() = default;

bool Client::Update()
{
// The executor is driven even when the config is invalid, because that is the only way
// a rejected request's handler ever runs. `Submit` on an invalid client rejects with
// `InvalidConfig` and queues the handler; skipping `Update()` here would leave those
// handlers stranded for ever, which is the opposite of what "inert" should mean.
return m_impl->executor->Update();
Comment thread
kirre-bylund marked this conversation as resolved.
Resolved
}

const Config& Client::GetConfig() const
{
return m_impl->config;
}

const Error& Client::ConfigError() const
{
return m_impl->config_error;
}

bool Client::SetTransport(std::weak_ptr<IHttpTransport> transport)
{
return m_impl->executor->SetTransport(std::move(transport));
}

std::weak_ptr<IHttpTransport> Client::GetTransport() const
{
return m_impl->executor->GetTransport();
}

namespace core {

Executor& GetExecutor(Client& client)
{
return *client.m_impl->executor;
}

} // namespace core

} // namespace lootlocker
43 changes: 43 additions & 0 deletions src/core/clock.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#pragma once

// The clock seam (D25, R26). Internal: `lootlocker::core::` is not on an adopter's include
// path (D18).
//
// The executor needs time for two things: back-off delays and request timeouts. Both are
// behaviour a test has to observe, and observing them against a wall clock means sleeping,
// which makes a suite slow and flaky. So time is read through this interface and a test
// advances a fake instead.
//
// This is deliberately NOT a `Config` seam. The four public seams exist because an adopter
// has to dock to their own ecosystem (challenge #5); nobody has asked to supply time, and
// `steady_clock` is monotonic on every platform we target. A seam with no consumer is a
// seam nobody maintains (D18). If a host with a fixed-timestep loop ever needs to drive
// time, that is a decision to take then.

#include <chrono>
#include <cstdint>

namespace lootlocker {
namespace core {

class Clock {
public:
virtual ~Clock() = default;

// Monotonic milliseconds. Never wall-clock: a system clock adjustment must not make a
// back-off fire early or a timeout fire late.
virtual std::int64_t NowMs() = 0;
};

class SteadyClock : public Clock {
public:
std::int64_t NowMs() override
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
};

} // namespace core
} // namespace lootlocker
Loading
Loading