diff --git a/CMakeLists.txt b/CMakeLists.txt index 44f315f..1e837b4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 ) diff --git a/README.md b/README.md index be832b7..3dcfccf 100644 --- a/README.md +++ b/README.md @@ -239,24 +239,95 @@ struct PlayerStats { std::string rank; }; -void from_json(const lootlocker::JsonValue& j, PlayerStats& out) +lootlocker::Result 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::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::Fail(e); } out.rank = j["rank"].AsString(); + + return lootlocker::Result::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 diff --git a/include/lootlocker/client.h b/include/lootlocker/client.h index 3257730..8c7bf28 100644 --- a/include/lootlocker/client.h +++ b/include/lootlocker/client.h @@ -10,6 +10,7 @@ #include #include +#include namespace lootlocker { @@ -70,6 +71,14 @@ class Client { // injected. std::weak_ptr 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. diff --git a/include/lootlocker/json_builder.h b/include/lootlocker/json_builder.h new file mode 100644 index 0000000..380d953 --- /dev/null +++ b/include/lootlocker/json_builder.h @@ -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()` finds it by ADL and sends the result as the body. + +#include +#include +#include + +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 + 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 m_impl; +}; + +} // namespace lootlocker diff --git a/src/core/client.cpp b/src/core/client.cpp index 9ccb7af..f9c4033 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -7,6 +7,8 @@ #include "clock.h" #include "executor.h" +#include +#include #include namespace lootlocker { @@ -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. @@ -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(device()) << 32) ^ device(); + std::uint64_t low = (static_cast(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((high >> 32) & 0xFFFFFFFFULL), + static_cast((high >> 16) & 0xFFFFULL), + static_cast(high & 0xFFFFULL), + static_cast((low >> 48) & 0xFFFFULL), + static_cast(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 ResolveLogger(const Config& config, std::shared_ptr& owned) { @@ -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 @@ -129,6 +162,11 @@ std::weak_ptr 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) diff --git a/src/core/definition.h b/src/core/definition.h new file mode 100644 index 0000000..cd854ef --- /dev/null +++ b/src/core/definition.h @@ -0,0 +1,259 @@ +#pragma once + +// The endpoint definition layer (T13). Internal: `lootlocker::core::` is not on an +// adopter's include path (D18). +// +// A definition is the internal unit of modularity. It carries everything the generic +// executor needs for one endpoint and nothing else: the wire contract (`kMethod`, `kPath`), +// the request and response types, and the three hooks D27 specifies. Retry policy, rate +// limiting, session refresh and logging are deliberately absent - they are the executor's +// job and identical for every endpoint. +// +// `Send()` is the only entry point. It is a free function rather than a `Client` +// member for the same reason the modules are free functions: a member would make `core` +// depend on every module's definitions. + +#include +#include +#include +#include +#include +#include +#include + +#include "executor.h" +#include "json.h" +#include "query_parameters.h" + +#include +#include +#include +#include +#include + +namespace lootlocker { +namespace core { + +// The response as it arrived, before any decoding. +// +// Passed to `NormalizeResponse` alongside the decoded value, because the decoded form is +// not always enough: classifying a discriminated-union field needs the raw JSON token, not +// a struct (D27). +struct RawResponse { + int status_code = 0; + HeaderMap headers; + std::string body; +}; + +// What a definition must provide. Checked at compile time rather than documented, because +// a missing hook would otherwise be a link error inside a template instantiation, which is +// the least readable failure the SDK can produce. +// +// `NormalizeResponse` is optional: a definition whose response needs no convenience simply +// omits it, and the trait below detects that. The other two are required. +template +struct HasNormalizeResponse : std::false_type {}; + +template +struct HasNormalizeResponse< + Def, decltype(static_cast( + &Def::NormalizeResponse))> : std::true_type {}; + +// Calls `NormalizeResponse` when the definition has one, and does nothing when it does not. +template +typename std::enable_if::value>::type Normalize( + typename Def::Response& response, const RawResponse& raw) +{ + Def::NormalizeResponse(response, raw); +} + +template +typename std::enable_if::value>::type Normalize( + typename Def::Response&, const RawResponse&) +{ +} + +// Whether a request type has an ADL `to_json`, which is what decides if the request carries +// a body (D27, owner 2026-11-25). +// +// The body is a property of the request type, not a hook on the definition, for the same +// reason `from_json` is: a nested type that appears in several bodies - `optionals` in every +// session start - needs one serialiser, and a definition hook would still have to call it. +// One mechanism throughout. +// +// Detected rather than required, so a GET definition needs nothing: no `to_json`, no body, +// no `Content-Type`. +template +struct HasToJson : std::false_type {}; + +template +struct HasToJson(), std::declval()), + void())> : std::true_type {}; + +// Serialises `request` into a body, or returns an empty string when the type has no +// `to_json`. +template +typename std::enable_if::value, std::string>::type BuildBody(const T& request) +{ + JsonBuilder builder; + to_json(builder, request); + return builder.ToJson(); +} + +template +typename std::enable_if::value, std::string>::type BuildBody(const T&) +{ + return std::string(); +} + +// The callback a caller supplies. Takes the `Result` by value, so a lambda, a +// `std::function` or a member-function wrapper all work. +template +using ResponseCallback = std::function)>; + +// Builds the URL for one request: base, path, then the definition's query parameters. +// +// Exposed rather than file-local because the tests assert on it directly, and because a +// definition's query construction is the part most likely to be wrong. +template +std::string BuildUrl(const Client& client, const typename Def::Request& request) +{ + std::string url = client.GetConfig().ResolveBaseUrl(); + url += Def::kPath; + + QueryParameters query; + Def::ConstructQueryParameters(request, query); + if (!query.Empty()) { + url.push_back('?'); + url += query.ToQueryString(); + } + return url; +} + +// The headers every request carries, before the definition adds its own. +// +// `LL-Version` is pinned rather than omitted. The backend defaults a missing header to +// `2021-03-01`, the oldest API version, so omitting it would silently opt every adopter +// into the oldest behaviour. Pinning it makes the version the SDK targets explicit and +// makes a future bump a one-line change here. +// +// `LL-SDK-Version` and `LL-Instance-Identifier` match the other SDKs, and the backend's +// tracing middleware reads both: without them every request is attributed to "unknown" and +// a support ticket cannot be tied to a session. The instance identifier is per-client and +// per-process, so two clients in one process are distinguishable (D20). +// +// `x-session-token` is deliberately absent: there is no session yet (T14). It is added by +// the executor once one exists, not by a definition, because it is identical for every +// endpoint. +// +// `is-development` is deliberately NOT here. It is read only on the white-label login path, +// so it belongs in that definition's `ConstructHeaders` rather than on every request. +inline HeaderMap BuildDefaultHeaders(const Client& client) +{ + HeaderMap headers; + + headers.Set("LL-Version", "2021-03-01"); + headers.Set("LL-SDK-Version", GetVersionString()); + headers.Set("LL-Instance-Identifier", client.GetInstanceIdentifier()); + headers.Set("Accept", "application/json"); + headers.Set("User-Agent", std::string("LootLocker-Cpp-SDK/") + GetVersionString()); + + return headers; +} + +// Sends one request described by `Def` and delivers the decoded response to `on_done`. +// +// Returns the id the executor assigned, which is the same id sent as `LL-Request-Id`. The +// callback never runs synchronously: it fires on the thread that calls `Client::Update()` +// (D5), including when the request is rejected outright. +// +// **The body comes from the request type's ADL `to_json`, when it has one.** A type without +// one sends no body and no `Content-Type`, which is what keeps every GET definition +// unchanged. `Content-Type` is set here rather than by a definition, because a body without +// it is a request the server rejects and no definition should have to remember. +template +RequestId Send(Client& client, const typename Def::Request& request, + ResponseCallback on_done) +{ + PendingRequest pending; + pending.method = Def::kMethod; + pending.url = BuildUrl(client, request); + pending.headers = BuildDefaultHeaders(client); + pending.body = BuildBody(request); + + if (!pending.body.empty()) { + pending.headers.Set("Content-Type", "application/json"); + } + + // The definition's own headers come last, so an endpoint can override a default rather + // than being stuck with it. + Def::ConstructHeaders(request, pending.headers); + + return GetExecutor(client).Submit( + std::move(pending), [on_done](const Completion& completion) { + if (!completion.error.Ok()) { + on_done(Result::Fail(completion.error, completion.body)); + return; + } + + // A 204 is the one legitimate empty success (`EndSession`), and the executor + // documents it as such. Parsing an empty body would report `MalformedResponse` + // for a request that succeeded, so it is handled before the parser sees it. + // + // `NormalizeResponse` still runs, because a definition may want to fill in + // derived fields on an empty response too. + if (completion.status_code == 204 || completion.body.empty()) { + typename Def::Response response; + + RawResponse raw; + raw.status_code = completion.status_code; + raw.headers = completion.headers; + raw.body = completion.body; + + Normalize(response, raw); + + on_done(Result::Ok(std::move(response), completion.body)); + return; + } + + Result parsed = ParseJson(completion.body); + if (!parsed.Ok()) { + // A body that is not JSON at all. The parse error carries the parser's + // message, but the transport metadata is the executor's and must survive: + // `request_id` is what ties the failure to a server log line, and + // `status_code` is what tells the caller the request was actually answered. + // Only the code and message are replaced. + Error error = completion.error; + error.code = parsed.Error().code; + error.message = parsed.Error().message; + error.status_code = completion.status_code; + on_done(Result::Fail(std::move(error), completion.body)); + return; + } + + typename Def::Response response; + Result decoded = DecodeJson(parsed.Value(), response); + if (!decoded.Ok()) { + // Same reasoning: keep the transport metadata, replace only the decode + // failure. + Error error = completion.error; + error.code = decoded.Error().code; + error.message = decoded.Error().message; + error.status_code = completion.status_code; + on_done(Result::Fail(std::move(error), completion.body)); + return; + } + + RawResponse raw; + raw.status_code = completion.status_code; + raw.headers = completion.headers; + raw.body = completion.body; + + Normalize(response, raw); + + on_done(Result::Ok(std::move(response), completion.body)); + }); +} + +} // namespace core +} // namespace lootlocker diff --git a/src/core/json.cpp b/src/core/json.cpp index 4f5e871..8bf4ddb 100644 --- a/src/core/json.cpp +++ b/src/core/json.cpp @@ -5,6 +5,8 @@ #include "json.h" +#include + // `JSON_NOEXCEPTION` makes the library's throwing paths abort rather than throw, and // `parse(..., allow_exceptions = false)` returns a discarded value instead. Both are // required: the build has exceptions disabled (`/EHs-c-`), so a `try`/`catch` here would @@ -319,3 +321,86 @@ std::string SerializeJson(const JsonValue& value) } // namespace core } // namespace lootlocker + +// --------------------------------------------------------------------------- +// JsonBuilder (T13d) +// --------------------------------------------------------------------------- +// +// In this translation unit for the same reason as everything above: it is the only one that +// includes the JSON library (D4, D18). + +namespace lootlocker { + +struct JsonBuilder::Impl { + nlohmann::json document = nlohmann::json::object(); +}; + +JsonBuilder::JsonBuilder() : m_impl(new Impl()) {} +JsonBuilder::~JsonBuilder() = default; +JsonBuilder::JsonBuilder(JsonBuilder&&) noexcept = default; +JsonBuilder& JsonBuilder::operator=(JsonBuilder&&) noexcept = default; + +void JsonBuilder::Set(const std::string& key, const std::string& value) +{ + m_impl->document[key] = value; +} + +void JsonBuilder::Set(const std::string& key, const char* value) +{ + // A null `const char*` becomes JSON null rather than an empty string: they are different + // answers, and silently turning one into the other is how a caller loses a distinction + // they cared about. + if (value == nullptr) { + SetNull(key); + return; + } + m_impl->document[key] = std::string(value); +} + +void JsonBuilder::Set(const std::string& key, int value) +{ + m_impl->document[key] = value; +} + +void JsonBuilder::Set(const std::string& key, std::int64_t value) +{ + m_impl->document[key] = value; +} + +void JsonBuilder::Set(const std::string& key, std::uint64_t value) +{ + // Assigned as unsigned, so nlohmann stores `number_unsigned` and a value above 2^63 + // round-trips. Assigning through `int64_t` would wrap it negative. + m_impl->document[key] = value; +} + +void JsonBuilder::Set(const std::string& key, double value) +{ + m_impl->document[key] = value; +} + +void JsonBuilder::Set(const std::string& key, bool value) +{ + m_impl->document[key] = value; +} + +void JsonBuilder::SetNull(const std::string& key) +{ + m_impl->document[key] = nullptr; +} + +void JsonBuilder::SetValue(const std::string& key, JsonBuilder&& child) +{ + m_impl->document[key] = std::move(child.m_impl->document); +} + +std::string JsonBuilder::ToJson() const +{ + // `dump` with `error_handler_t::replace` rather than the default. The default throws on + // invalid UTF-8, and with `JSON_NOEXCEPTION` a throw is an abort - so a player name with + // a stray byte would terminate the process. Replacing the bad sequence sends a body the + // server can reject with a clear message instead. + return m_impl->document.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); +} + +} // namespace lootlocker diff --git a/src/core/json.h b/src/core/json.h index 08bd1f1..3b2f120 100644 --- a/src/core/json.h +++ b/src/core/json.h @@ -31,5 +31,21 @@ Result ParseJson(const std::string& text); // the original bytes (D7). std::string SerializeJson(const JsonValue& value); +// Decodes `value` into `out` through the type's ADL `from_json` (D27). +// +// **`from_json` returns `Result`, not `void`.** The api-sketch draws it as `void`, +// which cannot express D23's rule that a missing field is a decode error rather than a +// zero: a `void` decoder has no way to say "this field was absent". Returning a `Result` +// is the smallest change that makes the rule enforceable, and it costs a decoder nothing +// when it succeeds. +// +// Found by ADL rather than by a trait, so a decoder lives next to its type and a type in +// another namespace works without registration. +template +Result DecodeJson(const JsonValue& value, T& out) +{ + return from_json(value, out); +} + } // namespace core } // namespace lootlocker diff --git a/src/core/query_parameters.cpp b/src/core/query_parameters.cpp new file mode 100644 index 0000000..c391133 --- /dev/null +++ b/src/core/query_parameters.cpp @@ -0,0 +1,168 @@ +#include "query_parameters.h" + +#include +#include +#include + +namespace lootlocker { +namespace core { + +namespace { + +// RFC 3986 unreserved characters are passed through; everything else is percent-encoded. +// +// Deliberately conservative: a space becomes `%20` rather than `+`. `+` is only a space in +// `application/x-www-form-urlencoded`, and a query string is not that, so encoding a space +// as `+` would be wrong for a value that legitimately contains a plus sign. +bool IsUnreserved(unsigned char c) +{ + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == '~'; +} + +std::string PercentEncode(const std::string& value) +{ + static const char* kHex = "0123456789ABCDEF"; + + std::string out; + out.reserve(value.size()); + + for (std::size_t i = 0; i < value.size(); ++i) { + const unsigned char c = static_cast(value[i]); + if (IsUnreserved(c)) { + out.push_back(static_cast(c)); + } else { + out.push_back('%'); + out.push_back(kHex[(c >> 4) & 0x0F]); + out.push_back(kHex[c & 0x0F]); + } + } + return out; +} + +// A double, formatted so it round-trips and never picks up a locale's decimal comma. +// +// `snprintf`'s `%g` is governed by the process-wide C locale, so in a locale with a decimal +// comma `1.5` would become `1,5` and then `%2C` on the wire - a different number. Rather +// than calling `setlocale` (which would change global process state and is not ours to +// touch), the digits are produced with `%g` and then any locale-specific separator is +// normalised back to '.'. +// +// `%g` with 17 significant digits is the shortest form that round-trips an IEEE double. +// `std::to_string` is not used because it always emits six decimals, which turns `1` into +// `1.000000` and a limit of `1.5` into `1.500000` - both wrong on the wire. +std::string FormatDouble(double value) +{ + if (!std::isfinite(value)) { + // A NaN or an infinity cannot be expressed in a query string. Sending "nan" would + // be a request the server rejects with a confusing message; sending nothing is + // worse. An empty value is the honest answer and the server's validation reports + // it. + return std::string(); + } + + // The locale's decimal separator, whatever it is. `localeconv` is the only portable way + // to ask, and it is read-only. + const char* decimal_point = std::localeconv()->decimal_point; + const std::string separator = + (decimal_point == nullptr || *decimal_point == '\0') ? std::string(".") : std::string(decimal_point); + + // `%.17g` is exact but noisy: 0.1 prints as 0.10000000000000001. Trim to the shortest + // representation that still round-trips, by trying progressively shorter precisions. + for (int precision = 1; precision <= 17; ++precision) { + char candidate[64]; + std::snprintf(candidate, sizeof(candidate), "%.*g", precision, value); + + std::string text(candidate); + + // Normalise the separator to '.', which is what JSON and query strings require. + if (separator != ".") { + const std::size_t at = text.find(separator); + if (at != std::string::npos) { + text.replace(at, separator.size(), "."); + } + } + + double reparsed = 0.0; + if (std::sscanf(text.c_str(), "%lf", &reparsed) == 1 && reparsed == value) { + return text; + } + } + + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%.17g", value); + std::string text(buffer); + if (separator != ".") { + const std::size_t at = text.find(separator); + if (at != std::string::npos) { + text.replace(at, separator.size(), "."); + } + } + return text; +} + +} // namespace + +void QueryParameters::Add(const std::string& name, const std::string& value) +{ + Entry entry; + entry.name = name; + entry.value = value; + m_entries.push_back(entry); +} + +void QueryParameters::Add(const std::string& name, const char* value) +{ + Add(name, std::string(value == nullptr ? "" : value)); +} + +void QueryParameters::Add(const std::string& name, int value) +{ + Add(name, static_cast(value)); +} + +void QueryParameters::Add(const std::string& name, std::int64_t value) +{ + // `%lld` rather than `std::to_string`, which is locale-independent for integers but + // allocates twice. This is not a hot path, but the cast is needed either way. + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%lld", static_cast(value)); + Add(name, std::string(buffer)); +} + +void QueryParameters::Add(const std::string& name, std::uint64_t value) +{ + // `%llu`, not a cast to `int64_t`: a value above 2^63 would wrap negative. + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%llu", static_cast(value)); + Add(name, std::string(buffer)); +} + +void QueryParameters::Add(const std::string& name, double value) +{ + Add(name, FormatDouble(value)); +} + +void QueryParameters::Add(const std::string& name, bool value) +{ + // The API expects `true`/`false`, not `1`/`0`. Both are accepted by most endpoints, but + // the documented form is the one to send. + Add(name, std::string(value ? "true" : "false")); +} + +std::string QueryParameters::ToQueryString() const +{ + std::string out; + for (std::size_t i = 0; i < m_entries.size(); ++i) { + if (i != 0) { + out.push_back('&'); + } + out += PercentEncode(m_entries[i].name); + out.push_back('='); + out += PercentEncode(m_entries[i].value); + } + return out; +} + +} // namespace core +} // namespace lootlocker diff --git a/src/core/query_parameters.h b/src/core/query_parameters.h new file mode 100644 index 0000000..97b4373 --- /dev/null +++ b/src/core/query_parameters.h @@ -0,0 +1,57 @@ +#pragma once + +// Query parameters for one request (T13). Internal: `lootlocker::core::` is not on an +// adopter's include path (D18). +// +// Typed rather than a string map, because a definition knows the type of each parameter and +// a generic map would throw that away at the call site. Insertion-ordered, because the API +// documents parameter order and some proxies care. + +#include +#include +#include +#include + +namespace lootlocker { +namespace core { + +class QueryParameters { +public: + void Add(const std::string& name, const std::string& value); + + // A string literal must not fall through to the `bool` overload. + // + // Without this, `Add("name", "abc")` picks `bool`: `const char*` to `bool` is a standard + // conversion and `const char*` to `std::string` is a user-defined one, so the literal + // silently becomes `true`. That is a wrong request with no diagnostic, which is the + // worst kind of bug to ship. + void Add(const std::string& name, const char* value); + + void Add(const std::string& name, int value); + void Add(const std::string& name, std::int64_t value); + + // A `uint64` needs its own overload. Without it the call is ambiguous between + // `std::int64_t` and `bool` on the usual platforms, so a definition could not add an + // unsigned wire id at all - and the SDK's ids are `uint64` end to end. + void Add(const std::string& name, std::uint64_t value); + + void Add(const std::string& name, double value); + void Add(const std::string& name, bool value); + + // Percent-encoded, joined with '&', no leading '?'. Empty when nothing was added. + std::string ToQueryString() const; + + std::size_t Size() const { return m_entries.size(); } + bool Empty() const { return m_entries.empty(); } + +private: + struct Entry { + std::string name; + std::string value; + }; + + std::vector m_entries; +}; + +} // namespace core +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9e3ae46..27ca845 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -67,6 +67,14 @@ target_link_libraries(test_json PRIVATE LootLocker::core lootlocker_compile_opti target_include_directories(test_json PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME json COMMAND test_json) +# The endpoint definition layer (T13). `src/core` is on the include path because the +# definition type and `Send()` are internal (D18) - an adopter reaches them +# through a module's typed wrapper, not directly. +add_executable(test_definition test_definition.cpp) +target_link_libraries(test_definition PRIVATE LootLocker::core lootlocker_compile_options) +target_include_directories(test_definition PRIVATE ${CMAKE_SOURCE_DIR}/src/core) +add_test(NAME definition COMMAND test_definition) + # 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_definition.cpp b/tests/test_definition.cpp new file mode 100644 index 0000000..2fe44ca --- /dev/null +++ b/tests/test_definition.cpp @@ -0,0 +1,815 @@ +// The endpoint definition layer (T13). +// +// The worked `ListBroadcastsDef` from the api-sketch is reproduced here, because the task's +// verification is that it compiles and that its typed wrapper returns the same `RequestId` +// the executor assigned. Everything else in this file exists to prove the generic executor +// actually consumes the definition rather than merely accepting it. +// +// The types live in their real namespaces rather than an anonymous one, because that is +// what a module target does: `from_json` is found by ADL, so it has to sit next to its type. + +#include +#include +#include +#include +#include +#include +#include + +#include "definition.h" +#include "query_parameters.h" + +#include "test_harness.h" + +#include +#include +#include +#include + +namespace lootlocker { + +// --- the worked definition's types, from api-sketch.md --------------------- + +struct Broadcast { + std::string id; + std::string message; +}; + +struct ListBroadcastsRequest { + int limit = 0; + std::string accept_language; +}; + +struct ListBroadcastsResponse { + std::vector broadcasts; +}; + +// The ADL decoder for the response type (D27). Returns a `Result` rather than `void` so a +// missing field is an error rather than a silent default (D23). +Result from_json(const JsonValue& j, ListBroadcastsResponse& out) +{ + if (j.GetKind() != JsonValue::Kind::Object) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "broadcasts response is not an object"; + return Result::Fail(e); + } + + const JsonValue list = j["broadcasts"]; + if (list.GetKind() != JsonValue::Kind::Array) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "broadcasts is missing or not an array"; + return Result::Fail(e); + } + + out.broadcasts.clear(); + for (std::size_t i = 0; i < list.Size(); ++i) { + const JsonValue item = list.At(i); + + // Each field is validated, not just the array. `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 D23 exists to prevent. A decoder that skipped this would make the + // generic layer look correct while proving nothing. + if (item["id"].GetKind() != JsonValue::Kind::String) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "a broadcast is missing a string id"; + return Result::Fail(e); + } + if (item["message"].GetKind() != JsonValue::Kind::String) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "a broadcast is missing a string message"; + return Result::Fail(e); + } + + Broadcast b; + b.id = item["id"].AsString(); + b.message = item["message"].AsString(); + out.broadcasts.push_back(b); + } + return Result::Ok(Empty()); +} + +namespace core { + +struct ListBroadcastsDef { + static constexpr const char* kMethod = "GET"; + static constexpr const char* kPath = "/game/broadcasts/v1"; + + using Request = ListBroadcastsRequest; + using Response = ListBroadcastsResponse; + + static void ConstructQueryParameters(const Request& r, QueryParameters& out) + { + out.Add("limit", r.limit); + } + + static void ConstructHeaders(const Request& r, HeaderMap& out) + { + if (!r.accept_language.empty()) { + out.Set("Accept-Language", r.accept_language); + } + } + + // Deliberately omitted: this definition has no endpoint-specific convenience, which is + // what proves `NormalizeResponse` is optional rather than required. +}; + +} // namespace core +} // namespace lootlocker + +namespace { + +using lootlocker::Broadcast; +using lootlocker::Client; +using lootlocker::Config; +using lootlocker::Empty; +using lootlocker::ErrorCode; +using lootlocker::FakeHttpTransport; +using lootlocker::IHttpTransport; +using lootlocker::JsonValue; +using lootlocker::ListBroadcastsRequest; +using lootlocker::ListBroadcastsResponse; +using lootlocker::RequestId; +using lootlocker::Result; +using lootlocker::core::ListBroadcastsDef; + +// --- helpers --------------------------------------------------------------- + +Config MakeConfig() +{ + Config config; + config.domain_key = "testdomain"; + config.game_key = "testgamekey"; + config.game_version = "1.0.0"; + return config; +} + +// A client wired to a fake transport the test keeps alive. +struct Fixture { + std::shared_ptr transport; + std::unique_ptr client; + + Fixture() + { + transport = std::make_shared(); + Config config = MakeConfig(); + config.transport = transport; + client.reset(new Client(config)); + } + + // The request the transport was first asked to start. + const IHttpTransport::Request* Sent() const + { + if (transport->Order().empty()) { + return nullptr; + } + return transport->FindRequest(transport->Order().front()); + } +}; + +// --- tests ----------------------------------------------------------------- + +// The task's stated verification: the typed wrapper returns the id the executor assigned. +void TestTypedWrapperReturnsExecutorId() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 10; + + const RequestId returned = lootlocker::core::Send( + *f.client, request, [](Result) {}); + + CHECK(returned.IsValid()); + + // The executor assigned this id, and the request is queued under it rather than sent: + // nothing moves until `Update()` (D5). + CHECK_EQ_INT(static_cast(lootlocker::core::GetExecutor(*f.client).QueuedCount()), + 1); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 0); +} + +// The definition's method, path and query parameters reach the wire. +void TestDefinitionBuildsTheRequest() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 25; + request.accept_language = "sv-SE"; + + lootlocker::core::Send(*f.client, request, + [](Result) {}); + f.client->Update(); + + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 1); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK_EQ(sent->method, "GET"); + CHECK_EQ(sent->url, "https://testdomain.api.lootlocker.com/game/broadcasts/v1?limit=25"); + + std::string value; + CHECK(sent->headers.Get("Accept-Language", value)); + CHECK_EQ(value, "sv-SE"); +} + +// The default headers are present on every request, and the definition's own headers do not +// displace them. +void TestDefaultHeaders() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + lootlocker::core::Send(*f.client, request, + [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + std::string value; + CHECK(sent->headers.Get("LL-Version", value)); + CHECK_EQ(value, "2021-03-01"); + + CHECK(sent->headers.Get("Accept", value)); + CHECK_EQ(value, "application/json"); + + CHECK(sent->headers.Get("User-Agent", value)); + CHECK(value.find("LootLocker-Cpp-SDK/") == 0); + + // Not development, so the header is absent rather than "false". + CHECK(!sent->headers.Has("is-development")); + + // No session yet (T14), so no token is sent. + CHECK(!sent->headers.Has("x-session-token")); +} + +// A successful response is decoded through the type's ADL `from_json` and delivered with the +// raw body intact (D7). +void TestSuccessfulDecode() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 5; + + std::vector received; + bool called = false; + std::string raw; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + CHECK(result.Ok()); + if (result.Ok()) { + received = result.Value().broadcasts; + } + raw = result.RawBody(); + }); + + f.client->Update(); + const std::string body = + R"({"broadcasts":[{"id":"a","message":"hello"},{"id":"b","message":"world"}]})"; + f.transport->Complete(f.transport->Order().front(), 200, body); + f.client->Update(); + + CHECK(called); + CHECK_EQ_INT(static_cast(received.size()), 2); + if (received.size() == 2) { + CHECK_EQ(received[0].id, "a"); + CHECK_EQ(received[1].message, "world"); + } + CHECK_EQ(raw, body); +} + +// A body that is not JSON is a `MalformedResponse` carrying the original bytes, not a crash +// and not an empty value (D23). +void TestMalformedBody() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 5; + + bool called = false; + ErrorCode code = ErrorCode::None; + std::string raw; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + raw = result.RawBody(); + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, "not json at all"); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); + CHECK_EQ(raw, "not json at all"); +} + +// A well-formed JSON body of the wrong shape is also a decode error, not a default. This is +// the case D23 exists for: `{"broadcasts": 5}` must not silently yield zero broadcasts. +void TestWrongShapeIsAnError() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 5; + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, R"({"broadcasts":5})"); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); +} + +// An HTTP failure is delivered as a failure with the status and the body, and is not +// decoded. +void TestHttpFailure() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 5; + + bool called = false; + ErrorCode code = ErrorCode::None; + int status = 0; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + status = result.Error().status_code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 404, R"({"error":"nope"})"); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::Http); + CHECK_EQ_INT(status, 404); +} + +// `NormalizeResponse` is optional: a definition without one compiles and runs. The trait is +// what makes that true, so it is asserted directly rather than inferred from the tests +// above passing. +void TestNormalizeIsOptional() +{ + CHECK(!lootlocker::core::HasNormalizeResponse::value); +} + +// --- query parameters ------------------------------------------------------ + +void TestQueryParameterEncoding() +{ + lootlocker::core::QueryParameters query; + query.Add("limit", 25); + query.Add("name", "a b&c=d"); + query.Add("flag", true); + query.Add("ratio", 0.5); + query.Add("big", static_cast(9007199254740993LL)); + + CHECK_EQ(query.ToQueryString(), + "limit=25&name=a%20b%26c%3Dd&flag=true&ratio=0.5&big=9007199254740993"); +} + +void TestQueryParameterEmpty() +{ + lootlocker::core::QueryParameters query; + CHECK(query.Empty()); + CHECK_EQ(query.ToQueryString(), ""); +} + +// A double must not pick up a locale's decimal comma, and must not print six trailing +// zeros. Both are real failure modes of the obvious implementations. +void TestQueryParameterDoubleFormatting() +{ + lootlocker::core::QueryParameters query; + query.Add("a", 1.0); + query.Add("b", 1.5); + query.Add("c", 0.1); + CHECK_EQ(query.ToQueryString(), "a=1&b=1.5&c=0.1"); +} + +// --- request bodies (T13d) ------------------------------------------------- + +} // namespace + +namespace lootlocker { + +// The nested type every session start sends. It is the reason the body hook is an ADL +// `to_json` rather than a definition hook: one serialiser, reused by three bodies. +struct SessionOptionals { + std::string timezone; + std::string player_name; + bool auto_create_profile = true; +}; + +void to_json(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(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); // the nested type, through its own to_json +} + +struct GuestSessionResponse { + std::string session_token; +}; + +Result from_json(const JsonValue& j, GuestSessionResponse& out) +{ + out.session_token = j["session_token"].AsString(); + return Result::Ok(Empty()); +} + +namespace core { + +struct GuestSessionDef { + static constexpr const char* kMethod = "POST"; + static constexpr const char* kPath = "/game/v2/session/guest"; + + using Request = GuestSessionRequest; + using Response = GuestSessionResponse; + + static void ConstructQueryParameters(const Request&, QueryParameters&) {} + + static void ConstructHeaders(const Request&, HeaderMap&) {} +}; + +} // namespace core +} // namespace lootlocker + +namespace { + +using lootlocker::GuestSessionRequest; +using lootlocker::GuestSessionResponse; +using lootlocker::core::GuestSessionDef; + +// A POST carries the serialised body and a JSON content type. +void TestRequestBodyIsSent() +{ + Fixture f; + + GuestSessionRequest request; + request.game_key = "gk"; + request.game_version = "1.0.0"; + request.player_identifier = "player-1"; + request.optionals.timezone = "Europe/Stockholm"; + request.optionals.player_name = "Erik"; + request.optionals.auto_create_profile = false; + + lootlocker::core::Send( + *f.client, request, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK_EQ(sent->method, "POST"); + + std::string content_type; + CHECK(sent->headers.Get("Content-Type", content_type)); + CHECK_EQ(content_type, "application/json"); + + // The nested object is serialised through its own `to_json`, which is the whole point of + // putting the hook on the type. + // + // Keys come out in sorted order, not insertion order: nlohmann stores an object in a + // `std::map`. That is correct for JSON, where an object is unordered by definition, and + // the server parses rather than pattern-matches. It is asserted exactly so a change in + // that behaviour is visible. + CHECK_EQ(sent->body, + R"({"game_key":"gk","game_version":"1.0.0",)" + R"("optionals":{"auto_create_profile":false,"player_name":"Erik",)" + R"("timezone":"Europe/Stockholm"},"player_identifier":"player-1"})"); +} + +// A GET definition has no `to_json`, so it sends no body and no content type. This is what +// keeps the existing definitions unchanged. +void TestNoBodyWithoutToJson() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + lootlocker::core::Send(*f.client, request, + [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK_EQ(sent->body, ""); + CHECK(!sent->headers.Has("Content-Type")); +} + +// The trait is what makes the two cases above work, so it is asserted directly. +void TestBodyTrait() +{ + CHECK(lootlocker::core::HasToJson::value); + CHECK(!lootlocker::core::HasToJson::value); +} + +// A string literal must not become `true`, the same trap `QueryParameters::Add` had. +void TestBuilderStringLiteral() +{ + lootlocker::JsonBuilder b; + b.Set("name", "abc"); + CHECK_EQ(b.ToJson(), R"({"name":"abc"})"); +} + +// A uint64 above 2^63 must round-trip rather than wrap negative. +void TestBuilderUnsigned() +{ + lootlocker::JsonBuilder b; + b.Set("big", static_cast(18446744073709551615ULL)); + CHECK_EQ(b.ToJson(), R"({"big":18446744073709551615})"); +} + +// A null `const char*` is JSON null, not an empty string. +void TestBuilderNullPointer() +{ + lootlocker::JsonBuilder b; + const char* nothing = nullptr; + b.Set("x", nothing); + CHECK_EQ(b.ToJson(), R"({"x":null})"); +} + +// Invalid UTF-8 must not abort the process. With exceptions off, nlohmann's default error +// handler throws, and a throw under `JSON_NOEXCEPTION` is an abort. +void TestBuilderInvalidUtf8DoesNotAbort() +{ + lootlocker::JsonBuilder b; + // Split so `\xFE` does not swallow the following `b` as a hex digit. + b.Set("name", std::string("bad\xFF\xFE" "byte")); + const std::string out = b.ToJson(); + CHECK(!out.empty()); + // The bad bytes are replaced with U+FFFD rather than aborting, and the rest of the + // string survives. + CHECK(out.find("\"name\":\"bad") != std::string::npos); + CHECK(out.find("byte\"") != std::string::npos); +} + +// A 204 is the one legitimate empty success (`EndSession`). Parsing an empty body would +// report `MalformedResponse` for a request that succeeded. +void TestNoContentIsSuccess() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + bool called = false; + bool ok = false; + ErrorCode code = ErrorCode::None; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + ok = result.Ok(); + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 204, ""); + f.client->Update(); + + CHECK(called); + CHECK(ok); + CHECK(code == ErrorCode::None); +} + +// A malformed body must keep the transport metadata: `request_id` is what ties the failure +// to a server log line, and `status_code` says the request was actually answered. +void TestMalformedBodyKeepsRequestMetadata() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + std::string request_id; + int status = 0; + ErrorCode code = ErrorCode::None; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + if (!result.Ok()) { + request_id = result.Error().request_id; + status = result.Error().status_code; + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, "not json"); + f.client->Update(); + + CHECK(code == ErrorCode::MalformedResponse); + CHECK_EQ_INT(status, 200); + CHECK(!request_id.empty()); +} + +// A malformed nested item is an error, not an empty string. Without this the decoder would +// silently default a field and the generic layer would look correct while proving nothing. +void TestMalformedNestedItem() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::core::Send( + *f.client, request, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, + R"({"broadcasts":[{"id":"a"}]})"); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); +} + +// The SDK version and instance identifier headers the other SDKs send, and which the +// backend's tracing middleware reads. +void TestSdkAndInstanceHeaders() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + lootlocker::core::Send(*f.client, request, + [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + std::string value; + CHECK(sent->headers.Get("LL-SDK-Version", value)); + CHECK(!value.empty()); + + CHECK(sent->headers.Get("LL-Instance-Identifier", value)); + CHECK_EQ_INT(static_cast(value.size()), 36); // UUID-shaped + + // Stable for the client's lifetime, and different between clients. + CHECK_EQ(value, f.client->GetInstanceIdentifier()); + + Fixture other; + CHECK(other.client->GetInstanceIdentifier() != f.client->GetInstanceIdentifier()); +} + +// `is-development` is read only on the white-label login path, so it is not a default +// header. +void TestIsDevelopmentIsNotADefaultHeader() +{ + Fixture f; + + ListBroadcastsRequest request; + request.limit = 1; + + lootlocker::core::Send(*f.client, request, + [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + CHECK(!sent->headers.Has("is-development")); +} + +// A `uint64` query parameter must be accepted without a narrowing cast, and must not wrap. +void TestQueryParameterUnsigned() +{ + lootlocker::core::QueryParameters query; + query.Add("id", static_cast(18446744073709551615ULL)); + CHECK_EQ(query.ToQueryString(), "id=18446744073709551615"); +} + +// The double formatter must not emit a locale's decimal comma. The test forces a comma +// locale, which is the only way to prove the normalisation actually runs. +void TestQueryParameterDoubleIsLocaleIndependent() +{ + const char* previous = std::setlocale(LC_NUMERIC, nullptr); + const std::string saved = previous == nullptr ? std::string("C") : std::string(previous); + + // A comma-decimal locale. Not every platform has every locale, so a failure to set one + // is not a test failure - the assertion below still holds under "C". + std::setlocale(LC_NUMERIC, "de_DE.UTF-8"); + std::setlocale(LC_NUMERIC, "German_Germany.1252"); + + lootlocker::core::QueryParameters query; + query.Add("ratio", 1.5); + const std::string encoded = query.ToQueryString(); + + std::setlocale(LC_NUMERIC, saved.c_str()); + + CHECK_EQ(encoded, "ratio=1.5"); +} + +} // namespace + +int main() +{ + TestTypedWrapperReturnsExecutorId(); + TestDefinitionBuildsTheRequest(); + TestDefaultHeaders(); + TestSuccessfulDecode(); + TestMalformedBody(); + TestWrongShapeIsAnError(); + TestHttpFailure(); + TestNormalizeIsOptional(); + TestQueryParameterEncoding(); + TestQueryParameterEmpty(); + TestQueryParameterDoubleFormatting(); + TestRequestBodyIsSent(); + TestNoBodyWithoutToJson(); + TestBodyTrait(); + TestBuilderStringLiteral(); + TestBuilderUnsigned(); + TestBuilderNullPointer(); + TestBuilderInvalidUtf8DoesNotAbort(); + TestNoContentIsSuccess(); + TestMalformedBodyKeepsRequestMetadata(); + TestMalformedNestedItem(); + TestSdkAndInstanceHeaders(); + TestIsDevelopmentIsNotADefaultHeader(); + TestQueryParameterUnsigned(); + TestQueryParameterDoubleIsLocaleIndependent(); + return testing::Report(); +}