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
23 changes: 23 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@ jobs:
with:
submodules: recursive

# libcurl is the default transport (D3). Installing it means the curl path is
# actually compiled and exercised on every target, rather than being dead code that
# only a downstream adopter discovers is broken.
- name: Install libcurl
shell: bash
run: |
set -e
if [ "$RUNNER_OS" = "Linux" ]; then
sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev
elif [ "$RUNNER_OS" = "macOS" ]; then
brew install curl
else
# windows-latest does NOT ship curl development files, only the CLI. vcpkg is
# the supported way to get headers and a lib on the runner.
vcpkg install curl:x64-windows
echo "CMAKE_TOOLCHAIN_FILE=$VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" >> "$GITHUB_ENV"
fi

- name: Configure
run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release

Expand Down Expand Up @@ -66,6 +84,11 @@ jobs:
with:
submodules: recursive

# The transport is part of core, so this job needs curl too - otherwise it would
# silently build a core without the default transport and prove less than it claims.
- name: Install libcurl
run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev

- name: Each module builds alone
run: |
set -e
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ out/
*.user
CMakeUserPresets.json
*.obj
CMakeFiles/
33 changes: 33 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ endif()
option(LOOTLOCKER_BUILD_TESTS "Build the SDK's own tests" ON)
option(LOOTLOCKER_BUILD_EXAMPLES "Build the examples" ON)

# The libcurl transport (D3).
#
# ON by default, but a missing curl is not an error: a console adopter injects its own
# transport and must not be forced to build curl, and a studio that vendors dependencies
# itself may already have one. When curl is absent the SDK still builds and the default
# transport is simply unavailable, which the client reports rather than crashing on.
option(LOOTLOCKER_WITH_CURL "Build the libcurl transport when curl is available" ON)

if(LOOTLOCKER_WITH_CURL)
find_package(CURL QUIET)
if(CURL_FOUND)
message(STATUS "libcurl ${CURL_VERSION_STRING} found: the default transport is available")
else()
message(STATUS "libcurl not found: the default transport is unavailable, inject your own")
endif()
endif()

# Regenerate the timezone table from data/windows-to-iana.tsv at BUILD time.
#
# OFF by default, and it must stay that way. The generator is Python, and requiring Python
Expand Down Expand Up @@ -121,7 +138,23 @@ add_library(lootlocker_core STATIC
src/core/log.cpp
src/core/text.cpp
src/core/config_obfuscation.cpp
src/core/header_map.cpp
)

# The curl transport is only compiled when curl was found AND the option is on. Both
# conditions matter: CURL_FOUND can already be true in a parent project or a reused
# configure, so gating on it alone would ignore the documented opt-out.
#
# LOOTLOCKER_HAVE_CURL is PUBLIC, not PRIVATE. The public header guards on it, so a
# consumer that includes `curl_http_transport.h` has to see the same value the library was
# built with - otherwise the class is undeclared for the adopter even though it exists in
# the binary, and the documented default transport cannot be constructed.
if(LOOTLOCKER_WITH_CURL AND CURL_FOUND)
target_sources(lootlocker_core PRIVATE src/core/curl_http_transport.cpp)
target_link_libraries(lootlocker_core PRIVATE CURL::libcurl)
target_compile_definitions(lootlocker_core PUBLIC LOOTLOCKER_HAVE_CURL)
endif()

add_library(LootLocker::core ALIAS lootlocker_core)

target_include_directories(lootlocker_core
Expand Down
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,102 @@ 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.

## The transport

The SDK never calls the network directly. Everything goes through `IHttpTransport`, and the
default implementation is libcurl.

### The interface

Three methods, and the contract is **pollable, not blocking**:

```cpp
class IHttpTransport {
public:
struct Request {
std::string method;
std::string url;
HeaderMap headers;
std::string body;
int timeout_seconds = 300;
};

struct Response {
int status_code = 0; // 0 = no response arrived at all
HeaderMap headers;
std::string body; // bytes, exactly as received
};

using TransferId = std::uint64_t;

virtual TransferId Start(const Request& request) = 0;
virtual bool Poll(TransferId id, Response& out) = 0;
virtual void Cancel(TransferId id) = 0;
};
```

`Start` returns immediately with a handle. `Poll` reports completion without waiting and is
called once per `Update()`. `Cancel` releases the transfer, and must be safe to call for one
that already finished.

A transport that blocks in `Poll` stalls the host's frame for the length of the transfer,
which is the one thing a game SDK must never do.

### Building with libcurl

libcurl is **optional**. It is on by default, but a missing curl is a status message rather
than a configure error:

```sh
cmake -S . -B build -DLOOTLOCKER_WITH_CURL=OFF # never look for curl
```

When curl is found, `LOOTLOCKER_HAVE_CURL` is defined publicly and `CurlHttpTransport` is
declared in `<lootlocker/curl_http_transport.h>`. When it is not, that header declares
nothing and the SDK still builds — you supply your own transport.

CI installs curl on all three targets, so the default path is compiled rather than being
dead code.

### Overriding it

Implement the interface, own it with a `shared_ptr`, and hand the SDK a `weak_ptr`:

```cpp
class MyTransport : public lootlocker::IHttpTransport {
// Start / Poll / Cancel
};

auto transport = std::make_shared<MyTransport>();

lootlocker::Config config;
config.transport = transport; // weak_ptr: you own it, the SDK observes it
```

The SDK uses it for every request. This is the seam a console uses: Sony and Nintendo ship
their own HTTP stacks, and curl needs porting to them.

**Why `weak_ptr` and not a raw pointer.** The adopter owns the object; the SDK only
observes it. A raw pointer would express that in a comment and nothing more, so an object
destroyed before the client would be a dangling dereference. With a `weak_ptr` the SDK
`lock()`s it per use, and if the object is gone it logs the fact and fails the call
gracefully instead of reading freed memory.

**The cost:** an injected object must be owned by a `shared_ptr`. A stack object cannot be
observed this way. That is the price of the safety, and it is why the example above
allocates.

`FakeHttpTransport` in `<lootlocker/fake_http_transport.h>` is a scriptable implementation
for tests. Transfers complete only when you say so, which makes the pollable contract
assertable without sleeping.

### One caveat: DNS

curl's default resolver is synchronous, so the first `Poll` for a hostname that is not
already cached can block for the length of the lookup. The transfer itself is pollable; the
name resolution is not. If that matters, resolve once at startup or inject a transport whose
resolver is asynchronous.

## What is in v1

Guest, white label and Steam authentication, plus broadcasts. Presence, offline mode,
Expand Down
29 changes: 21 additions & 8 deletions include/lootlocker/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <lootlocker/result.h>

#include <cstdint>
#include <memory>
#include <string>

namespace lootlocker {
Expand Down Expand Up @@ -58,8 +59,20 @@ struct RateLimitConfig {

// The only runtime input.
//
// A plain aggregate, so a game fills it directly. The injection pointers are not owned;
// null means "use the SDK default".
// A plain aggregate, so a game fills it directly.
//
// **The four injection seams are `weak_ptr`, not raw pointers.** The adopter owns their
// logger, state writer, transport and timezone provider; the SDK only observes them. A
// `weak_ptr` says exactly that, and it makes the dangerous case detectable: if the
// adopter's object dies while the client is still alive, `lock()` returns null and the
// SDK logs it and fails gracefully instead of dereferencing freed memory.
//
// The cost is that an injected object must be owned by a `shared_ptr`. A stack object
// cannot be observed this way, which is the price of the safety.
//
// `weak_ptr` rather than `shared_ptr` deliberately: a `shared_ptr` member would keep the
// object alive for the client's lifetime, which is ownership, not observation - and it
// would make the expiry check dead code.
struct Config {
// Required. There is no host to talk to without a domain key: the base URL is
// https://<domain_key>.api.lootlocker.com.
Expand All @@ -80,10 +93,10 @@ struct Config {
// Empty means derive from `domain_key`.
std::string base_url;

// Optional overrides. Not owned. Null means "use the SDK default".
Logger* logger = nullptr; // default writes to stderr
StateWriter* state_writer = nullptr; // default is FileStateWriter
IHttpTransport* transport = nullptr; // default is the libcurl one
// Optional overrides. Empty means "use the SDK default".
std::weak_ptr<Logger> logger; // default writes to stderr
std::weak_ptr<StateWriter> state_writer; // default is FileStateWriter
std::weak_ptr<IHttpTransport> transport; // default is the libcurl one
Comment thread
kirre-bylund marked this conversation as resolved.
Resolved

// The least-verbose level the SDK emits (D26).
//
Expand All @@ -99,13 +112,13 @@ struct Config {
// field, a platform API. The OS value is frequently not what the player chose.
std::string timezone;

// Supplies the player's timezone. Not owned. Null means "use the OS".
// Supplies the player's timezone. Empty means "use the OS".
//
// This is a seam for the same reason `state_writer` is: timezone and locale are both
// potentially user-configurable in a game, and every engine exposes them differently.
// The SDK's default reads the OS, which is right for a plain application and often
// wrong for a game whose player picked a timezone in a menu.
TimezoneProvider* timezone_provider = nullptr;
std::weak_ptr<TimezoneProvider> timezone_provider;

// False means send no timezone at all, so the server treats the player as UTC.
//
Expand Down
56 changes: 56 additions & 0 deletions include/lootlocker/curl_http_transport.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#pragma once

// The libcurl transport (D3).
//
// Only compiled when libcurl is found, because a console adopter injects its own transport
// and must not be forced to build curl. `LOOTLOCKER_HAVE_CURL` is defined by CMake when
// the dependency is present; without it this header declares nothing and the SDK still
// builds.
//
// The implementation is `curl_multi`, which is already pollable: `Start` adds an easy
// handle to the multi handle, `Poll` drives it without waiting, and `Cancel` removes it.
// That is why D3 chose curl - the interface shape is the library's native shape rather
// than something bolted on.

#include <lootlocker/http_transport.h>

#if defined(LOOTLOCKER_HAVE_CURL)

#include <cstdint>
#include <map>
#include <string>

namespace lootlocker {

class CurlHttpTransport : public IHttpTransport {
public:
CurlHttpTransport();
~CurlHttpTransport() override;

// Not copyable: it owns a curl multi handle and per-transfer state.
CurlHttpTransport(const CurlHttpTransport&) = delete;
CurlHttpTransport& operator=(const CurlHttpTransport&) = delete;

TransferId Start(const Request& request) override;
bool Poll(TransferId id, Response& out) override;
void Cancel(TransferId id) override;

// True when a transfer died at the curl level rather than returning a status. Exposed
// so a test can distinguish "no response yet" from "the transfer failed".
bool HadTransportError() const { return m_had_transport_error; }

private:
struct Transfer;

// Drives the multi handle once. Called from `Poll`, never blocks.
void Pump();

void* m_multi = nullptr; // CURLM*, void* so curl headers stay out of this header
TransferId m_next_id = 0;
std::map<TransferId, Transfer*> m_transfers;
bool m_had_transport_error = false;
};

} // namespace lootlocker

#endif // LOOTLOCKER_HAVE_CURL
Loading
Loading