diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e837b4..8b44f4b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,6 +143,7 @@ add_library(lootlocker_core STATIC src/core/rate_limiter.cpp src/core/json.cpp src/core/query_parameters.cpp + src/core/state_writer.cpp src/core/executor.cpp src/core/client.cpp ) diff --git a/README.md b/README.md index 3dcfccf..5aff967 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,70 @@ definition. 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. +### Persistence + +The SDK remembers a session between launches through a `IStateWriter`. The default writes one +file next to the game; a console or an engine injects its own. + +```cpp +// The default: one file, next to the game. Constructed lazily, on first use, so a client +// that never persists anything performs no file I/O. +lootlocker::Config config; +config.domain_key = "your-domain"; + +// Or your own store, for a console's save-data API or an engine's settings. +// +// Keep the shared_ptr alive for as long as the client uses it: the client holds a weak_ptr, +// so a temporary would expire before the client was even constructed. +std::shared_ptr my_writer = std::make_shared(); +config.state_writer = my_writer; + +// Or nothing at all, if you would rather re-authenticate every launch. +std::shared_ptr no_persistence = + std::make_shared(); +config.state_writer = no_persistence; +``` + +The interface is typed rather than strings-only, because a store that only speaks strings +forces every adopter to write the same conversions and get the same rounding wrong: + +```cpp +class IStateWriter { +public: + virtual bool GetString(const std::string& key, std::string& out) = 0; + virtual void SetString(const std::string& key, const std::string& value) = 0; + + virtual bool GetInt64(const std::string& key, std::int64_t& out) = 0; + virtual void SetInt64(const std::string& key, std::int64_t value) = 0; + + virtual bool GetUInt64(const std::string& key, std::uint64_t& out) = 0; + virtual void SetUInt64(const std::string& key, std::uint64_t value) = 0; + + virtual bool GetDouble(const std::string& key, double& out) = 0; + virtual void SetDouble(const std::string& key, double value) = 0; + + virtual bool GetBool(const std::string& key, bool& out) = 0; + virtual void SetBool(const std::string& key, bool value) = 0; + + virtual void Erase(const std::string& key) = 0; + virtual bool Has(const std::string& key) = 0; +}; +``` + +`GetUInt64` exists separately from `GetInt64` because `player_id` is a `uint64` on the wire +and a valid id above `INT64_MAX` must round-trip exactly. A getter returns `false` and leaves +`out` untouched when the key is absent **or holds a different type** — it never converts, +because guessing is how a corrupt store becomes a wrong player id. + +Implementations must not throw. Persistence is best-effort: a failed write never fails a +request. + +`FileStateWriter` writes a flat `type:key=value` text file, whole, on every change. It is +**not atomic across a crash** — a power loss mid-write loses the file, and the cost is one +re-authentication. Write-temp-then-rename is not portable to every platform this SDK +targets, so the limitation is documented rather than hidden. A corrupt line is skipped on +load rather than losing the whole file. + ### 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 8c7bf28..94d4b86 100644 --- a/include/lootlocker/client.h +++ b/include/lootlocker/client.h @@ -15,6 +15,7 @@ namespace lootlocker { class Client; +class IStateWriter; namespace core { class Executor; @@ -79,6 +80,22 @@ class Client { // more. const std::string& GetInstanceIdentifier() const; + // Replaces the state writer. The client observes it through a `weak_ptr`, so the + // adopter keeps ownership. + // + // Unlike `SetTransport`, this is allowed at any time, because a state writer has no + // in-flight state to strand. That is a property of the implementation rather than an + // invitation: swapping the writer mid-game is not a use case anyone has, and a game + // that does it will find the new writer knows nothing the old one had already stored. + // Set it once, before the first request. + // + // An empty or dead `weak_ptr` falls back to the default `FileStateWriter`. + void SetStateWriter(std::weak_ptr writer); + + // The state writer in use. Never empty: the client always has one, defaulting to + // `FileStateWriter`. + std::weak_ptr GetStateWriter() 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/config.h b/include/lootlocker/config.h index aae3653..7cb42ba 100644 --- a/include/lootlocker/config.h +++ b/include/lootlocker/config.h @@ -17,7 +17,7 @@ namespace lootlocker { -class StateWriter; +class IStateWriter; class IHttpTransport; class TimezoneProvider; @@ -95,7 +95,7 @@ struct Config { // Optional overrides. Empty means "use the SDK default". std::weak_ptr logger; // default writes to stderr - std::weak_ptr state_writer; // default is FileStateWriter + std::weak_ptr state_writer; // default is FileStateWriter std::weak_ptr transport; // default is the libcurl one // The least-verbose level the SDK emits (D26). diff --git a/include/lootlocker/state_writer.h b/include/lootlocker/state_writer.h new file mode 100644 index 0000000..c222332 --- /dev/null +++ b/include/lootlocker/state_writer.h @@ -0,0 +1,139 @@ +#pragma once + +// Persistence (D11, R18). The seam that lets the SDK remember a session between launches. +// +// The problem this solves: guest auth's whole point is that a player keeps the same account +// across restarts. That requires remembering `player_identifier`, and there is no portable +// way to write a file on every platform this SDK targets — a console has its own save-data +// API, an engine has its own settings store, and a plain application has a filesystem. +// +// So the SDK defines the interface and ships two implementations: `FileStateWriter`, which +// writes one file next to the game, and `NullStateWriter`, which writes nothing. An engine +// or a console injects its own through `Config::state_writer` or `Client::SetStateWriter`. +// +// **Typed accessors rather than strings-only.** A store that only speaks strings forces +// every adopter to write the same conversions and get the same rounding wrong — and the +// `player_id` case is exactly where that bites, because a `uint64` above `INT64_MAX` does +// not survive a round trip through a `double` or a signed integer. +// +// **Implementations must not throw** (D7). A failed write is reported by returning false +// from the getter or by silently doing nothing from the setter; the SDK treats persistence +// as best-effort and never fails a request because a save failed. + +#include +#include +#include + +namespace lootlocker { + +class IStateWriter { +public: + virtual ~IStateWriter() = default; + + // Each getter returns false and leaves `out` untouched when the key is absent or holds + // a value of a different type. It does not convert: a key written as a string is not + // readable as an integer, because guessing is how a corrupt store becomes a wrong + // player id. + virtual bool GetString(const std::string& key, std::string& out) = 0; + virtual void SetString(const std::string& key, const std::string& value) = 0; + + virtual bool GetInt64(const std::string& key, std::int64_t& out) = 0; + virtual void SetInt64(const std::string& key, std::int64_t value) = 0; + + // Unsigned, because `player_id` is a `uint64` on the wire and a valid id above + // `INT64_MAX` must round-trip exactly (D4). + virtual bool GetUInt64(const std::string& key, std::uint64_t& out) = 0; + virtual void SetUInt64(const std::string& key, std::uint64_t value) = 0; + + virtual bool GetDouble(const std::string& key, double& out) = 0; + virtual void SetDouble(const std::string& key, double value) = 0; + + virtual bool GetBool(const std::string& key, bool& out) = 0; + virtual void SetBool(const std::string& key, bool value) = 0; + + virtual void Erase(const std::string& key) = 0; + virtual bool Has(const std::string& key) = 0; +}; + +// Writes nothing, and reports every key as absent. +// +// For a game that would rather re-authenticate every launch, and for a test that wants the +// no-persistence path. It is a real implementation rather than a null pointer, so the +// client never has to branch on whether a writer exists. +class NullStateWriter : public IStateWriter { +public: + bool GetString(const std::string& key, std::string& out) override; + void SetString(const std::string& key, const std::string& value) override; + + bool GetInt64(const std::string& key, std::int64_t& out) override; + void SetInt64(const std::string& key, std::int64_t value) override; + + bool GetUInt64(const std::string& key, std::uint64_t& out) override; + void SetUInt64(const std::string& key, std::uint64_t value) override; + + bool GetDouble(const std::string& key, double& out) override; + void SetDouble(const std::string& key, double value) override; + + bool GetBool(const std::string& key, bool& out) override; + void SetBool(const std::string& key, bool value) override; + + void Erase(const std::string& key) override; + bool Has(const std::string& key) override; +}; + +// Writes one file, next to the game by default. +// +// The format is a flat text file of `type:key=value` lines, written whole on every change. +// Deliberately not JSON: the SDK already has a JSON parser, but using it here would mean a +// corrupt save file is a parse error the adopter has to handle, and a flat format degrades +// to "skip the bad line" instead. +// +// **Not atomic across a crash.** A write truncates and rewrites, so a power loss mid-write +// loses the file. That is acceptable for a session token — the cost is one re-authentication +// — and the alternative (write-temp-then-rename) is not portable to every platform this SDK +// targets. Documented rather than hidden. +class FileStateWriter : public IStateWriter { +public: + // `path` is the file to write. Empty means the default, which is + // `lootlocker-state.txt` in the current working directory. + // + // The file is read once, at construction, so a writer is a snapshot plus a write-through + // cache. A second writer on the same path will not see the first one's later writes. + explicit FileStateWriter(const std::string& path = std::string()); + ~FileStateWriter() override; + + FileStateWriter(const FileStateWriter&) = delete; + FileStateWriter& operator=(const FileStateWriter&) = delete; + + bool GetString(const std::string& key, std::string& out) override; + void SetString(const std::string& key, const std::string& value) override; + + bool GetInt64(const std::string& key, std::int64_t& out) override; + void SetInt64(const std::string& key, std::int64_t value) override; + + bool GetUInt64(const std::string& key, std::uint64_t& out) override; + void SetUInt64(const std::string& key, std::uint64_t value) override; + + bool GetDouble(const std::string& key, double& out) override; + void SetDouble(const std::string& key, double value) override; + + bool GetBool(const std::string& key, bool& out) override; + void SetBool(const std::string& key, bool value) override; + + void Erase(const std::string& key) override; + bool Has(const std::string& key) override; + + // The path in use, after the default was resolved. + const std::string& GetPath() const; + + // True when the last write succeeded. A writer whose file is unwritable still serves + // reads from its cache, so a game on a read-only filesystem degrades to + // re-authenticating rather than failing. + bool LastWriteSucceeded() const; + +private: + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace lootlocker diff --git a/src/core/client.cpp b/src/core/client.cpp index f9c4033..70fd7eb 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "clock.h" #include "executor.h" @@ -30,6 +31,25 @@ struct Client::Impl { // in, which is a supported configuration: the adopter injects their own. std::shared_ptr owned_transport; + // The state writer. The default is constructed lazily, on first use, so a client that + // never persists anything performs no file I/O - which is what keeps the "no implicit + // config" non-negotiable true (D9). An injected writer is held weakly and may expire at + // any time, so the default is also the fallback. + mutable std::shared_ptr default_state_writer; + std::weak_ptr state_writer; + + // The writer to use, constructing the default on first call. + std::shared_ptr ResolveStateWriter() const + { + if (std::shared_ptr live = state_writer.lock()) { + return live; + } + if (!default_state_writer) { + default_state_writer = std::make_shared(); + } + return default_state_writer; + } + core::SteadyClock clock; std::unique_ptr executor; }; @@ -110,9 +130,13 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } + // The state writer: the injected one wins, otherwise the file default is constructed + // lazily on first use. Deliberately NOT constructed here - a client that never persists + // anything must perform no file I/O, which is what keeps "no implicit config" true (D9). + m_impl->state_writer = config.state_writer; + core::ExecutorSettings settings; settings.queue = config.queue; - // An invalid config means the policy was never validated, so it must not reach the // limiter: a rejected 2-billion-second window would still derive 2 billion buckets and // attempt a multi-gigabyte allocation during construction, which in a no-exceptions @@ -167,6 +191,22 @@ const std::string& Client::GetInstanceIdentifier() const return m_impl->instance_identifier; } +void Client::SetStateWriter(std::weak_ptr writer) +{ + // An empty or dead writer falls back to the default, which is constructed lazily on + // first use. A game that wants no persistence injects a `NullStateWriter` explicitly, + // which is a different statement from "I forgot". + m_impl->state_writer = writer; +} + +std::weak_ptr Client::GetStateWriter() const +{ + // Resolved at read time, not at set time: the injected writer is held weakly, so it may + // have died since. Returning the expired handle would leave the caller with nothing to + // persist to, which is the opposite of what a default is for. + return m_impl->ResolveStateWriter(); +} + namespace core { Executor& GetExecutor(Client& client) diff --git a/src/core/state_writer.cpp b/src/core/state_writer.cpp new file mode 100644 index 0000000..86ca1f9 --- /dev/null +++ b/src/core/state_writer.cpp @@ -0,0 +1,358 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace lootlocker { + +// --------------------------------------------------------------------------- +// NullStateWriter +// --------------------------------------------------------------------------- + +bool NullStateWriter::GetString(const std::string&, std::string&) { return false; } +void NullStateWriter::SetString(const std::string&, const std::string&) {} + +bool NullStateWriter::GetInt64(const std::string&, std::int64_t&) { return false; } +void NullStateWriter::SetInt64(const std::string&, std::int64_t) {} + +bool NullStateWriter::GetUInt64(const std::string&, std::uint64_t&) { return false; } +void NullStateWriter::SetUInt64(const std::string&, std::uint64_t) {} + +bool NullStateWriter::GetDouble(const std::string&, double&) { return false; } +void NullStateWriter::SetDouble(const std::string&, double) {} + +bool NullStateWriter::GetBool(const std::string&, bool&) { return false; } +void NullStateWriter::SetBool(const std::string&, bool) {} + +void NullStateWriter::Erase(const std::string&) {} +bool NullStateWriter::Has(const std::string&) { return false; } + +// --------------------------------------------------------------------------- +// FileStateWriter +// --------------------------------------------------------------------------- + +namespace { + +// The type tag on each line. A key written as one type is not readable as another, which is +// what stops a corrupt or hand-edited file from silently becoming a wrong player id. +enum class ValueType { String, Int64, UInt64, Double, Bool }; + +const char* TypeTag(ValueType type) +{ + switch (type) { + case ValueType::String: return "s"; + case ValueType::Int64: return "i"; + case ValueType::UInt64: return "u"; + case ValueType::Double: return "d"; + case ValueType::Bool: return "b"; + } + return "s"; +} + +bool ParseTypeTag(const std::string& tag, ValueType& out) +{ + if (tag == "s") { out = ValueType::String; return true; } + if (tag == "i") { out = ValueType::Int64; return true; } + if (tag == "u") { out = ValueType::UInt64; return true; } + if (tag == "d") { out = ValueType::Double; return true; } + if (tag == "b") { out = ValueType::Bool; return true; } + return false; +} + +struct Entry { + ValueType type = ValueType::String; + std::string text; +}; + +// A key may not contain the separators, because the format is line-based and unescaped. +// Rejecting is better than escaping: an escaped format is a parser, and this is deliberately +// not one. +bool IsValidKey(const std::string& key) +{ + if (key.empty()) { + return false; + } + return key.find('=') == std::string::npos && key.find('\n') == std::string::npos && + key.find('\r') == std::string::npos; +} + +// A value may not contain a newline, for the same reason. A session token is base64-ish and +// a player name could contain anything, so a newline is replaced rather than rejected - the +// alternative is losing the whole write over a display name. +std::string SanitizeValue(const std::string& value) +{ + std::string out = value; + for (std::size_t i = 0; i < out.size(); ++i) { + if (out[i] == '\n' || out[i] == '\r') { + out[i] = ' '; + } + } + return out; +} + +std::string FormatDouble(double value) +{ + // `%.17g` round-trips an IEEE double exactly. A shorter form would lose precision on a + // value the SDK wrote itself, which is the one thing a store must not do. + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%.17g", value); + + // `%g` is governed by the process-wide `LC_NUMERIC` locale, so in a comma-decimal locale + // this writes `0,1` - and `GetDouble` uses `strtod`, which under the same locale would + // read it back, but under a *different* locale (the game changed it, or the file was + // written on another machine) would not. Normalising to '.' makes the file + // locale-independent, which is what a persisted format has to be. + std::string text(buffer); + const char* decimal_point = std::localeconv()->decimal_point; + if (decimal_point != nullptr && *decimal_point != '\0' && std::string(decimal_point) != ".") { + const std::size_t at = text.find(decimal_point); + if (at != std::string::npos) { + text.replace(at, std::string(decimal_point).size(), "."); + } + } + return text; +} + +} // namespace + +struct FileStateWriter::Impl { + std::string path; + std::map entries; + bool last_write_ok = true; + + void Load() + { + std::ifstream in(path.c_str(), std::ios::binary); + if (!in) { + // No file yet is the normal first-launch case, not an error. + return; + } + + std::string line; + while (std::getline(in, line)) { + if (line.empty()) { + continue; + } + + // `type:key=value`. A malformed line is skipped rather than aborting the load, + // so one bad line does not lose the whole session. + const std::size_t colon = line.find(':'); + if (colon == std::string::npos) { + continue; + } + const std::size_t equals = line.find('=', colon + 1); + if (equals == std::string::npos) { + continue; + } + + ValueType type = ValueType::String; + if (!ParseTypeTag(line.substr(0, colon), type)) { + continue; + } + + const std::string key = line.substr(colon + 1, equals - colon - 1); + if (!IsValidKey(key)) { + continue; + } + + Entry entry; + entry.type = type; + entry.text = line.substr(equals + 1); + entries[key] = entry; + } + } + + void Save() + { + // Written whole. A partial write is possible on a crash, which is documented on the + // class rather than papered over: the cost is one re-authentication. + std::ofstream out(path.c_str(), std::ios::binary | std::ios::trunc); + if (!out) { + last_write_ok = false; + return; + } + + for (std::map::const_iterator it = entries.begin(); + it != entries.end(); ++it) { + out << TypeTag(it->second.type) << ':' << it->first << '=' << it->second.text + << '\n'; + } + + out.flush(); + last_write_ok = out.good(); + } + + void Put(const std::string& key, ValueType type, const std::string& text) + { + if (!IsValidKey(key)) { + // A key with a separator cannot be represented. Silently dropping it is better + // than writing a file that will not load back. + return; + } + Entry entry; + entry.type = type; + entry.text = SanitizeValue(text); + entries[key] = entry; + Save(); + } + + bool Get(const std::string& key, ValueType expected, std::string& out) const + { + const std::map::const_iterator it = entries.find(key); + if (it == entries.end() || it->second.type != expected) { + return false; + } + out = it->second.text; + return true; + } +}; + +FileStateWriter::FileStateWriter(const std::string& path) : m_impl(new Impl()) +{ + m_impl->path = path.empty() ? std::string("lootlocker-state.txt") : path; + m_impl->Load(); +} + +FileStateWriter::~FileStateWriter() = default; + +const std::string& FileStateWriter::GetPath() const +{ + return m_impl->path; +} + +bool FileStateWriter::LastWriteSucceeded() const +{ + return m_impl->last_write_ok; +} + +bool FileStateWriter::GetString(const std::string& key, std::string& out) +{ + return m_impl->Get(key, ValueType::String, out); +} + +void FileStateWriter::SetString(const std::string& key, const std::string& value) +{ + m_impl->Put(key, ValueType::String, value); +} + +bool FileStateWriter::GetInt64(const std::string& key, std::int64_t& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Int64, text)) { + return false; + } + + // `strtoll` with an end pointer, so trailing garbage is a failure rather than a silent + // truncation. + errno = 0; + char* end = nullptr; + const long long parsed = std::strtoll(text.c_str(), &end, 10); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = static_cast(parsed); + return true; +} + +void FileStateWriter::SetInt64(const std::string& key, std::int64_t value) +{ + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%lld", static_cast(value)); + m_impl->Put(key, ValueType::Int64, buffer); +} + +bool FileStateWriter::GetUInt64(const std::string& key, std::uint64_t& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::UInt64, text)) { + return false; + } + + // `strtoull` rather than `strtoll`: a `player_id` above `INT64_MAX` is valid and must + // round-trip exactly (D4). A leading '-' is rejected explicitly, because `strtoull` + // accepts it and wraps. + if (!text.empty() && text[0] == '-') { + return false; + } + + errno = 0; + char* end = nullptr; + const unsigned long long parsed = std::strtoull(text.c_str(), &end, 10); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = static_cast(parsed); + return true; +} + +void FileStateWriter::SetUInt64(const std::string& key, std::uint64_t value) +{ + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%llu", static_cast(value)); + m_impl->Put(key, ValueType::UInt64, buffer); +} + +bool FileStateWriter::GetDouble(const std::string& key, double& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Double, text)) { + return false; + } + + errno = 0; + char* end = nullptr; + const double parsed = std::strtod(text.c_str(), &end); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = parsed; + return true; +} + +void FileStateWriter::SetDouble(const std::string& key, double value) +{ + m_impl->Put(key, ValueType::Double, FormatDouble(value)); +} + +bool FileStateWriter::GetBool(const std::string& key, bool& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Bool, text)) { + return false; + } + if (text == "1") { + out = true; + return true; + } + if (text == "0") { + out = false; + return true; + } + return false; +} + +void FileStateWriter::SetBool(const std::string& key, bool value) +{ + m_impl->Put(key, ValueType::Bool, value ? "1" : "0"); +} + +void FileStateWriter::Erase(const std::string& key) +{ + if (m_impl->entries.erase(key) != 0) { + m_impl->Save(); + } +} + +bool FileStateWriter::Has(const std::string& key) +{ + return m_impl->entries.find(key) != m_impl->entries.end(); +} + +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 27ca845..e9f5dc6 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -75,6 +75,11 @@ target_link_libraries(test_definition PRIVATE LootLocker::core lootlocker_compil target_include_directories(test_definition PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME definition COMMAND test_definition) +# The StateWriter seam (T12a). Public surface, so no `src/` include path is needed. +add_executable(test_state_writer test_state_writer.cpp) +target_link_libraries(test_state_writer PRIVATE LootLocker::core lootlocker_compile_options) +add_test(NAME state_writer COMMAND test_state_writer) + # 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_state_writer.cpp b/tests/test_state_writer.cpp new file mode 100644 index 0000000..7fa5301 --- /dev/null +++ b/tests/test_state_writer.cpp @@ -0,0 +1,459 @@ +// The IStateWriter seam (T12a). +// +// The verification the task asks for: each typed accessor round-trips its type; the null +// writer persists nothing and the client still works; a `uint64` above `INT64_MAX` +// round-trips exactly (the `player_id` case, D4). + +#include +#include +#include +#include + +#include "test_harness.h" + +#include +#include +#include +#include + +namespace { + +using lootlocker::Client; +using lootlocker::Config; +using lootlocker::FileStateWriter; +using lootlocker::NullStateWriter; +using lootlocker::IStateWriter; + +// A scratch file that removes itself, so a failing test does not leave state behind for the +// next run to trip over. +struct TempFile { + std::string path; + + explicit TempFile(const char* name) + { + path = std::string("test-state-") + name + ".txt"; + std::remove(path.c_str()); + } + + ~TempFile() { std::remove(path.c_str()); } +}; + +// --- typed round trips ----------------------------------------------------- + +void TestStringRoundTrip() +{ + TempFile file("string"); + FileStateWriter writer(file.path); + + writer.SetString("session_token", "abc123"); + + std::string out; + CHECK(writer.GetString("session_token", out)); + CHECK_EQ(out, "abc123"); +} + +void TestInt64RoundTrip() +{ + TempFile file("int64"); + FileStateWriter writer(file.path); + + writer.SetInt64("negative", -9007199254740993LL); + + std::int64_t out = 0; + CHECK(writer.GetInt64("negative", out)); + CHECK_EQ_INT(static_cast(out), -9007199254740993LL); +} + +// The `player_id` case (D4): a valid id above INT64_MAX must round-trip exactly. This is the +// reason the interface has a `uint64` accessor at all. +void TestUInt64AboveInt64MaxRoundTrips() +{ + TempFile file("uint64"); + FileStateWriter writer(file.path); + + const std::uint64_t big = 18446744073709551615ULL; // UINT64_MAX + writer.SetUInt64("player_id", big); + + std::uint64_t out = 0; + CHECK(writer.GetUInt64("player_id", out)); + CHECK(out == big); + + // And it survives a reload, which is the whole point of persistence. + FileStateWriter reopened(file.path); + std::uint64_t reloaded = 0; + CHECK(reopened.GetUInt64("player_id", reloaded)); + CHECK(reloaded == big); +} + +void TestDoubleRoundTrip() +{ + TempFile file("double"); + FileStateWriter writer(file.path); + + writer.SetDouble("ratio", 0.1); + + double out = 0.0; + CHECK(writer.GetDouble("ratio", out)); + CHECK(out == 0.1); // exact, because the format round-trips +} + +void TestBoolRoundTrip() +{ + TempFile file("bool"); + FileStateWriter writer(file.path); + + writer.SetBool("seen_before", true); + writer.SetBool("check_dlc", false); + + bool out = false; + CHECK(writer.GetBool("seen_before", out)); + CHECK(out); + + CHECK(writer.GetBool("check_dlc", out)); + CHECK(!out); +} + +// --- type safety ----------------------------------------------------------- + +// A key written as one type is not readable as another. Guessing is how a corrupt store +// becomes a wrong player id. +void TestTypeMismatchIsNotConverted() +{ + TempFile file("mismatch"); + FileStateWriter writer(file.path); + + writer.SetString("player_id", "12345"); + + std::uint64_t out = 0; + CHECK(!writer.GetUInt64("player_id", out)); + CHECK_EQ_INT(static_cast(out), 0); // untouched +} + +void TestAbsentKey() +{ + TempFile file("absent"); + FileStateWriter writer(file.path); + + std::string out = "untouched"; + CHECK(!writer.GetString("nope", out)); + CHECK_EQ(out, "untouched"); + CHECK(!writer.Has("nope")); +} + +void TestErase() +{ + TempFile file("erase"); + FileStateWriter writer(file.path); + + writer.SetString("k", "v"); + CHECK(writer.Has("k")); + writer.Erase("k"); + CHECK(!writer.Has("k")); + + // And the erase is persisted, not just cached. + FileStateWriter reopened(file.path); + CHECK(!reopened.Has("k")); +} + +// --- persistence across instances ------------------------------------------ + +void TestSurvivesReopen() +{ + TempFile file("reopen"); + + { + FileStateWriter writer(file.path); + writer.SetString("player_identifier", "guest-42"); + writer.SetUInt64("player_id", 9007199254740993ULL); + writer.SetBool("seen_before", true); + } + + FileStateWriter reopened(file.path); + + std::string identifier; + CHECK(reopened.GetString("player_identifier", identifier)); + CHECK_EQ(identifier, "guest-42"); + + std::uint64_t id = 0; + CHECK(reopened.GetUInt64("player_id", id)); + CHECK(id == 9007199254740993ULL); + + bool seen = false; + CHECK(reopened.GetBool("seen_before", seen)); + CHECK(seen); +} + +// A corrupt line is skipped rather than losing the whole file. One bad line must not cost +// the player their session. +void TestCorruptLineIsSkipped() +{ + TempFile file("corrupt"); + + { + std::FILE* f = std::fopen(file.path.c_str(), "wb"); + CHECK(f != nullptr); + if (f != nullptr) { + std::fputs("s:good=kept\n", f); + std::fputs("this line has no separator\n", f); + std::fputs("x:badtype=1\n", f); + std::fputs("s:also_good=yes\n", f); + std::fclose(f); + } + } + + FileStateWriter writer(file.path); + + std::string out; + CHECK(writer.GetString("good", out)); + CHECK_EQ(out, "kept"); + + CHECK(writer.GetString("also_good", out)); + CHECK_EQ(out, "yes"); + + CHECK(!writer.Has("badtype")); +} + +// A newline in a value must not break the file format. A player name could contain +// anything, and losing the whole write over a display name would be worse than replacing it. +void TestNewlineInValueIsSanitised() +{ + TempFile file("newline"); + FileStateWriter writer(file.path); + + writer.SetString("player_name", "line one\nline two"); + + std::string out; + CHECK(writer.GetString("player_name", out)); + CHECK_EQ(out, "line one line two"); + + // The other keys still load, which is what proves the file was not corrupted. + writer.SetString("after", "ok"); + FileStateWriter reopened(file.path); + CHECK(reopened.GetString("after", out)); + CHECK_EQ(out, "ok"); +} + +// --- the null writer ------------------------------------------------------- + +void TestNullWriterPersistsNothing() +{ + NullStateWriter writer; + + writer.SetString("k", "v"); + writer.SetUInt64("player_id", 42); + writer.SetBool("b", true); + + std::string s; + std::uint64_t u = 0; + bool b = false; + + CHECK(!writer.GetString("k", s)); + CHECK(!writer.GetUInt64("player_id", u)); + CHECK(!writer.GetBool("b", b)); + CHECK(!writer.Has("k")); +} + +// --- the client seam ------------------------------------------------------- + +Config MakeConfig() +{ + Config config; + config.domain_key = "testdomain"; + config.game_key = "testgamekey"; + config.game_version = "1.0.0"; + return config; +} + +// A client with no injected writer still has one, and it is the file default. +void TestClientHasADefaultWriter() +{ + Client client(MakeConfig()); + CHECK(!client.GetStateWriter().expired()); +} + +// The default is constructed lazily, so a client that never persists anything performs no +// file I/O. That is what keeps the "no implicit config" non-negotiable true (D9): the SDK +// must not read a file on its own. +// +// The discriminator is *when* the read happens. `FileStateWriter` reads its file in its +// constructor, so the probe is deleted between constructing the client and first asking for +// the writer: a lazy default then finds nothing to load, an eager one has already loaded it. +void TestDefaultWriterIsLazy() +{ + const std::string probe = "lootlocker-state.txt"; + std::remove(probe.c_str()); + + { + std::FILE* f = std::fopen(probe.c_str(), "wb"); + CHECK(f != nullptr); + if (f != nullptr) { + std::fputs("s:probe=loaded\n", f); + std::fclose(f); + } + } + + Client client(MakeConfig()); + + // Remove the file before the writer is ever asked for. An eager default has already read + // it; a lazy one has not. + std::remove(probe.c_str()); + + std::shared_ptr writer = client.GetStateWriter().lock(); + CHECK(writer != nullptr); + if (writer != nullptr) { + std::string out; + CHECK(!writer->GetString("probe", out)); + } + + std::remove(probe.c_str()); +} + +// An injected writer means the default is never constructed at all, so no file is touched +// even when the writer is used. +void TestInjectedWriterMeansNoFileIo() +{ + const std::string probe = "lootlocker-state.txt"; + std::remove(probe.c_str()); + + std::shared_ptr writer = std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + + Client client(config); + client.GetStateWriter().lock()->SetString("k", "v"); + + std::FILE* f = std::fopen(probe.c_str(), "rb"); + CHECK(f == nullptr); + if (f != nullptr) { + std::fclose(f); + } + + std::remove(probe.c_str()); +} + +// An injected writer is the one used. +void TestClientUsesInjectedWriter() +{ + std::shared_ptr writer = std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + + Client client(config); + + std::shared_ptr in_use = client.GetStateWriter().lock(); + CHECK(in_use != nullptr); + CHECK(in_use.get() == writer.get()); +} + +// The null writer is a supported configuration: the client still works, it just does not +// persist. +void TestClientWorksWithNullWriter() +{ + std::shared_ptr writer = std::make_shared(); + std::shared_ptr transport = + std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + config.transport = transport; + + Client client(config); + + CHECK(client.ConfigError().Ok()); + CHECK(!client.GetStateWriter().expired()); + + // Nothing was written anywhere. + std::string out; + CHECK(!writer->GetString("session_token", out)); +} + +// `SetStateWriter` is allowed at any time, unlike `SetTransport`, because a writer has no +// in-flight state to strand. +void TestSetStateWriterAtRuntime() +{ + Client client(MakeConfig()); + + std::shared_ptr replacement = std::make_shared(); + client.SetStateWriter(replacement); + + std::shared_ptr in_use = client.GetStateWriter().lock(); + CHECK(in_use != nullptr); + CHECK(in_use.get() == replacement.get()); +} + +// An empty or dead writer falls back to the default rather than leaving the client with +// nothing. A game that wants no persistence injects a `NullStateWriter` explicitly, which is +// a different statement from "I forgot". +void TestSetStateWriterFallsBackWhenEmpty() +{ + Client client(MakeConfig()); + + client.SetStateWriter(std::weak_ptr()); + CHECK(!client.GetStateWriter().expired()); + + { + std::shared_ptr temporary = std::make_shared(); + client.SetStateWriter(temporary); + } + // The injected writer died with its scope. + CHECK(!client.GetStateWriter().expired()); +} + +// A double must round-trip even when the process locale uses a decimal comma. The file is a +// persisted format, so it has to be locale-independent: a file written under one locale must +// read back under another. +void TestDoubleIsLocaleIndependent() +{ + const char* previous = std::setlocale(LC_NUMERIC, nullptr); + const std::string saved = previous == nullptr ? std::string("C") : std::string(previous); + + std::setlocale(LC_NUMERIC, "de_DE.UTF-8"); + std::setlocale(LC_NUMERIC, "German_Germany.1252"); + + TempFile file("locale"); + { + FileStateWriter writer(file.path); + writer.SetDouble("ratio", 0.1); + } + + // Read back under the C locale, which is the "written on another machine" case. + std::setlocale(LC_NUMERIC, "C"); + + FileStateWriter reopened(file.path); + double out = 0.0; + const bool ok = reopened.GetDouble("ratio", out); + + std::setlocale(LC_NUMERIC, saved.c_str()); + + CHECK(ok); + CHECK(out == 0.1); +} + +} // namespace + +int main() +{ + TestStringRoundTrip(); + TestInt64RoundTrip(); + TestUInt64AboveInt64MaxRoundTrips(); + TestDoubleRoundTrip(); + TestBoolRoundTrip(); + TestTypeMismatchIsNotConverted(); + TestAbsentKey(); + TestErase(); + TestSurvivesReopen(); + TestCorruptLineIsSkipped(); + TestNewlineInValueIsSanitised(); + TestNullWriterPersistsNothing(); + TestClientHasADefaultWriter(); + TestDefaultWriterIsLazy(); + TestInjectedWriterMeansNoFileIo(); + TestClientUsesInjectedWriter(); + TestClientWorksWithNullWriter(); + TestSetStateWriterAtRuntime(); + TestSetStateWriterFallsBackWhenEmpty(); + TestDoubleIsLocaleIndependent(); + return testing::Report(); +}