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 @@ -142,6 +142,7 @@ add_library(lootlocker_core STATIC
src/core/request_id.cpp
src/core/rate_limiter.cpp
src/core/json.cpp
src/core/query_parameters.cpp
src/core/executor.cpp
src/core/client.cpp
)
Expand Down
77 changes: 74 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,24 +239,95 @@ struct PlayerStats {
std::string rank;
};

void from_json(const lootlocker::JsonValue& j, PlayerStats& out)
lootlocker::Result<lootlocker::Empty> from_json(const lootlocker::JsonValue& j,
PlayerStats& out)
{
// `IsUnsigned()` matters: reading a uint64 through AsDouble() loses precision above
// 2^53, which is the one hazard the JSON spike found.
if (j["total_score"].IsUnsigned()) {
out.total_score = j["total_score"].AsUInt64();
if (!j["total_score"].IsUnsigned()) {
lootlocker::Error e;
e.code = lootlocker::ErrorCode::MalformedResponse;
e.message = "total_score is missing or not an unsigned integer";
return lootlocker::Result<lootlocker::Empty>::Fail(e);
}
out.total_score = j["total_score"].AsUInt64();

// Every field is validated, not just the numeric one. `AsString()` on a missing or
// non-string value returns an empty string, so assigning it unchecked would turn "the
// server did not send this" into "the server sent an empty string" — the silent default
// the error model exists to prevent.
if (j["rank"].GetKind() != lootlocker::JsonValue::Kind::String) {
lootlocker::Error e;
e.code = lootlocker::ErrorCode::MalformedResponse;
e.message = "rank is missing or not a string";
return lootlocker::Result<lootlocker::Empty>::Fail(e);
}
out.rank = j["rank"].AsString();

return lootlocker::Result<lootlocker::Empty>::Ok(lootlocker::Empty());
}

} // namespace my_game
```

**`from_json` returns a `Result`, not `void`.** That is what lets a decoder say "this field
was absent" instead of silently defaulting it to zero — the failure mode the SDK's error
model exists to prevent. A decoder that has nothing to reject returns `Ok(Empty())`.

`JsonValue` gives you `GetKind()`, `IsInteger()`, `IsUnsigned()`, the typed `As*` reads,
`operator[]`, `HasKey()`, `Size()` and `At()`. An absent key is `Kind::Invalid`, which is
distinct from `Kind::Null` — so "the field is missing" and "the field is null" are different
answers, and you can tell them apart.

### Writing a request body

A request type with an ADL `to_json` sends its serialised form as the body, with
`Content-Type: application/json` set for you. A type without one sends no body, which is
what every GET does.

```cpp
namespace my_game {

struct SessionOptionals {
std::string timezone;
std::string player_name;
bool auto_create_profile = true;
};

void to_json(lootlocker::JsonBuilder& b, const SessionOptionals& in)
{
b.Set("timezone", in.timezone);
b.Set("player_name", in.player_name);
b.Set("auto_create_profile", in.auto_create_profile);
}

struct GuestSessionRequest {
std::string game_key;
std::string game_version;
std::string player_identifier;
SessionOptionals optionals;
};

void to_json(lootlocker::JsonBuilder& b, const GuestSessionRequest& in)
{
b.Set("game_key", in.game_key);
b.Set("game_version", in.game_version);
b.Set("player_identifier", in.player_identifier);
b.Set("optionals", in.optionals); // nested, through its own to_json
}

} // namespace my_game
```

`JsonBuilder` gives you `Set()` for strings, integers, unsigned integers, doubles and bools,
`SetNull()` for an explicit JSON null, and a `Set()` overload that takes any type with its
own `to_json`. Keys serialise in sorted order, because a JSON object is unordered by
definition.

`JsonBuilder` is a separate type from `JsonValue` on purpose: `JsonValue` is a read handle
over a shared, immutable document, which is what makes it cheap to pass around and safe to
hold across a callback. Writing needs its own type.

### There is no parser seam

Unlike the transport or the state writer, the JSON parser is not injectable. It is internal
Expand Down
9 changes: 9 additions & 0 deletions include/lootlocker/client.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <lootlocker/result.h>

#include <memory>
#include <string>

namespace lootlocker {

Expand Down Expand Up @@ -70,6 +71,14 @@ class Client {
// injected.
std::weak_ptr<IHttpTransport> GetTransport() const;

// A per-client identifier, sent as `LL-Instance-Identifier`.
//
// Generated once when the client is constructed and stable for its lifetime, so the
// backend can tell two clients in one process apart (D20) and a support ticket can be
// tied to a session. Not a security token: it identifies a client instance, nothing
// more.
const std::string& GetInstanceIdentifier() 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.
Expand Down
84 changes: 84 additions & 0 deletions include/lootlocker/json_builder.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#pragma once

// A parser-independent JSON writer (D4, D27).
//
// The counterpart to `JsonValue`: that one reads a decoded document, this one builds a
// request body. Both are handles over an opaque implementation, so the chosen JSON library
// stays behind the pimpl and swapping it is not a breaking change.
//
// Deliberately a separate type rather than a mutable `JsonValue`. A `JsonValue` is a path
// into a shared, immutable document, which is what makes it cheap to pass around and safe
// to hold across a callback. Making it writable would mean either copying the document on
// every write or giving up that sharing - so the two roles get two types.
//
// An adopter writes a `to_json` next to their type, exactly as they write a `from_json`:
//
// void to_json(lootlocker::JsonBuilder& b, const MyRequest& in)
// {
// b.Set("name", in.name);
// b.Set("score", in.score);
// }
//
// and `core::Send<Definition>()` finds it by ADL and sends the result as the body.

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

namespace lootlocker {

class JsonBuilder {
public:
// An empty object. A request body is always an object at the root.
JsonBuilder();
~JsonBuilder();

JsonBuilder(JsonBuilder&&) noexcept;
JsonBuilder& operator=(JsonBuilder&&) noexcept;

JsonBuilder(const JsonBuilder&) = delete;
JsonBuilder& operator=(const JsonBuilder&) = delete;

void Set(const std::string& key, const std::string& value);

// A string literal must not fall through to the `bool` overload. Without this,
// `Set("name", "abc")` picks `bool`, because `const char*` to `bool` is a standard
// conversion and to `std::string` is a user-defined one - so the literal silently
// becomes `true`. The same trap as `QueryParameters::Add`.
void Set(const std::string& key, const char* value);

void Set(const std::string& key, int value);
void Set(const std::string& key, std::int64_t value);
void Set(const std::string& key, std::uint64_t value);
void Set(const std::string& key, double value);
void Set(const std::string& key, bool value);

// An explicit JSON null, which is different from omitting the key. The API treats
// `"optionals": null` and an absent `optionals` the same way, but a field that is
// genuinely nullable needs to be expressible.
void SetNull(const std::string& key);

// A nested object, serialised through the type's ADL `to_json`.
template <typename T>
void Set(const std::string& key, const T& value)
{
JsonBuilder child;
to_json(child, value);
SetValue(key, std::move(child));
}

// The serialised object. Never throws: invalid UTF-8 in a string is replaced rather
// than aborting, because the build has exceptions disabled and a player name is not
// worth terminating the process over.
std::string ToJson() const;

private:
// Attaches an already-built child under `key`. Out of line because it moves the
// underlying document, which only this translation unit's implementation knows about.
void SetValue(const std::string& key, JsonBuilder&& child);

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

} // namespace lootlocker
38 changes: 38 additions & 0 deletions src/core/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#include "clock.h"
#include "executor.h"

#include <cstdio>
#include <random>
#include <utility>

namespace lootlocker {
Expand All @@ -15,6 +17,10 @@ struct Client::Impl {
Config config;
Error config_error;

// Sent as `LL-Instance-Identifier`. Generated once, at construction, so it is stable for
// the client's lifetime and two clients in one process differ (D20).
std::string instance_identifier;

// 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.
Expand All @@ -30,6 +36,32 @@ struct Client::Impl {

namespace {

// A random identifier for `LL-Instance-Identifier`.
//
// Not a security token, so `std::random_device` is the right tool rather than a
// cryptographic generator: it only has to be unlikely to collide between two clients in one
// process. Formatted as a UUID-shaped string because that is what the other SDKs send and
// what the backend's tracing expects to log.
std::string MakeInstanceIdentifier()
{
std::random_device device;
std::uint64_t high = (static_cast<std::uint64_t>(device()) << 32) ^ device();
std::uint64_t low = (static_cast<std::uint64_t>(device()) << 32) ^ device();

// Version 4, variant 1, so it reads as a UUID rather than as arbitrary hex.
high = (high & 0xFFFFFFFFFFFF0FFFULL) | 0x0000000000004000ULL;
low = (low & 0x3FFFFFFFFFFFFFFFULL) | 0x8000000000000000ULL;

char buffer[37];
std::snprintf(buffer, sizeof(buffer), "%08x-%04x-%04x-%04x-%012llx",
static_cast<unsigned>((high >> 32) & 0xFFFFFFFFULL),
static_cast<unsigned>((high >> 16) & 0xFFFFULL),
static_cast<unsigned>(high & 0xFFFFULL),
static_cast<unsigned>((low >> 48) & 0xFFFFULL),
static_cast<unsigned long long>(low & 0xFFFFFFFFFFFFULL));
return std::string(buffer);
}

// 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)
{
Expand All @@ -48,6 +80,7 @@ Client::Client(const Config& config) : m_impl(new Impl())
{
m_impl->config = config;
m_impl->config_error = ValidateConfig(config);
m_impl->instance_identifier = MakeInstanceIdentifier();

// 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
Expand Down Expand Up @@ -129,6 +162,11 @@ std::weak_ptr<IHttpTransport> Client::GetTransport() const
return m_impl->executor->GetTransport();
}

const std::string& Client::GetInstanceIdentifier() const
{
return m_impl->instance_identifier;
}

namespace core {

Executor& GetExecutor(Client& client)
Expand Down
Loading
Loading