Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Load family-shared games in the background, by hash

Leonardo Lobato15346c2f7780
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index bdf3340..ae2717f 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -147,6 +147,8 @@ endif()
# Authenticated CM session for the CM-only library facts (acquisition dates).
add_library(playden_steam_cm STATIC
"${CMAKE_SOURCE_DIR}/src/steam/backend/cm_client.cpp"
+ "${CMAKE_SOURCE_DIR}/src/steam/backend/app_info_http.cpp"
+ "${CMAKE_SOURCE_DIR}/src/steam/backend/app_names.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/entitled_library.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/family_groups.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/cm_app_details.cpp"
diff --git a/src/app/library_controller.cpp b/src/app/library_controller.cpp
index debf044..56bf891 100644
--- a/src/app/library_controller.cpp
+++ b/src/app/library_controller.cpp
@@ -70,7 +70,7 @@ void LibraryController::Refresh(Store store) {
for(auto& other:others_) if(other.source->store()==store) RefreshOther(other);
}
void LibraryController::Reset() {
- steam_.Invalidate(++generation_);request_=0;account_=0;clearing_=false;clear_result_.reset();offline_=false;needs_renewal_=false;
+ steam_.Invalidate(++generation_);request_=0;completed_request_=0;account_=0;clearing_=false;clear_result_.reset();offline_=false;needs_renewal_=false;
}
void LibraryController::Clear() {
clear_result_.reset();clearing_=true;
@@ -111,6 +111,16 @@ void LibraryController::TickOther(Other& other,LibraryEvent& event) {
else other.request=0;
}
void LibraryController::TickSteam(LibraryEvent& event) {
+ if(event.kind==LibraryEventKind::kUpdated) {
+ // Games named in the background after the last load completed: the whole library again, status untouched.
+ if(request_ || clearing_ || !completed_request_ || event.request_id!=completed_request_ ||
+ event.account_id!=account_ || event.account_generation!=generation_) return;
+ // Keeps the status line, unless saving the bigger library failed.
+ const std::string status=event.cache_error!=StorageError::kNone ? "Library loaded, but saving failed. Retry to save."
+ : model_.state().account().error;
+ model_.UpdateLibrary({std::move(event.games),false,status,false,event.cache_available,Time(event)});
+ return;
+ }
if(!request_ || event.request_id!=request_ || event.account_id!=account_ || event.account_generation!=generation_) return;
if(clearing_) {
if(event.kind==LibraryEventKind::kCleared || event.kind==LibraryEventKind::kFailure) {
@@ -145,6 +155,7 @@ void LibraryController::TickSteam(LibraryEvent& event) {
const char* warning=event.cache_error!=StorageError::kNone ? "Library loaded, but saving failed. Retry to save."
: event.metadata_partial ? "Some game details are unavailable." : "";
if(*warning) model_.UpdateLibrary({{},false,warning,cached,event.cache_available,time});
+ completed_request_=cached ? 0 : request_;
request_=0;
}
}
diff --git a/src/app/library_controller.h b/src/app/library_controller.h
index b5e0713..6e29f7d 100644
--- a/src/app/library_controller.h
+++ b/src/app/library_controller.h
@@ -51,6 +51,8 @@ class LibraryController {
stores::LibrarySource& steam_;
std::vector<Other> others_;
std::uint64_t account_=0,generation_=0,request_=0;
+ // The last load that completed, for the games its backend names later (kUpdated).
+ std::uint64_t completed_request_=0;
std::uint64_t licenses_generation_=0,licenses_read_=0;
bool offline_=false,clearing_=false;
bool needs_renewal_=false;
diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cpp
index 4fecc73..c057036 100644
--- a/src/homebrew/host.cpp
+++ b/src/homebrew/host.cpp
@@ -552,6 +552,7 @@ int main(int argc, char** argv) {
cm_client->SetSharedSession(steam_cm);
library_backend = std::make_unique<playden::steam::EntitledLibraryBackend>(*owned_library, *cm_client);
library_backend->SetLicensedDepots(&licensed_depots);
+ library_backend->SetAppNameStorage(library_storage.get());
// Family sharing diagnostics.
library_backend->SetFamilyDiagnostics(PLAYDEN_HOMEBREW_CA_BUNDLE, [log_directory](const std::string& line) {
playden::app::AppendLogLine(log_directory, "steam-cm.log", line);
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index f1a1124..eadd503 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -354,6 +354,7 @@ int main() {
playden::steam::EntitledLibraryBackend library_backend(owned_library, cm_client);
playden::steam::LicensedDepots licensed_depots;
library_backend.SetLicensedDepots(&licensed_depots);
+ library_backend.SetAppNameStorage(&library_storage);
// Family sharing diagnostics, with the CM license lines.
library_backend.SetFamilyDiagnostics(paths.trust_store, [](const std::string& line) {
playden::app::AppendLogLine(log_root, "steam-cm.log", line);
diff --git a/src/library/service.cpp b/src/library/service.cpp
index e6928aa..017ad43 100644
--- a/src/library/service.cpp
+++ b/src/library/service.cpp
@@ -4,6 +4,7 @@
#include <chrono>
#include <limits>
#include <unordered_map>
+#include <unordered_set>
namespace playden {
namespace {
@@ -12,6 +13,16 @@ constexpr std::size_t kMaximumEvents = 64;
constexpr std::uint64_t kMaximumTimestamp =
static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max());
+// Only a library with demos needs schema 6, and one with family-shared games schema 7; one without stays
+// readable by older versions.
+void SetSchema(LibrarySnapshot* snapshot) {
+ const auto& games = snapshot->games;
+ if (std::any_of(games.begin(), games.end(), [](const GameSummary& game) { return game.demo; }))
+ snapshot->schema_version = 6;
+ if (std::any_of(games.begin(), games.end(), [](const GameSummary& game) { return game.family_shared; }))
+ snapshot->schema_version = 7;
+}
+
} // namespace
LibraryService::LibraryService(steam::LibraryBackend& backend,
@@ -19,7 +30,9 @@ LibraryService::LibraryService(steam::LibraryBackend& backend,
LibraryRepository* cache,
std::function<std::uint64_t()> unix_seconds)
: backend_(backend), sessions_(sessions), cache_(cache),
- unix_seconds_(std::move(unix_seconds)), worker_([this] { Run(); }) {}
+ unix_seconds_(std::move(unix_seconds)), worker_([this] { Run(); }) {
+ backend_.SetLateGamesCallback([this] { NotifyLateGames(); });
+}
LibraryService::~LibraryService() { Shutdown(); }
@@ -108,7 +121,22 @@ bool LibraryService::Current(const Job& job) const {
!job.cancel->load();
}
+void LibraryService::NotifyLateGames() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ // A refresh in flight starts its lookups again, and asks for a merge itself once it completes.
+ if (active_command_ && *active_command_ != Command::kMerge) return;
+ QueueMergeLocked();
+}
+
+void LibraryService::QueueMergeLocked() {
+ if (stopping_ || clear_barrier_ || !pending_.empty()) return;
+ pending_.push_back(Job{Command::kMerge, request_, 0, generation_, std::make_shared<std::atomic<bool>>(false)});
+ wake_.notify_one();
+}
+
void LibraryService::Shutdown() {
+ // Waits for a running callback; none comes after this.
+ backend_.SetLateGamesCallback(nullptr);
{
std::lock_guard<std::mutex> lock(mutex_);
if (joined_) return;
@@ -203,6 +231,7 @@ void LibraryService::Run() {
void LibraryService::Execute(const Job& job) {
if (job.command == Command::kRefresh) ExecuteRefresh(job);
else if (job.command == Command::kLoadCached) ExecuteLoadCached(job);
+ else if (job.command == Command::kMerge) ExecuteMerge(job);
else ExecuteClear(job);
}
@@ -294,13 +323,7 @@ void LibraryService::ExecuteRefresh(const Job& job) {
if (previous != previous_added_at.end()) game.added_at_unix_seconds = previous->second;
}
snapshot.metadata_partial = result.metadata_partial;
- // Only a library with demos needs schema 6, and one with family-shared games schema 7; one without stays
- // readable by older versions.
- if (std::any_of(snapshot.games.begin(), snapshot.games.end(), [](const GameSummary& game) { return game.demo; }))
- snapshot.schema_version = 6;
- if (std::any_of(snapshot.games.begin(), snapshot.games.end(),
- [](const GameSummary& game) { return game.family_shared; }))
- snapshot.schema_version = 7;
+ SetSchema(&snapshot);
if (cache_) {
const auto saved = cache_->Save(job.account, snapshot);
if (!Current(job)) return;
@@ -312,6 +335,16 @@ void LibraryService::ExecuteRefresh(const Job& job) {
}
}
+ completed_ = snapshot;
+ completed_request_ = job.request;
+ completed_account_ = job.account;
+ completed_cache_available_ = cache_available;
+ {
+ // Late games named before completed_ was set would otherwise wait for the next load.
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (job.request == request_ && job.generation == generation_) QueueMergeLocked();
+ }
+
LibraryEvent event;
event.kind = LibraryEventKind::kComplete;
event.request_id = job.request;
@@ -328,6 +361,44 @@ void LibraryService::ExecuteRefresh(const Job& job) {
!job.cancel->load()) PushEvent(std::move(event));
}
+void LibraryService::ExecuteMerge(const Job& job) {
+ if (!Current(job) || !completed_ || completed_request_ != job.request) return;
+ auto late = backend_.TakeLateGames(completed_account_);
+ std::unordered_set<GameId> present;
+ for (const auto& game : completed_->games) present.insert(game.id);
+ std::size_t added = 0;
+ for (auto& game : late)
+ if (present.insert(game.id).second) {
+ completed_->games.push_back(std::move(game));
+ ++added;
+ }
+ if (!added) return;
+ SetSchema(&*completed_);
+ StorageError cache_error = StorageError::kNone;
+ if (cache_) {
+ const auto saved = cache_->Save(completed_account_, *completed_);
+ if (saved.ok()) completed_cache_available_ = true;
+ else cache_error = saved.error();
+ }
+ LibraryEvent event;
+ event.kind = LibraryEventKind::kUpdated;
+ event.request_id = job.request;
+ event.account_id = completed_account_;
+ event.account_generation = job.generation;
+ event.games = completed_->games;
+ event.metadata_partial = completed_->metadata_partial;
+ event.retrieved_at_unix_seconds = completed_->retrieved_at_unix_seconds;
+ event.cache_available = completed_cache_available_;
+ event.cache_error = cache_error;
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_ || job.request != request_ || job.generation != generation_ || job.cancel->load()) return;
+ // Each update carries the whole library: one waiting is enough, and they can't crowd out the completion.
+ events_.erase(std::remove_if(events_.begin(), events_.end(), [&](const LibraryEvent& queued) {
+ return queued.kind == LibraryEventKind::kUpdated && queued.request_id == job.request;
+ }), events_.end());
+ PushEvent(std::move(event));
+}
+
void LibraryService::ExecuteClear(const Job& job) {
Result<void> cleared = cache_
? cache_->Clear(job.account)
diff --git a/src/library/service.h b/src/library/service.h
index d2f7916..c15cb33 100644
--- a/src/library/service.h
+++ b/src/library/service.h
@@ -14,7 +14,9 @@
namespace playden {
-enum class LibraryEventKind { kLoading, kCached, kComplete, kFailure, kCleared };
+// kUpdated follows a kComplete of the same request: the whole library again, with games the backend named
+// in the background since.
+enum class LibraryEventKind { kLoading, kCached, kComplete, kFailure, kCleared, kUpdated };
struct LibraryEvent {
LibraryEventKind kind = LibraryEventKind::kFailure;
@@ -50,11 +52,14 @@ class LibraryService {
std::uint64_t account_generation);
std::uint64_t Clear(std::uint64_t account_id, std::uint64_t account_generation);
void Invalidate(std::uint64_t account_generation);
+ // From any thread (the backend's late-games callback): queues adding the backend's late games to the last
+ // completed refresh, unless something else is queued or that refresh is no longer current.
+ void NotifyLateGames();
void Shutdown();
std::vector<LibraryEvent> Pump(std::size_t max_events);
private:
- enum class Command { kRefresh, kLoadCached, kClear };
+ enum class Command { kRefresh, kLoadCached, kClear, kMerge };
struct Job {
Command command;
std::uint64_t request;
@@ -70,6 +75,8 @@ class LibraryService {
void ExecuteRefresh(const Job&);
void ExecuteLoadCached(const Job&);
void ExecuteClear(const Job&);
+ void ExecuteMerge(const Job&);
+ void QueueMergeLocked();
void EmitFailure(const Job&, steam::LibraryError, StorageError = StorageError::kNone,
bool cache_available = false);
void PushEvent(LibraryEvent, bool destructive_terminal = false);
@@ -92,6 +99,11 @@ class LibraryService {
bool clear_barrier_ = false;
bool stopping_ = false;
bool joined_ = false;
+ // The last refresh that completed (worker thread only), for late games.
+ std::optional<LibrarySnapshot> completed_;
+ std::uint64_t completed_request_ = 0;
+ std::uint64_t completed_account_ = 0;
+ bool completed_cache_available_ = false;
std::thread worker_;
};
diff --git a/src/steam/backend/app_info_http.cpp b/src/steam/backend/app_info_http.cpp
new file mode 100644
index 0000000..8ea9b68
--- /dev/null
+++ b/src/steam/backend/app_info_http.cpp
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/backend/app_info_http.h"
+
+#include "steam/backend/gzip.h"
+
+#include <mbedtls/sha1.h>
+
+#include <algorithm>
+#include <mutex>
+#include <thread>
+
+namespace playden::steam {
+namespace {
+
+constexpr std::uint32_t kTimeoutMs = 5'000; // a few KB each
+constexpr int kFailuresBeforeStop = 3;
+
+// A bare host name for a URL: letters, digits, dots and dashes only.
+bool ValidHost(const std::string& host) {
+ if (host.empty() || host.size() > 253) return false;
+ return std::all_of(host.begin(), host.end(), [](char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-';
+ });
+}
+
+std::string Hex(const std::vector<std::uint8_t>& bytes) {
+ static constexpr char kDigits[] = "0123456789abcdef";
+ std::string text;
+ text.reserve(bytes.size() * 2);
+ for (const auto byte : bytes) {
+ text.push_back(kDigits[byte >> 4]);
+ text.push_back(kDigits[byte & 15]);
+ }
+ return text;
+}
+
+} // namespace
+
+std::string AppInfoHttpUrl(std::string host, std::uint32_t app_id, const std::vector<std::uint8_t>& sha) {
+ if (!ValidHost(host)) host = kAppInfoHttpHost;
+ return "https://" + host + "/appinfo/" + std::to_string(app_id) + "/sha/" + Hex(sha) + ".txt.gz";
+}
+
+std::map<std::uint32_t, std::string> FetchAppInfoByHash(
+ const std::function<AppInfoPerform()>& make_perform, const std::string& host,
+ const std::map<std::uint32_t, HashedAppInfo>& apps, std::size_t workers, const std::atomic<bool>& cancel,
+ AppInfoHttpStats* stats, const std::function<void(std::uint32_t, const std::string&)>& on_text) {
+ std::map<std::uint32_t, std::string> texts;
+ AppInfoHttpStats totals;
+ if (apps.empty() || !make_perform) {
+ totals.skipped = apps.size();
+ if (stats) *stats = totals;
+ return texts;
+ }
+ std::vector<std::pair<std::uint32_t, const HashedAppInfo*>> queue;
+ queue.reserve(apps.size());
+ for (const auto& [id, app] : apps) queue.emplace_back(id, &app);
+
+ std::mutex mutex; // guards texts, totals, next, failures_in_row and on_text calls
+ std::size_t next = 0;
+ int failures_in_row = 0;
+ const auto work = [&] {
+ const AppInfoPerform perform = make_perform();
+ for (;;) {
+ std::uint32_t id = 0;
+ const HashedAppInfo* app = nullptr;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ if (next == queue.size() || cancel.load() || failures_in_row >= kFailuresBeforeStop) return;
+ id = queue[next].first;
+ app = queue[next].second;
+ ++next;
+ }
+ if (app->sha.size() != 20 || app->size == 0 || app->size > kMaxGunzipBytes || !perform) {
+ std::lock_guard<std::mutex> lock(mutex);
+ ++totals.failed;
+ continue;
+ }
+ HttpRequest request;
+ request.url = AppInfoHttpUrl(host, id, app->sha);
+ request.headers = {{"User-Agent", "Playden/1.0"}};
+ request.max_response_bytes = kMaxGunzipBytes;
+ request.timeout_ms = kTimeoutMs;
+ const HttpResponse response = perform(request, cancel);
+ std::string text;
+ bool matched = false;
+ if (response.ok() && response.status_code == 200) {
+ std::vector<std::uint8_t> vdf;
+ if (Gunzip(response.body.data(), response.body.size(), app->size, &vdf)) {
+ text.assign(vdf.begin(), vdf.end());
+ while (!text.empty() && text.back() == '\0') text.pop_back();
+ unsigned char sha1[20] = {};
+ mbedtls_sha1(reinterpret_cast<const unsigned char*>(text.data()), text.size(), sha1);
+ matched = std::equal(sha1, sha1 + sizeof(sha1), app->sha.begin());
+ }
+ }
+ std::lock_guard<std::mutex> lock(mutex);
+ totals.new_connections += response.timing.new_connections;
+ totals.total_ms += response.timing.total_ms;
+ if (!response.ok()) {
+ if (response.error != HttpError::kCanceled) {
+ totals.error = HttpFailureName(response);
+ ++failures_in_row;
+ }
+ ++totals.skipped;
+ continue;
+ }
+ failures_in_row = 0;
+ if (!matched) {
+ ++totals.failed;
+ continue;
+ }
+ ++totals.fetched;
+ if (on_text) on_text(id, text);
+ texts[id] = std::move(text);
+ }
+ };
+ const std::size_t count = std::max<std::size_t>(1, std::min(workers, queue.size()));
+ std::vector<std::thread> threads;
+ threads.reserve(count - 1);
+ for (std::size_t index = 1; index < count; ++index) threads.emplace_back(work);
+ work();
+ for (auto& thread : threads) thread.join();
+ totals.skipped += queue.size() - next;
+ if (stats) *stats = totals;
+ return texts;
+}
+
+} // namespace playden::steam
diff --git a/src/steam/backend/app_info_http.h b/src/steam/backend/app_info_http.h
new file mode 100644
index 0000000..584e8a7
--- /dev/null
+++ b/src/steam/backend/app_info_http.h
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "steam/backend/http_client.h"
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <string>
+#include <vector>
+
+namespace playden::steam {
+
+// Steam's PICS answers most apps with only the SHA-1 and size of their app info VDF; the Steam client then
+// fetches the VDF from the clientconfig host by that hash. The copy is checked against both, so the host
+// is not trusted.
+inline constexpr const char* kAppInfoHttpHost = "clientconfig.akamai.steamstatic.com";
+
+struct HashedAppInfo {
+ std::vector<std::uint8_t> sha; // SHA-1 of the VDF text without trailing NULs
+ std::uint32_t size = 0; // gzip's uncompressed size, trailing NUL included
+};
+
+using AppInfoPerform = std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)>;
+
+struct AppInfoHttpStats {
+ std::size_t fetched = 0;
+ std::size_t failed = 0; // answered, but not a matching copy (status, gzip, size or SHA-1)
+ std::size_t skipped = 0; // a transport failure or timeout on that app, or not asked after the stop
+ std::string error; // the last transport failure, empty when none
+ std::uint32_t new_connections = 0;
+ std::uint64_t total_ms = 0; // summed over requests
+};
+
+// "https://<host>/appinfo/<id>/sha/<hex>.txt.gz"; a host that isn't a bare name gets the default one.
+std::string AppInfoHttpUrl(std::string host, std::uint32_t app_id, const std::vector<std::uint8_t>& sha);
+
+// Fetches the VDFs of `apps` by hash, up to `workers` at once. Each worker gets its own transport from
+// `make_perform` (one HttpClient per thread). An app whose request fails is skipped; after three transport
+// failures in a row the rest are skipped too, since the host is then out of reach. `on_text`, when set, is
+// called (from a worker, one call at a time) for each checked copy as it lands.
+std::map<std::uint32_t, std::string> FetchAppInfoByHash(
+ const std::function<AppInfoPerform()>& make_perform, const std::string& host,
+ const std::map<std::uint32_t, HashedAppInfo>& apps, std::size_t workers, const std::atomic<bool>& cancel,
+ AppInfoHttpStats* stats = nullptr,
+ const std::function<void(std::uint32_t, const std::string&)>& on_text = {});
+
+} // namespace playden::steam
diff --git a/src/steam/backend/app_names.cpp b/src/steam/backend/app_names.cpp
new file mode 100644
index 0000000..86b714c
--- /dev/null
+++ b/src/steam/backend/app_names.cpp
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/backend/app_names.h"
+
+#include <algorithm>
+#include <vector>
+
+namespace playden::steam {
+namespace {
+
+constexpr const char* kPath = "app-names.cache";
+const Bytes kMagic = {'P', 'D', 'N', 'A', 'M', 'E', 0, 1};
+constexpr std::size_t kMaxName = 1024;
+constexpr std::size_t kMaxIcon = 64;
+constexpr std::size_t kMaxBytes = 4 * 1024 * 1024;
+
+std::uint32_t Checksum(const Bytes& bytes, std::size_t size) {
+ std::uint32_t crc = 0xffffffffu;
+ for (std::size_t i = 0; i < size; ++i) {
+ crc ^= bytes[i];
+ for (int bit = 0; bit < 8; ++bit) crc = (crc >> 1) ^ (0xedb88320u & (0u - (crc & 1u)));
+ }
+ return ~crc;
+}
+
+void Number(Bytes& out, std::uint64_t value, unsigned count) {
+ for (unsigned i = 0; i < count; ++i) {
+ out.push_back(static_cast<std::uint8_t>(value));
+ value >>= 8;
+ }
+}
+
+struct Reader {
+ const Bytes& bytes;
+ std::size_t offset = 0;
+ std::size_t limit = 0;
+ bool okay = true;
+ std::uint64_t Number(unsigned count) {
+ if (!okay || offset > limit || count > limit - offset) {
+ okay = false;
+ return 0;
+ }
+ std::uint64_t value = 0;
+ for (unsigned i = 0; i < count; ++i) value |= std::uint64_t(bytes[offset++]) << (i * 8);
+ return value;
+ }
+ std::string String(std::size_t maximum) {
+ const auto count = Number(2);
+ if (!okay || count > maximum || offset > limit || count > limit - offset) {
+ okay = false;
+ return {};
+ }
+ std::string value(bytes.begin() + static_cast<std::ptrdiff_t>(offset),
+ bytes.begin() + static_cast<std::ptrdiff_t>(offset + count));
+ offset += count;
+ return value;
+ }
+};
+
+} // namespace
+
+AppNames LoadAppNames(const Storage& storage) {
+ const auto read = storage.Read(kPath, kMaxBytes);
+ if (!read.ok()) return {};
+ const Bytes& bytes = read.value();
+ if (bytes.size() < kMagic.size() + 8 || !std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) return {};
+ const std::size_t body = bytes.size() - 4;
+ Reader crc{bytes, body, bytes.size()};
+ if (static_cast<std::uint32_t>(crc.Number(4)) != Checksum(bytes, body)) return {};
+ Reader reader{bytes, kMagic.size(), body};
+ const auto count = reader.Number(4);
+ if (!reader.okay || count > kMaxAppNames) return {};
+ AppNames names;
+ names.reserve(static_cast<std::size_t>(count));
+ for (std::uint64_t i = 0; i < count; ++i) {
+ const auto id = static_cast<std::uint32_t>(reader.Number(4));
+ AppName name;
+ const auto kind = reader.Number(1);
+ name.learned_at = reader.Number(8);
+ name.name = reader.String(kMaxName);
+ name.icon = reader.String(kMaxIcon);
+ if (!reader.okay || !id || kind > 2) return {};
+ name.kind = static_cast<AppName::Kind>(kind);
+ if (name.kind != AppName::Kind::kOther && name.name.empty()) return {};
+ names[id] = std::move(name);
+ }
+ if (reader.offset != body) return {};
+ return names;
+}
+
+bool SaveAppNames(const Storage& storage, const AppNames& names) {
+ std::vector<std::pair<std::uint32_t, const AppName*>> entries;
+ entries.reserve(names.size());
+ for (const auto& [id, name] : names) {
+ if (!id || name.name.size() > kMaxName || name.icon.size() > kMaxIcon) continue;
+ if (name.kind != AppName::Kind::kOther && name.name.empty()) continue;
+ entries.emplace_back(id, &name);
+ }
+ // The newest stay, as many as Load accepts: kMaxAppNames entries in kMaxBytes.
+ std::sort(entries.begin(), entries.end(),
+ [](const auto& a, const auto& b) { return a.second->learned_at > b.second->learned_at; });
+ std::size_t bytes = kMagic.size() + 4 + 4;
+ std::size_t kept = 0;
+ for (; kept < entries.size() && kept < kMaxAppNames; ++kept) {
+ const auto& name = *entries[kept].second;
+ const std::size_t size = 4 + 1 + 8 + 2 + name.name.size() + 2 + name.icon.size();
+ if (bytes + size > kMaxBytes) break;
+ bytes += size;
+ }
+ entries.resize(kept);
+ std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
+ Bytes out = kMagic;
+ Number(out, entries.size(), 4);
+ for (const auto& [id, name] : entries) {
+ Number(out, id, 4);
+ Number(out, static_cast<std::uint8_t>(name->kind), 1);
+ Number(out, name->learned_at, 8);
+ Number(out, name->name.size(), 2);
+ out.insert(out.end(), name->name.begin(), name->name.end());
+ Number(out, name->icon.size(), 2);
+ out.insert(out.end(), name->icon.begin(), name->icon.end());
+ }
+ Number(out, Checksum(out, out.size()), 4);
+ return storage.WriteAtomic(kPath, out).ok();
+}
+
+} // namespace playden::steam
diff --git a/src/steam/backend/app_names.h b/src/steam/backend/app_names.h
new file mode 100644
index 0000000..51d9e39
--- /dev/null
+++ b/src/steam/backend/app_names.h
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "platform/storage.h"
+
+#include <cstdint>
+#include <string>
+#include <unordered_map>
+
+namespace playden::steam {
+
+// What the Library needs about a Steam app it only knows from a license: whether it is a game or a demo
+// and its name. Anything else (DLC, tools, configs) is kept as kOther, so it is never looked up again.
+struct AppName {
+ enum class Kind : std::uint8_t { kOther = 0, kGame = 1, kDemo = 2 };
+ Kind kind = Kind::kOther;
+ std::string name; // empty for kOther
+ std::string icon; // the PICS icon hash, when known
+ std::uint64_t learned_at = 0; // unix seconds
+};
+
+using AppNames = std::unordered_map<std::uint32_t, AppName>;
+
+inline constexpr std::size_t kMaxAppNames = 20'000;
+
+// "app-names.cache" in user storage. Names are public data, shared by every account on the console.
+// Load returns nothing for a missing, damaged or foreign file; Save keeps the newest kMaxAppNames.
+AppNames LoadAppNames(const Storage& storage);
+bool SaveAppNames(const Storage& storage, const AppNames& names);
+
+} // namespace playden::steam
diff --git a/src/steam/backend/cm_client.cpp b/src/steam/backend/cm_client.cpp
index a8a2766..2db25ac 100644
--- a/src/steam/backend/cm_client.cpp
+++ b/src/steam/backend/cm_client.cpp
@@ -1,5 +1,6 @@
#include "steam/backend/cm_client.h"
+#include "steam/backend/app_info_http.h"
#include "steam/backend/auth_messages.h"
#include "steam/backend/binary_kv.h"
#include "steam/backend/gzip.h"
@@ -1070,6 +1071,16 @@ CmError CmClient::WithServiceSession(const StoredSession& stored, std::uint32_t
AppInfoBuffers CmClient::FetchAppInfo(const StoredSession& stored,
const std::vector<std::uint32_t>& app_ids,
const std::atomic<bool>& cancel) {
+ return FetchAppInfo(stored, app_ids, cancel, true);
+}
+
+AppInfoBuffers CmClient::FetchAppInfoPics(const StoredSession& stored, const std::vector<std::uint32_t>& app_ids,
+ const std::atomic<bool>& cancel) {
+ return FetchAppInfo(stored, app_ids, cancel, false);
+}
+
+AppInfoBuffers CmClient::FetchAppInfo(const StoredSession& stored, const std::vector<std::uint32_t>& app_ids,
+ const std::atomic<bool>& cancel, bool by_hash) {
AppInfoBuffers result;
if (app_ids.empty() || app_ids.size() > kMaxAppInfoBatch) return result; // kProtocol
const auto deadline = Clock::now() + std::chrono::milliseconds(hooks_.deadline_ms);
@@ -1094,12 +1105,13 @@ AppInfoBuffers CmClient::FetchAppInfo(const StoredSession& stored,
// A kept session the server dropped while idle: one fresh try, since this call only reads.
if (reused && (call == CmError::kNetwork || call == CmError::kTimeout)) {
CloseSession(&lease);
- return FetchAppInfo(stored, app_ids, cancel);
+ return FetchAppInfo(stored, app_ids, cancel, by_hash);
}
return finish(call == CmError::kRejected ? CmError::kProtocol : call);
}
std::vector<cm::AppRequest> tokens;
- if (!cm::DecodePicsAccessTokenResponse(reply, &tokens)) return finish(CmError::kProtocol);
+ std::vector<std::uint32_t> denied;
+ if (!cm::DecodePicsAccessTokenResponse(reply, &tokens, &denied)) return finish(CmError::kProtocol);
std::vector<cm::AppRequest> requests;
for (const auto id : app_ids) {
cm::AppRequest request{id, 0};
@@ -1112,15 +1124,72 @@ AppInfoBuffers CmClient::FetchAppInfo(const StoredSession& stored,
pics != CmError::kNone)
return finish(pics);
const std::set<std::uint32_t> wanted(app_ids.begin(), app_ids.end());
+ std::map<std::uint32_t, std::string> why;
+ std::map<std::uint32_t, const cm::PicsApp*> offloaded;
+ std::uint32_t http_min_size = 0;
+ std::string http_host;
for (const auto& part : parts) {
+ if (part.http_min_size) http_min_size = part.http_min_size;
+ if (!part.http_host.empty()) http_host = part.http_host;
+ for (const auto app : part.unknown_apps)
+ if (wanted.count(app)) why.emplace(app, "unknown");
for (const auto& app : part.apps) {
- if (!wanted.count(app.app_id) || app.missing_token || app.buffer.empty()) continue;
+ if (!wanted.count(app.app_id)) continue;
+ if (app.missing_token || app.buffer.empty()) {
+ why[app.app_id] = app.missing_token ? "missing_token" : !app.sha.empty() ? "http" : "empty";
+ if (!app.missing_token && !app.sha.empty()) offloaded[app.app_id] = &app;
+ continue;
+ }
std::string text(app.buffer.begin(), app.buffer.end());
while (!text.empty() && text.back() == '\0') text.pop_back();
result.buffers[app.app_id] = std::move(text);
}
}
- return finish(CmError::kNone);
+ // The CM is done with: the session goes back before any HTTP.
+ finish(CmError::kNone);
+
+ // Steam answers most apps with only the SHA-1 and size of their VDF, fetched by hash from its HTTP host.
+ for (const auto& [id, app] : offloaded) result.hashed[id] = HashedAppInfo{app->sha, app->size};
+ result.http_host = http_host;
+ AppInfoHttpStats http;
+ if (by_hash && !result.hashed.empty()) {
+ const auto make_perform = [this]() -> AppInfoPerform {
+ if (hooks_.app_info) return hooks_.app_info;
+ if (ca_bundle_.empty()) return nullptr;
+ auto client = std::make_shared<HttpClient>(ca_bundle_);
+ return [client](const HttpRequest& request, const std::atomic<bool>& stop) { return client->Perform(request, stop); };
+ };
+ for (auto& [id, text] : FetchAppInfoByHash(make_perform, http_host, result.hashed, kAppInfoHttpWorkers, cancel, &http)) {
+ result.hashed.erase(id);
+ result.buffers[id] = std::move(text);
+ }
+ }
+
+ for (const auto id : app_ids) {
+ if (result.buffers.count(id)) continue;
+ auto reason = why.count(id) ? why[id] : std::string("absent");
+ if (std::find(denied.begin(), denied.end(), id) != denied.end()) reason = "token_denied";
+ result.unanswered[id] = std::move(reason);
+ }
+ if (!offloaded.empty() || !result.unanswered.empty()) {
+ // One line per batch Steam didn't answer in full, so the log tells a refused token from an HTTP-only answer.
+ std::map<std::string, std::size_t> counts;
+ for (const auto& [id, reason] : result.unanswered) ++counts[reason];
+ std::string line = "step=app_info requested=" + std::to_string(app_ids.size()) +
+ " answered=" + std::to_string(result.buffers.size()) + " parts=" + std::to_string(parts.size()) +
+ " tokens=" + std::to_string(tokens.size()) + " denied=" + std::to_string(denied.size()) +
+ " offloaded=" + std::to_string(offloaded.size());
+ if (by_hash)
+ line += " http_fetched=" + std::to_string(http.fetched) + " http_failed=" + std::to_string(http.failed) +
+ " http_skipped=" + std::to_string(http.skipped) + " http_connections=" + std::to_string(http.new_connections) +
+ " http_ms=" + std::to_string(http.total_ms);
+ if (!http.error.empty()) line += " http_error=" + http.error;
+ for (const auto& [reason, count] : counts) line += " " + reason + "=" + std::to_string(count);
+ if (http_min_size) line += " http_min_size=" + std::to_string(http_min_size);
+ if (!http_host.empty()) line += " http_host=" + http_host.substr(0, 64);
+ Log(line);
+ }
+ return result;
}
FreeLicenseResult CmClient::RequestFreeLicenses(const StoredSession& stored, const std::vector<std::uint32_t>& app_ids,
diff --git a/src/steam/backend/cm_client.h b/src/steam/backend/cm_client.h
index e47b850..669ec69 100644
--- a/src/steam/backend/cm_client.h
+++ b/src/steam/backend/cm_client.h
@@ -2,6 +2,7 @@
#include "platform/storage.h"
#include "steam/backend/cm_messages.h"
+#include "steam/backend/app_info_http.h"
#include "steam/backend/http_client.h"
#include "steam/backend/ws_client.h"
#include "steam/auth_backend.h"
@@ -108,10 +109,19 @@ struct TokenRenewal {
};
inline constexpr std::size_t kMaxAppInfoBatch = 50;
+// By-hash app info fetches at once.
+inline constexpr std::size_t kAppInfoHttpWorkers = 4;
struct AppInfoBuffers {
CmError error = CmError::kProtocol;
std::map<std::uint32_t, std::string> buffers; // app ID -> VDF text (trailing NULs removed)
+ // Asked-for apps still without a buffer, and why: token_denied, missing_token, http (only a hash, and
+ // the copy on Steam's HTTP host was not fetched or did not match), unknown, empty, or absent (not in any
+ // response part).
+ std::map<std::uint32_t, std::string> unanswered;
+ // The "http" ones: what to fetch them by, from http_host (empty: Steam named none, use the default).
+ std::map<std::uint32_t, HashedAppInfo> hashed;
+ std::string http_host;
bool ok() const { return error == CmError::kNone; }
};
@@ -152,6 +162,12 @@ class AcquisitionSource {
const std::atomic<bool>&) {
return {};
}
+ // The same without fetching the hash-only apps over HTTP: they come back in `hashed`, for a caller that
+ // fetches them itself (FetchAppInfoByHash).
+ virtual AppInfoBuffers FetchAppInfoPics(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
+ const std::atomic<bool>& cancel) {
+ return FetchAppInfo(session, app_ids, cancel);
+ }
};
// Derives the stable logon device fields from a per-install seed, as the reference
@@ -163,6 +179,7 @@ std::string LoadOrCreateDeviceSeed(const Storage& storage);
struct CmClientHooks {
std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)> directory;
+ std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)> app_info; // VDFs Steam serves over HTTP
std::function<std::unique_ptr<MessageTransport>()> transport;
std::function<std::uint64_t()> unix_now;
std::uint32_t deadline_ms = 25'000;
@@ -212,6 +229,8 @@ class CmClient final : public AcquisitionSource {
AppInfoBuffers FetchAppInfo(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
const std::atomic<bool>& cancel) override;
+ AppInfoBuffers FetchAppInfoPics(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
+ const std::atomic<bool>& cancel) override;
// Asks Steam to add free apps (free DLC) to the account in one ClientRequestFreeLicense. When it
// grants anything, waits up to `license_wait_ms` (cancelable) for the license list Steam pushes
@@ -231,6 +250,8 @@ class CmClient final : public AcquisitionSource {
const std::function<CmError(const ServiceCall& call, std::uint64_t steam_id)>& work);
private:
+ AppInfoBuffers FetchAppInfo(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
+ const std::atomic<bool>& cancel, bool by_hash);
friend class CmSharedSession;
class Session;
// The session one call runs on: its own, or the shared one held for the call's duration.
diff --git a/src/steam/backend/cm_messages.cpp b/src/steam/backend/cm_messages.cpp
index aeacad0..a48da7a 100644
--- a/src/steam/backend/cm_messages.cpp
+++ b/src/steam/backend/cm_messages.cpp
@@ -260,6 +260,22 @@ bool DecodePicsResponse(const std::vector<std::uint8_t>& body, PicsResponse* res
decoded.response_pending = field.value != 0;
continue;
}
+ if (field.number == 2) {
+ if (!IsVarint(field)) return false;
+ if (decoded.unknown_apps.size() >= kMaxRepeatedEntries) return false;
+ decoded.unknown_apps.push_back(static_cast<std::uint32_t>(field.value));
+ continue;
+ }
+ if (field.number == 7) {
+ if (!IsVarint(field)) return false;
+ decoded.http_min_size = static_cast<std::uint32_t>(field.value);
+ continue;
+ }
+ if (field.number == 8) {
+ if (!IsBytes(field)) return false;
+ decoded.http_host.assign(reinterpret_cast<const char*>(field.data), field.size);
+ continue;
+ }
if (field.number == 1) {
if (decoded.apps.size() >= kMaxRepeatedEntries) return false;
proto::Reader child;
@@ -273,9 +289,18 @@ bool DecodePicsResponse(const std::vector<std::uint8_t>& body, PicsResponse* res
} else if (entry.number == 3) {
if (!IsVarint(entry)) return false;
app.missing_token = entry.value != 0;
+ } else if (entry.number == 4) {
+ if (!IsBytes(entry)) return false;
+ app.sha = Bytes(entry);
} else if (entry.number == 5) {
if (!IsBytes(entry)) return false;
app.buffer = Bytes(entry);
+ } else if (entry.number == 6) {
+ if (!IsVarint(entry)) return false;
+ app.only_public = entry.value != 0;
+ } else if (entry.number == 7) {
+ if (!IsVarint(entry)) return false;
+ app.size = static_cast<std::uint32_t>(entry.value);
}
}
if (!child.ok()) return false;
@@ -328,11 +353,18 @@ std::vector<std::uint8_t> EncodePicsAccessTokenRequest(const std::vector<std::ui
}
bool DecodePicsAccessTokenResponse(const std::vector<std::uint8_t>& body,
- std::vector<AppRequest>* tokens) {
+ std::vector<AppRequest>* tokens,
+ std::vector<std::uint32_t>* denied) {
proto::Reader reader(body, kLimits);
proto::Field field;
std::vector<AppRequest> decoded;
+ std::vector<std::uint32_t> refused;
while (reader.Next(&field)) {
+ if (field.number == 4 && IsVarint(field)) {
+ if (refused.size() >= kMaxRepeatedEntries) return false;
+ refused.push_back(static_cast<std::uint32_t>(field.value));
+ continue;
+ }
if (field.number != 3) continue;
if (decoded.size() >= kMaxRepeatedEntries) return false;
proto::Reader child;
@@ -349,6 +381,7 @@ bool DecodePicsAccessTokenResponse(const std::vector<std::uint8_t>& body,
}
if (!reader.ok()) return false;
*tokens = std::move(decoded);
+ if (denied) *denied = std::move(refused);
return true;
}
diff --git a/src/steam/backend/cm_messages.h b/src/steam/backend/cm_messages.h
index 9cec6cd..0232a81 100644
--- a/src/steam/backend/cm_messages.h
+++ b/src/steam/backend/cm_messages.h
@@ -139,12 +139,19 @@ struct PicsPackage {
struct PicsApp {
std::uint32_t app_id = 0;
bool missing_token = false;
+ bool only_public = false;
std::vector<std::uint8_t> buffer; // text VDF, possibly NUL-terminated
+ std::vector<std::uint8_t> sha; // SHA-1 of the VDF; with no buffer, the copy over HTTP is named by it
+ std::uint32_t size = 0;
};
struct PicsResponse {
std::vector<PicsPackage> packages;
std::vector<PicsApp> apps;
+ std::vector<std::uint32_t> unknown_apps;
bool response_pending = false;
+ // Apps whose VDF is at least this big may come without a buffer, to be fetched from http_host instead.
+ std::uint32_t http_min_size = 0;
+ std::string http_host;
};
struct AppRequest {
@@ -153,9 +160,10 @@ struct AppRequest {
};
std::vector<std::uint8_t> EncodePicsAppsRequest(const std::vector<AppRequest>& apps);
std::vector<std::uint8_t> EncodePicsAccessTokenRequest(const std::vector<std::uint32_t>& app_ids);
-// App ID -> access token, for apps Steam granted tokens to (denied apps are absent).
+// App ID -> access token, for apps Steam granted tokens to (denied apps are absent, listed in `denied`).
bool DecodePicsAccessTokenResponse(const std::vector<std::uint8_t>& body,
- std::vector<AppRequest>* tokens);
+ std::vector<AppRequest>* tokens,
+ std::vector<std::uint32_t>* denied = nullptr);
bool DecodePicsResponse(const std::vector<std::uint8_t>& body, PicsResponse* response);
std::vector<std::uint8_t> EncodeDepotKeyRequest(std::uint32_t depot_id, std::uint32_t app_id);
diff --git a/src/steam/backend/entitled_library.cpp b/src/steam/backend/entitled_library.cpp
index deb2332..93bb373 100644
--- a/src/steam/backend/entitled_library.cpp
+++ b/src/steam/backend/entitled_library.cpp
@@ -1,6 +1,7 @@
#include "steam/backend/entitled_library.h"
#include "steam/backend/app_info.h"
+#include "steam/backend/app_info_http.h"
#include <algorithm>
#include <cctype>
@@ -28,7 +29,10 @@ FamilyLog Serialized(FamilyLog log) {
} // namespace
-EntitledLibraryBackend::~EntitledLibraryBackend() { StopFamilyProbe(); }
+EntitledLibraryBackend::~EntitledLibraryBackend() {
+ StopLookups();
+ StopFamilyProbe();
+}
void EntitledLibraryBackend::StopFamilyProbe() {
std::lock_guard<std::mutex> guard(family_start_mutex_);
@@ -44,6 +48,7 @@ void EntitledLibraryBackend::StopFamilyProbe() {
void EntitledLibraryBackend::SetFamilyDiagnostics(std::string ca_bundle, FamilyLog log) {
StopFamilyProbe();
family_answered_.store(false);
+ family_no_group_.store(0);
family_ca_bundle_ = std::move(ca_bundle);
family_perform_ = nullptr;
family_log_ = Serialized(std::move(log));
@@ -52,6 +57,7 @@ void EntitledLibraryBackend::SetFamilyDiagnostics(std::string ca_bundle, FamilyL
void EntitledLibraryBackend::SetFamilyDiagnostics(FamilyPerform perform, FamilyLog log) {
StopFamilyProbe();
family_answered_.store(false);
+ family_no_group_.store(0);
family_ca_bundle_.clear();
family_perform_ = std::move(perform);
family_log_ = Serialized(std::move(log));
@@ -62,11 +68,13 @@ void EntitledLibraryBackend::SetFamilyDiagnostics(FamilyPerform perform, FamilyL
bool EntitledLibraryBackend::StartFamilyProbe(const StoredSession& session) {
if (!family_log_ || (!family_perform_ && family_ca_bundle_.empty())) return false;
std::lock_guard<std::mutex> guard(family_start_mutex_);
- if (family_running_.load() || family_answered_.load()) return false;
+ if (family_running_.load() || family_no_group_.load() == session.steam_id) return false;
if (family_thread_.joinable()) family_thread_.join(); // finished
{
std::lock_guard<std::mutex> lock(family_mutex_);
family_licenses_published_ = false;
+ family_probe_done_ = false;
+ family_web_fresh_ = false;
}
family_running_.store(true);
family_thread_ = std::thread([this, session, perform = family_perform_, ca_bundle = family_ca_bundle_,
@@ -81,10 +89,22 @@ bool EntitledLibraryBackend::StartFamilyProbe(const StoredSession& session) {
const FamilyProbe probe = ProbeFamily(session, request, log, family_stop_);
const auto elapsed_ms = static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count());
- // Only Steam's answer ends the probing for this run: no family, or a family compared with known
- // licenses. A failure, or a family whose load had no licenses, is tried again by the next load.
- if (probe.outcome == FamilyProbe::Outcome::kNoGroup) family_answered_.store(true);
- if (probe.outcome == FamilyProbe::Outcome::kGroup && probe.library) {
+ // The family's games, for the load waiting on them (and later loads, until the next answer).
+ {
+ std::lock_guard<std::mutex> lock(family_mutex_);
+ if (probe.outcome == FamilyProbe::Outcome::kGroup && probe.library) {
+ family_web_account_ = session.steam_id;
+ family_web_fresh_ = true;
+ family_web_apps_.clear();
+ for (const auto& app : probe.library->apps) family_web_apps_[app.appid] = app;
+ }
+ family_probe_done_ = true;
+ }
+ family_cv_.notify_all();
+ // No family ends the probing for this run and account. A family is asked again by every load, since a
+ // member can share a game at any time; it is compared with known licenses in the log once per run.
+ if (probe.outcome == FamilyProbe::Outcome::kNoGroup) family_no_group_.store(session.steam_id);
+ if (probe.outcome == FamilyProbe::Outcome::kGroup && probe.library && !family_answered_.load()) {
// Compared with the licenses of the load that started the probe, once that load has them.
AcquisitionResult licenses;
bool known = false;
@@ -120,6 +140,10 @@ void EntitledLibraryBackend::PublishFamilyLicenses(const AcquisitionResult* lice
LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,
const std::atomic<bool>& cancel) {
+ // The background lookup shares the CM client: it stops here, and the load starts it again with what is
+ // still unknown.
+ StopLookups();
+ const auto started = std::chrono::steady_clock::now();
// The CM side gets its own flag so a failed or canceled owned fetch stops it promptly.
std::atomic<bool> stop{false};
std::atomic<bool> done{false};
@@ -152,13 +176,113 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,
if (found != acquisitions.acquired_at.end()) game.added_at_unix_seconds = found->second;
}
if (probing) PublishFamilyLicenses(&acquisitions);
- AddLicensedGames(session, acquisitions, cancel, &result);
+ bool family_fresh = false;
+ const auto family = FamilyApps(session.steam_id, probing, started, &family_fresh);
+ AddLicensedGames(session, acquisitions, family ? &*family : nullptr, family_fresh, cancel, &result);
return result;
}
+std::optional<std::map<std::uint32_t, SharedLibraryApp>> EntitledLibraryBackend::FamilyApps(
+ std::uint64_t steam_id, bool probing, std::chrono::steady_clock::time_point started, bool* fresh) {
+ *fresh = false;
+ if (!family_log_) return std::nullopt;
+ std::unique_lock<std::mutex> lock(family_mutex_);
+ // A load waits a little for its own probe (counted from the load's start); a slower answer is used by the
+ // next one. A load that started none uses the last answer.
+ if (probing)
+ family_cv_.wait_until(lock, started + family_wait_, [&] { return family_stop_.load() || family_probe_done_; });
+ if (family_web_account_ != steam_id) return std::nullopt;
+ *fresh = probing && family_web_fresh_;
+ return family_web_apps_;
+}
+
+namespace {
+
+std::uint64_t UnixNow() {
+ return static_cast<std::uint64_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());
+}
+
+// The Library's entry for a licensed app it knows the name of.
+GameSummary LicensedGame(std::uint32_t app, const AppName& name, bool shared,
+ const std::map<std::uint32_t, std::uint32_t>& acquired_at, std::uint32_t family_acquired) {
+ GameSummary game{GameId::Steam(app), name.name, {}, {}, {}};
+ game.demo = name.kind == AppName::Kind::kDemo;
+ game.family_shared = shared;
+ if (!name.icon.empty())
+ game.artwork_source = "https://media.steampowered.com/steamcommunity/public/images/apps/" + std::to_string(app) +
+ "/" + name.icon + ".jpg";
+ if (const auto added = acquired_at.find(app); added != acquired_at.end()) game.added_at_unix_seconds = added->second;
+ else if (family_acquired) game.added_at_unix_seconds = family_acquired;
+ return game;
+}
+
+// What PICS says an app is: a named game or demo, or something the Library leaves out (and why).
+std::optional<AppName> NameFromAppInfo(std::uint32_t app, const std::string& text, std::string* reason) {
+ const auto info = ParseAppInfo(app, text);
+ if (!info) {
+ *reason = "app_info_unreadable";
+ return std::nullopt;
+ }
+ std::string type = info->type;
+ std::transform(type.begin(), type.end(), type.begin(), [](unsigned char c) { return std::tolower(c); });
+ AppName name;
+ if ((type == "game" || type == "demo") && !info->name.empty() && info->name != "app_" + std::to_string(app)) {
+ name.kind = type == "demo" ? AppName::Kind::kDemo : AppName::Kind::kGame;
+ name.name = info->name;
+ name.icon = info->icon.size() <= 64 ? info->icon : std::string();
+ } else {
+ *reason = type != "game" && type != "demo" ? "type=" + (type.empty() ? std::string("none") : type.substr(0, 32))
+ : "no_name";
+ }
+ name.learned_at = UnixNow();
+ return name;
+}
+
+} // namespace
+
+void EntitledLibraryBackend::SetAppNameStorage(const Storage* storage) {
+ StopLookups();
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ names_storage_ = storage;
+ names_loaded_ = false;
+}
+
+void EntitledLibraryBackend::SetLateGamesCallback(std::function<void()> callback) {
+ std::lock_guard<std::mutex> lock(late_callback_mutex_);
+ late_callback_ = std::move(callback);
+}
+
+std::vector<GameSummary> EntitledLibraryBackend::TakeLateGames(std::uint64_t steam_id) {
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ if (late_context_.steam_id != steam_id) return {};
+ return std::exchange(late_games_, {});
+}
+
+void EntitledLibraryBackend::LoadNamesLocked() {
+ if (names_loaded_) return;
+ names_loaded_ = true;
+ if (names_storage_) names_ = LoadAppNames(*names_storage_);
+}
+
+void EntitledLibraryBackend::SaveNames() {
+ AppNames copy;
+ const Storage* storage = nullptr;
+ {
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ if (!names_dirty_ || !names_storage_) return;
+ names_dirty_ = false;
+ copy = names_;
+ storage = names_storage_;
+ }
+ if (!SaveAppNames(*storage, copy) && family_log_) family_log_("family names save=failed");
+}
+
void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,
const AcquisitionResult& acquisitions,
- const std::atomic<bool>& cancel, LibraryResult* result) {
+ const std::map<std::uint32_t, SharedLibraryApp>* family,
+ bool family_fresh, const std::atomic<bool>& cancel,
+ LibraryResult* result) {
const auto& shared = acquisitions.shared_apps;
std::set<std::uint32_t> listed;
for (const auto& game : result->games) listed.insert(*game.id.steam_app());
@@ -175,52 +299,16 @@ void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,
if (!listed.count(app)) candidates.insert(app);
}
- std::lock_guard<std::mutex> lock(looked_up_mutex_);
- std::vector<std::uint32_t> unknown;
- for (const auto app : candidates)
- if (!looked_up_.count(app)) unknown.push_back(app);
- for (std::size_t start = 0; start < unknown.size() && !cancel.load(); start += kMaxAppInfoBatch) {
- const std::vector<std::uint32_t> batch(
- unknown.begin() + static_cast<std::ptrdiff_t>(start),
- unknown.begin() + static_cast<std::ptrdiff_t>(std::min(start + kMaxAppInfoBatch, unknown.size())));
- const auto fetched = acquisitions_.FetchAppInfo(session, batch, cancel);
- // Unanswered apps are asked again on the next refresh.
- if (!fetched.ok()) break;
- for (const auto app : batch) {
- std::string name;
- std::string type;
- const auto found = fetched.buffers.find(app);
- const auto info = found != fetched.buffers.end() ? ParseAppInfo(app, found->second) : std::nullopt;
- if (info) {
- type = info->type;
- std::transform(type.begin(), type.end(), type.begin(), [](unsigned char c) { return std::tolower(c); });
- if ((type == "game" || type == "demo") && info->name != "app_" + std::to_string(app)) name = info->name;
- if (!name.empty() && type == "demo") demos_.insert(app);
- if (!name.empty() && !info->icon.empty())
- icons_[app] = "https://media.steampowered.com/steamcommunity/public/images/apps/" + std::to_string(app) +
- "/" + info->icon + ".jpg";
- }
- if (name.empty() && shared.count(app)) {
- // Why a shared app stays out of the Library, for the family log.
- std::string reason = found == fetched.buffers.end() ? "no_app_info"
- : !info ? "app_info_unreadable"
- : type != "game" && type != "demo"
- ? "type=" + (type.empty() ? std::string("none") : type.substr(0, 32))
- : "no_name";
- family_left_out_[app] = std::move(reason);
- }
- looked_up_[app] = name;
- }
- }
std::size_t added = 0;
std::size_t left_out = 0;
- std::size_t pending = 0;
+ std::size_t named_family = 0;
+ std::size_t named_saved = 0;
// Per-app lines are capped per load so a big family library can't rotate the license dump out of the
// log. An app's line counts as logged only once written, so the rest follow on later loads.
std::size_t written = 0;
std::size_t truncated = 0;
const auto detail = [&](std::set<std::uint32_t>& logged, std::uint32_t app, const std::string& line) {
- if (logged.count(app)) return;
+ if (!family_log_ || logged.count(app)) return;
if (written == kFamilyAppLineLimit) {
++truncated;
return;
@@ -229,46 +317,226 @@ void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,
logged.insert(app);
family_log_(line);
};
- for (const auto app : candidates) {
- const auto found = looked_up_.find(app);
- const bool is_shared = shared.count(app) != 0;
- if (found == looked_up_.end() || found->second.empty()) {
- if (!is_shared || !family_log_) continue;
- if (found == looked_up_.end()) {
- // PICS did not answer (or the load was canceled): asked again on the next refresh. Logged once per
- // app; a repeated failure only counts as pending.
- ++pending;
- if (!cancel.load())
- detail(family_failed_logged_, app, "family library left_out app=" + std::to_string(app) + " reason=app_info_failed");
+ std::vector<std::uint32_t> unknown;
+ {
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ LoadNamesLocked();
+ for (const auto app : candidates) {
+ const bool is_shared = shared.count(app) != 0;
+ std::uint32_t family_acquired = 0;
+ if (is_shared && family) {
+ // Steam's family service lists the family's games (and demos) by name. A shared app this load's
+ // answer leaves out is DLC or another non-game, and is not looked up. An older answer only names
+ // games: a game shared since then is looked up.
+ const auto found = family->find(app);
+ const bool game = found != family->end() && (found->second.app_type == kFamilyAppTypeGame ||
+ found->second.app_type == kFamilyAppTypeDemo);
+ if (game && !found->second.name.empty()) {
+ AppName& name = names_[app];
+ const auto kind = found->second.app_type == kFamilyAppTypeDemo ? AppName::Kind::kDemo : AppName::Kind::kGame;
+ if (name.kind != kind || name.name != found->second.name) {
+ name.kind = kind;
+ name.name = found->second.name;
+ name.learned_at = UnixNow();
+ names_dirty_ = true;
+ }
+ ++added;
+ ++named_family;
+ if (name.kind == AppName::Kind::kDemo) demos_.insert(app);
+ result->games.push_back(LicensedGame(app, name, true, acquisitions.acquired_at, found->second.rt_time_acquired));
+ detail(family_logged_, app, "family library added app=" + std::to_string(app) + " demo=" +
+ (name.kind == AppName::Kind::kDemo ? "1" : "0") + " source=family");
+ continue;
+ }
+ if (!game && !names_.count(app) && family_fresh) {
+ ++left_out;
+ detail(family_logged_, app, "family library left_out app=" + std::to_string(app) + " reason=" +
+ (found == family->end() ? std::string("not_in_family_list")
+ : "app_type=" + std::to_string(found->second.app_type)));
+ continue;
+ }
+ family_acquired = found != family->end() ? found->second.rt_time_acquired : 0;
+ }
+ const auto known = names_.find(app);
+ if (known == names_.end()) {
+ unknown.push_back(app);
continue;
}
- ++left_out;
- const auto reason = family_left_out_.find(app);
- detail(family_logged_, app, "family library left_out app=" + std::to_string(app) +
- " reason=" + (reason != family_left_out_.end() ? reason->second : std::string("no_name")));
- continue;
- }
- GameSummary game{GameId::Steam(app), found->second, {}, {}, {}};
- game.demo = demos_.count(app) != 0;
- game.family_shared = is_shared;
- if (const auto icon = icons_.find(app); icon != icons_.end()) game.artwork_source = icon->second;
- if (const auto added_at = acquisitions.acquired_at.find(app); added_at != acquisitions.acquired_at.end())
- game.added_at_unix_seconds = added_at->second;
- if (is_shared) {
- ++added;
- if (family_log_)
- detail(family_logged_, app, "family library added app=" + std::to_string(app) + " demo=" + (game.demo ? "1" : "0"));
+ if (known->second.kind == AppName::Kind::kOther) {
+ if (is_shared) {
+ ++left_out;
+ const auto reason = family_left_out_.find(app);
+ detail(family_logged_, app, "family library left_out app=" + std::to_string(app) + " reason=" +
+ (reason != family_left_out_.end() ? reason->second : std::string("not_a_game")));
+ }
+ continue;
+ }
+ if (is_shared) {
+ ++added;
+ ++named_saved;
+ detail(family_logged_, app, "family library added app=" + std::to_string(app) + " demo=" +
+ (known->second.kind == AppName::Kind::kDemo ? "1" : "0") + " source=saved");
+ }
+ result->games.push_back(LicensedGame(app, known->second, is_shared, acquisitions.acquired_at, family_acquired));
}
- result->games.push_back(std::move(game));
+ // What the background lookup still has to name, and what the Library needs to add each one.
+ late_context_ = {};
+ late_context_.steam_id = session.steam_id;
+ late_context_.shared = shared;
+ late_context_.acquired_at = acquisitions.acquired_at;
+ late_context_.wanted.insert(unknown.begin(), unknown.end());
+ if (family)
+ for (const auto app : unknown)
+ if (const auto found = family->find(app); found != family->end())
+ late_context_.family_acquired[app] = found->second.rt_time_acquired;
+ late_games_.clear();
}
if (family_log_) {
if (truncated) family_log_("family library truncated=" + std::to_string(truncated));
std::size_t in_owned_list = 0;
for (const auto app : shared) in_owned_list += listed.count(app);
+ std::size_t pending = 0;
+ for (const auto app : unknown) pending += shared.count(app);
family_log_("family library shared=" + std::to_string(shared.size()) + " added=" + std::to_string(added) +
" left_out=" + std::to_string(left_out) + " pending=" + std::to_string(pending) +
- " in_owned_list=" + std::to_string(in_owned_list));
+ " in_owned_list=" + std::to_string(in_owned_list) + " named_family=" + std::to_string(named_family) +
+ " named_saved=" + std::to_string(named_saved) +
+ " family_list=" + (!family ? "n" : family_fresh ? "y" : "stale") +
+ " lookups=" + std::to_string(unknown.size()));
+ }
+ if (unknown.empty() || cancel.load()) {
+ SaveNames();
+ return;
+ }
+ StartLookups(session, std::move(unknown));
+}
+
+void EntitledLibraryBackend::StopLookups() {
+ std::lock_guard<std::mutex> guard(lookup_start_mutex_);
+ lookup_stop_.store(true);
+ if (lookup_thread_.joinable()) lookup_thread_.join();
+ lookup_stop_.store(false);
+}
+
+void EntitledLibraryBackend::StartLookups(const StoredSession& session, std::vector<std::uint32_t> apps) {
+ std::lock_guard<std::mutex> guard(lookup_start_mutex_);
+ if (lookup_thread_.joinable()) lookup_thread_.join();
+ lookup_running_.store(true);
+ lookup_thread_ = std::thread([this, session, apps = std::move(apps)] {
+ RunLookups(session, apps);
+ lookup_running_.store(false);
+ });
+}
+
+bool EntitledLibraryBackend::WaitForLookups(std::chrono::milliseconds timeout) {
+ const auto deadline = std::chrono::steady_clock::now() + timeout;
+ while (lookup_running_.load()) {
+ if (std::chrono::steady_clock::now() > deadline) return false;
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+ return true;
+}
+
+// Names one app from its app info, and queues it for the Library when it is a game this load wanted.
+bool EntitledLibraryBackend::Record(std::uint32_t app, const std::string& text) {
+ std::string reason;
+ auto name = NameFromAppInfo(app, text, &reason);
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ if (!name) {
+ if (late_context_.shared.count(app)) family_left_out_[app] = reason;
+ return false;
+ }
+ if (name->kind == AppName::Kind::kOther && late_context_.shared.count(app)) family_left_out_[app] = reason;
+ if (name->kind == AppName::Kind::kDemo) demos_.insert(app);
+ const bool wanted = late_context_.wanted.erase(app) != 0;
+ names_[app] = *name;
+ names_dirty_ = true;
+ if (!wanted || name->kind == AppName::Kind::kOther) return false;
+ const auto family_acquired = late_context_.family_acquired.find(app);
+ late_games_.push_back(LicensedGame(app, *name, late_context_.shared.count(app) != 0, late_context_.acquired_at,
+ family_acquired != late_context_.family_acquired.end() ? family_acquired->second
+ : 0));
+ return true;
+}
+
+void EntitledLibraryBackend::RecordOther(std::uint32_t app, const std::string& reason) {
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ if (late_context_.shared.count(app)) family_left_out_[app] = reason;
+ late_context_.wanted.erase(app);
+ AppName name;
+ name.learned_at = UnixNow();
+ names_[app] = std::move(name);
+ names_dirty_ = true;
+}
+
+void EntitledLibraryBackend::PublishLateGames() {
+ {
+ std::lock_guard<std::mutex> lock(names_mutex_);
+ if (late_games_.empty()) return;
+ }
+ std::lock_guard<std::mutex> lock(late_callback_mutex_);
+ if (late_callback_) late_callback_();
+}
+
+// Names the apps a load could not, off the load: PICS in batches, then the hash-only ones over HTTP a few at
+// a time. Games are handed to the Library after each batch. A failed batch ends the pass; what is still
+// unknown is asked again by the next load.
+void EntitledLibraryBackend::RunLookups(const StoredSession& session, const std::vector<std::uint32_t>& apps) {
+ const auto start = std::chrono::steady_clock::now();
+ if (family_log_) family_log_("family lookup start apps=" + std::to_string(apps.size()));
+ std::size_t games = 0;
+ std::size_t by_hash = 0;
+ std::size_t unanswered = 0;
+ std::string error;
+ const auto make_perform = [this]() -> AppInfoPerform {
+ if (family_perform_) return family_perform_;
+ if (family_ca_bundle_.empty()) return nullptr;
+ auto client = std::make_shared<HttpClient>(family_ca_bundle_);
+ return [client](const HttpRequest& request, const std::atomic<bool>& stop) { return client->Perform(request, stop); };
+ };
+ for (std::size_t first = 0; first < apps.size() && !lookup_stop_.load(); first += kMaxAppInfoBatch) {
+ const std::vector<std::uint32_t> batch(
+ apps.begin() + static_cast<std::ptrdiff_t>(first),
+ apps.begin() + static_cast<std::ptrdiff_t>(std::min(first + kMaxAppInfoBatch, apps.size())));
+ const auto fetched = acquisitions_.FetchAppInfoPics(session, batch, lookup_stop_);
+ if (!fetched.ok()) {
+ if (fetched.error != CmError::kCanceled) error = CmErrorName(fetched.error);
+ break;
+ }
+ std::size_t answered = fetched.buffers.size();
+ for (const auto& [app, text] : fetched.buffers) games += Record(app, text);
+ // Apps Steam doesn't know, or describes with nothing, are no games; a refused token is asked again.
+ for (const auto& [app, reason] : fetched.unanswered)
+ if (reason == "unknown" || reason == "empty") {
+ RecordOther(app, "no_app_info:" + reason);
+ ++answered;
+ }
+ if (!fetched.hashed.empty()) {
+ AppInfoHttpStats http;
+ const auto texts = FetchAppInfoByHash(make_perform, fetched.http_host, fetched.hashed, kAppInfoHttpWorkers,
+ lookup_stop_, &http, [&](std::uint32_t app, const std::string& text) {
+ games += Record(app, text);
+ });
+ by_hash += texts.size();
+ answered += texts.size();
+ if (family_log_)
+ family_log_("family lookup http=" + std::to_string(fetched.hashed.size()) + " fetched=" +
+ std::to_string(http.fetched) + " failed=" + std::to_string(http.failed) + " skipped=" +
+ std::to_string(http.skipped) + " connections=" + std::to_string(http.new_connections) +
+ " ms=" + std::to_string(http.total_ms) + (http.error.empty() ? "" : " error=" + http.error));
+ }
+ unanswered += batch.size() - answered;
+ SaveNames();
+ PublishLateGames();
}
+ SaveNames();
+ PublishLateGames();
+ if (family_log_)
+ family_log_("family lookup end games=" + std::to_string(games) + " by_hash=" + std::to_string(by_hash) +
+ " unanswered=" + std::to_string(unanswered) + (error.empty() ? "" : " error=" + error) +
+ (lookup_stop_.load() ? " stopped=1" : "") + " elapsed_ms=" +
+ std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - start).count()));
}
} // namespace playden::steam
diff --git a/src/steam/backend/entitled_library.h b/src/steam/backend/entitled_library.h
index 90c780a..298996a 100644
--- a/src/steam/backend/entitled_library.h
+++ b/src/steam/backend/entitled_library.h
@@ -1,12 +1,17 @@
#pragma once
+#include "steam/backend/app_names.h"
#include "steam/backend/cm_client.h"
#include "steam/backend/family_groups.h"
#include "steam/library_backend.h"
#include <atomic>
+#include <chrono>
#include <condition_variable>
+#include <functional>
+#include <map>
#include <memory>
+#include <optional>
#include <mutex>
#include <set>
#include <string>
@@ -19,10 +24,12 @@ namespace playden::steam {
// The owned library from GetOwnedGames, enriched with CM acquisition dates. As in the macOS
// reference, both run in parallel and a CM failure is never fatal: games then simply lack a date.
// A CM logon rejection never reports revoked credentials.
-// GetOwnedGames leaves out free-to-play games added to the library but never played. Licensed
-// packages none of whose apps are listed are looked up in PICS, and their games and demos (marked)
-// are added. Each app is looked up once per run, so after the first load a refresh only asks about
-// new licenses. Apps only a Steam family member's licenses grant are marked family_shared.
+// GetOwnedGames leaves out free-to-play games added to the library but never played. The apps of licensed
+// packages none of whose apps are listed are added when they are games or demos (marked). Apps only a Steam
+// family member's licenses grant are marked family_shared.
+// A load never waits for app lookups. It names apps from Steam's family service (the family's games), from
+// saved names, and leaves the rest to a background lookup (PICS, then Steam's HTTP host by hash), which hands
+// each game it names to the Library as TakeLateGames. Names are saved, so each app is looked up once.
class EntitledLibraryBackend final : public LibraryBackend {
public:
EntitledLibraryBackend(LibraryBackend& owned, AcquisitionSource& acquisitions)
@@ -31,15 +38,24 @@ class EntitledLibraryBackend final : public LibraryBackend {
~EntitledLibraryBackend() override;
LibraryResult Fetch(const StoredSession& session, const std::atomic<bool>& cancel) override;
+ std::vector<GameSummary> TakeLateGames(std::uint64_t steam_id) override;
+ void SetLateGamesCallback(std::function<void()> callback) override;
+ // Where app names are saved (app-names.cache); without it they last for the run. Set before the first Fetch.
+ void SetAppNameStorage(const Storage* storage);
+ // For tests: waits until no background lookup runs. False on timeout.
+ bool WaitForLookups(std::chrono::milliseconds timeout);
+ // For tests: how long a load waits for the family service's games (4 s by default).
+ void SetFamilyWait(std::chrono::milliseconds wait) { family_wait_ = wait; }
// Receives each successful license read, for size estimates.
void SetLicensedDepots(LicensedDepots* licensed) { licensed_ = licensed; }
- // Writes "family" lines: which family-shared apps the Library got or left out, and what Steam's family
- // service lists, asked over HTTPS (with this CA bundle) on a thread of its own until it answers once this
- // run. A load starts it when none runs and never waits for it. Purely diagnostic: its failures are log
- // lines. Off until set; set it before the first Fetch, as it is not synchronized with a running one.
+ // Asks Steam's family service over HTTPS (with this CA bundle; the background lookup's HTTP uses it too)
+ // and writes "family" lines: which family-shared apps the Library got or left out, and what the service
+ // lists. The service is asked on a thread of its own by each load (none while one runs); a load waits for
+ // it a few seconds at most, and its failures are log lines. Off until set; set it before the first Fetch,
+ // as it is not synchronized with a running one.
void SetFamilyDiagnostics(std::string ca_bundle, FamilyLog log);
- // For tests: the family service requests go to `perform`.
+ // For tests: the family service and the by-hash app info requests go to `perform`.
void SetFamilyDiagnostics(FamilyPerform perform, FamilyLog log);
// Category of the most recent CM attempt, for diagnostics without identifiers.
@@ -51,19 +67,52 @@ class EntitledLibraryBackend final : public LibraryBackend {
void StopFamilyProbe();
// Hands the license sets of the load that started the probe (or that it had none) to the probe.
void PublishFamilyLicenses(const AcquisitionResult* licenses);
+ // The family service's apps for this account: this load's answer (waited for until `started` + the
+ // family wait), or the last one. None without an answer for the account.
+ // `fresh` says the answer is this load's own; only then does it tell which shared apps are no games.
+ std::optional<std::map<std::uint32_t, SharedLibraryApp>> FamilyApps(std::uint64_t steam_id, bool probing,
+ std::chrono::steady_clock::time_point started,
+ bool* fresh);
void AddLicensedGames(const StoredSession& session, const AcquisitionResult& acquisitions,
+ const std::map<std::uint32_t, SharedLibraryApp>* family, bool family_fresh,
const std::atomic<bool>& cancel, LibraryResult* result);
+ void LoadNamesLocked();
+ void SaveNames();
+ void StartLookups(const StoredSession& session, std::vector<std::uint32_t> apps);
+ void StopLookups();
+ void RunLookups(const StoredSession& session, const std::vector<std::uint32_t>& apps);
+ bool Record(std::uint32_t app, const std::string& text);
+ void RecordOther(std::uint32_t app, const std::string& reason);
+ void PublishLateGames();
LibraryBackend& owned_;
AcquisitionSource& acquisitions_;
LicensedDepots* licensed_ = nullptr;
std::atomic<CmError> last_error_{CmError::kNone};
- // App ID -> its name when PICS calls it a game or a demo, empty when it is something else or
- // undescribed. Demos are also in demos_.
- std::mutex looked_up_mutex_;
- std::unordered_map<std::uint32_t, std::string> looked_up_;
- std::unordered_map<std::uint32_t, std::string> icons_;
+ // What each looked-up app is, loaded from names_storage_ on the first load. The load and the background
+ // lookup take names_mutex_ for it and for the late games.
+ std::mutex names_mutex_;
+ const Storage* names_storage_ = nullptr;
+ AppNames names_;
+ bool names_loaded_ = false;
+ bool names_dirty_ = false;
std::unordered_set<std::uint32_t> demos_;
+ // The last load's licensed apps, for games the background lookup names after it returned.
+ struct LateContext {
+ std::uint64_t steam_id = 0;
+ std::set<std::uint32_t> shared;
+ std::map<std::uint32_t, std::uint32_t> acquired_at;
+ std::map<std::uint32_t, std::uint32_t> family_acquired;
+ std::set<std::uint32_t> wanted;
+ };
+ LateContext late_context_;
+ std::vector<GameSummary> late_games_;
+ std::mutex late_callback_mutex_;
+ std::function<void()> late_callback_;
+ std::mutex lookup_start_mutex_;
+ std::thread lookup_thread_;
+ std::atomic<bool> lookup_stop_{false};
+ std::atomic<bool> lookup_running_{false};
// Shared apps PICS left out -> why, and the shared apps whose outcome is already logged this run.
std::unordered_map<std::uint32_t, std::string> family_left_out_;
std::set<std::uint32_t> family_logged_;
@@ -78,7 +127,11 @@ class EntitledLibraryBackend final : public LibraryBackend {
std::mutex family_start_mutex_;
std::thread family_thread_;
std::atomic<bool> family_running_{false};
+ // The family compared with licenses in the log this run.
std::atomic<bool> family_answered_{false};
+ // The account the family service said has no family: not asked again this run.
+ std::atomic<std::uint64_t> family_no_group_{0};
+ std::chrono::milliseconds family_wait_{4000};
std::atomic<bool> family_stop_{false};
// The license sets of the load that started the probe, for the comparison, once it published them.
std::mutex family_mutex_;
@@ -87,6 +140,11 @@ class EntitledLibraryBackend final : public LibraryBackend {
bool family_licenses_ok_ = false;
std::set<std::uint32_t> family_shared_apps_;
std::set<std::uint32_t> family_owned_apps_;
+ // The family service's last answer (family_mutex_), and whether this load's probe has answered.
+ std::uint64_t family_web_account_ = 0;
+ std::map<std::uint32_t, SharedLibraryApp> family_web_apps_;
+ bool family_probe_done_ = true;
+ bool family_web_fresh_ = false; // family_web_apps_ came from the probe started last
};
} // namespace playden::steam
diff --git a/src/steam/backend/family_groups.cpp b/src/steam/backend/family_groups.cpp
index 387bb9d..ffdb1bd 100644
--- a/src/steam/backend/family_groups.cpp
+++ b/src/steam/backend/family_groups.cpp
@@ -17,6 +17,7 @@ constexpr std::uint32_t kRequestTimeoutMs = 6000;
constexpr std::size_t kMemberLimit = 32;
constexpr std::size_t kAppLimit = 20000;
constexpr std::size_t kOwnerLimit = 32;
+constexpr std::size_t kNameLimit = 1024;
constexpr std::size_t kAppLineLimit = 200;
bool Unreserved(unsigned char byte) {
@@ -148,6 +149,12 @@ std::optional<SharedLibrary> ParseSharedLibraryApps(std::string_view body) {
}
}
app.exclude_reason = Id(item.Find("exclude_reason")).value_or(0);
+ if (const auto* name = item.Find("name"); name && name->is_string() && name->text().size() <= kNameLimit)
+ app.name = name->text();
+ app.app_type = Id(item.Find("app_type")).value_or(kFamilyAppTypeGame);
+ if (const auto acquired = Id(item.Find("rt_time_acquired"));
+ acquired && *acquired <= std::numeric_limits<std::uint32_t>::max())
+ app.rt_time_acquired = static_cast<std::uint32_t>(*acquired);
library.apps.push_back(std::move(app));
}
return library;
diff --git a/src/steam/backend/family_groups.h b/src/steam/backend/family_groups.h
index 35b3e4c..d4ad66c 100644
--- a/src/steam/backend/family_groups.h
+++ b/src/steam/backend/family_groups.h
@@ -15,8 +15,8 @@
namespace playden::steam {
-// Diagnostics only: what IFamilyGroupsService says about the account's Steam family, to compare with the
-// licenses the CM sent. Nothing here adds games or affects a library load.
+// What IFamilyGroupsService says about the account's Steam family: the games it shares, by name (the Library
+// adds them without a PICS lookup), and log lines comparing them with the licenses the CM sent.
using FamilyPerform = std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)>;
using FamilyLog = std::function<void(const std::string& line)>;
@@ -34,10 +34,17 @@ struct FamilyGroup {
std::vector<FamilyMember> members;
};
+// EAppType values in SharedApp.app_type.
+inline constexpr std::uint64_t kFamilyAppTypeGame = 1;
+inline constexpr std::uint64_t kFamilyAppTypeDemo = 8;
+
struct SharedLibraryApp {
std::uint32_t appid = 0;
std::vector<std::uint64_t> owners;
std::uint64_t exclude_reason = 0; // 0: shared; anything else is Steam's reason it is not
+ std::string name;
+ std::uint64_t app_type = kFamilyAppTypeGame; // Steam's default when the field is absent
+ std::uint32_t rt_time_acquired = 0;
};
// GetSharedLibraryApps.
diff --git a/src/steam/library_backend.h b/src/steam/library_backend.h
index 5fee2b1..22eb8a9 100644
--- a/src/steam/library_backend.h
+++ b/src/steam/library_backend.h
@@ -4,6 +4,8 @@
#include "steam/session_store.h"
#include <atomic>
+#include <cstdint>
+#include <functional>
#include <vector>
namespace playden::steam {
@@ -31,6 +33,11 @@ class LibraryBackend {
virtual ~LibraryBackend() = default;
virtual LibraryResult Fetch(const StoredSession& session,
const std::atomic<bool>& cancel) = 0;
+ // Games named after Fetch returned (looked up in the background), for that load's account; each is
+ // handed over once. None by default.
+ virtual std::vector<playden::GameSummary> TakeLateGames(std::uint64_t /*steam_id*/) { return {}; }
+ // Called from the backend's own thread when TakeLateGames has games. It must only queue work.
+ virtual void SetLateGamesCallback(std::function<void()> /*callback*/) {}
};
} // namespace playden::steam
diff --git a/tests/cm_client_test.cpp b/tests/cm_client_test.cpp
index bb8aac2..c864066 100644
--- a/tests/cm_client_test.cpp
+++ b/tests/cm_client_test.cpp
@@ -982,6 +982,137 @@ void AppInfoUsesAccessTokensAndCollectsMultipartBuffers() {
assert(client.FetchAppInfo(Session(), {}, cancel).error == CmError::kProtocol);
}
+// Apps that come back without a buffer are named with the reason, and the batch gets one log line.
+void AppInfoNamesWhyAppsWereNotAnswered() {
+ auto script = std::make_shared<Script>();
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9))};
+ proto::Writer tokens;
+ tokens.AddVarint(4, 50); // token denied
+ script->on_emsg[cm::kEMsgClientPICSAccessTokenRequest] = {
+ ServerFrame(cm::kEMsgClientPICSAccessTokenResponse, tokens.bytes(), std::nullopt, 1)};
+ proto::Writer response;
+ auto add_app = [&](std::uint32_t id, bool missing_token, bool sha, const std::string& text) {
+ proto::Writer app;
+ app.AddVarint(1, id);
+ if (missing_token) app.AddVarint(3, 1);
+ if (sha) app.AddBytes(4, std::vector<std::uint8_t>{0xab, 0x01});
+ if (!text.empty()) app.AddBytes(5, std::vector<std::uint8_t>(text.begin(), text.end()));
+ if (sha) app.AddVarint(7, 4096);
+ response.AddMessage(1, app);
+ };
+ add_app(10, false, false, "\"appinfo\" { }");
+ add_app(20, true, false, "");
+ add_app(30, false, true, "");
+ add_app(50, true, false, "");
+ response.AddVarint(2, 40);
+ response.AddVarint(7, 2048);
+ response.AddString(8, "cache.example");
+ script->on_emsg[cm::kEMsgClientPICSProductInfoRequest] = {
+ ServerFrame(cm::kEMsgClientPICSProductInfoResponse, response.bytes(), std::nullopt, 2)};
+ std::vector<std::string> lines;
+ SetCmLog([&](const std::string& line) { lines.push_back(line); });
+ auto client = MakeClient(script);
+ std::atomic<bool> cancel{false};
+ const auto result = client.FetchAppInfo(Session(), {10, 20, 30, 40, 50, 60}, cancel);
+ SetCmLog(nullptr);
+ assert(result.ok() && result.buffers.size() == 1 && result.buffers.count(10));
+ assert((result.unanswered == std::map<std::uint32_t, std::string>{
+ {20, "missing_token"}, {30, "http"}, {40, "unknown"}, {50, "token_denied"}, {60, "absent"}}));
+ const auto line = std::find_if(lines.begin(), lines.end(),
+ [](const std::string& l) { return l.find("step=app_info ") != std::string::npos; });
+ assert(line != lines.end());
+ // App 30's two-byte hash can't name a copy, so nothing is fetched over HTTP.
+ assert(line->find("requested=6 answered=1 parts=1 tokens=0 denied=1 offloaded=1 http_fetched=0 http_failed=1 http_skipped=0 "
+ "http_connections=0 http_ms=0 "
+ "absent=1 http=1 missing_token=1 token_denied=1 unknown=1 http_min_size=2048 "
+ "http_host=cache.example") != std::string::npos);
+}
+
+// A VDF Steam serves only by hash is fetched from the clientconfig host and kept when it matches.
+void AppInfoFetchesHashOnlyAppsOverHttp() {
+ // gzip of "\"appinfo\" { \"appid\" \"30\" }" plus its NUL (27 bytes), and the SHA-1 of the text.
+ const std::vector<std::uint8_t> gz = {
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x53, 0x4a, 0x2c, 0x28, 0xc8,
+ 0xcc, 0x4b, 0xcb, 0x57, 0x52, 0xa8, 0x56, 0x50, 0x02, 0xb1, 0x53, 0x94, 0x14, 0x94, 0x8c,
+ 0x0d, 0x94, 0x14, 0x6a, 0x19, 0x00, 0xd1, 0x24, 0x53, 0xe3, 0x1b, 0x00, 0x00, 0x00};
+ const std::vector<std::uint8_t> sha = {0x32, 0x58, 0xf0, 0xc7, 0xb5, 0xd5, 0x30, 0xaf, 0x77, 0xca,
+ 0x1d, 0xb0, 0x54, 0x58, 0xcb, 0xe8, 0x60, 0xf7, 0x47, 0xa8};
+ auto run = [&](const std::vector<std::uint8_t>& pics_sha, std::function<HttpResponse(const HttpRequest&)> serve,
+ std::vector<std::string>* urls, std::vector<std::string>* lines) {
+ auto script = std::make_shared<Script>();
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9))};
+ script->on_emsg[cm::kEMsgClientPICSAccessTokenRequest] = {
+ ServerFrame(cm::kEMsgClientPICSAccessTokenResponse, {}, std::nullopt, 1)};
+ proto::Writer response;
+ for (const std::uint32_t id : {30u, 31u}) {
+ proto::Writer app;
+ app.AddVarint(1, id);
+ app.AddBytes(4, pics_sha);
+ app.AddVarint(7, 27);
+ response.AddMessage(1, app);
+ }
+ script->on_emsg[cm::kEMsgClientPICSProductInfoRequest] = {
+ ServerFrame(cm::kEMsgClientPICSProductInfoResponse, response.bytes(), std::nullopt, 2)};
+ CmClientHooks hooks;
+ hooks.directory = [](const HttpRequest&, const std::atomic<bool>&) { return Directory(kTwoEndpoints); };
+ auto urls_mutex = std::make_shared<std::mutex>();
+ hooks.app_info = [&, urls_mutex](const HttpRequest& request, const std::atomic<bool>&) {
+ {
+ // Fetches run on several workers at once.
+ std::lock_guard<std::mutex> lock(*urls_mutex);
+ urls->push_back(request.url);
+ }
+ return serve(request);
+ };
+ hooks.transport = [script] { return std::make_unique<FakeTransport>(script); };
+ hooks.unix_now = [] { return std::uint64_t{1700000000}; };
+ hooks.deadline_ms = 3000;
+ CmClient client(hooks, MakeDeviceIdentity(kSeed));
+ SetCmLog([lines](const std::string& line) { lines->push_back(line); });
+ std::atomic<bool> cancel{false};
+ auto result = client.FetchAppInfo(Session(), {30, 31}, cancel);
+ SetCmLog(nullptr);
+ return result;
+ };
+ auto has = [](const std::vector<std::string>& lines, const std::string& text) {
+ return std::any_of(lines.begin(), lines.end(), [&](const std::string& l) { return l.find(text) != std::string::npos; });
+ };
+
+ // App 30's copy matches; app 31 shares the hash, so its copy (also app 30's text) matches too.
+ std::vector<std::string> urls, lines;
+ auto result = run(sha, [&](const HttpRequest&) {
+ HttpResponse ok;
+ ok.status_code = 200;
+ ok.body = gz;
+ return ok;
+ }, &urls, &lines);
+ assert(result.ok() && result.buffers.size() == 2 && result.unanswered.empty());
+ assert(result.buffers.at(30) == "\"appinfo\" { \"appid\" \"30\" }");
+ assert(urls.size() == 2 && std::count(urls.begin(), urls.end(),
+ "https://clientconfig.akamai.steamstatic.com/appinfo/30/sha/"
+ "3258f0c7b5d530af77ca1db05458cbe860f747a8.txt.gz") == 1);
+ assert(has(lines, "offloaded=2 http_fetched=2 http_failed=0"));
+
+ // A copy that doesn't match the hash is refused; a host that can't be reached stops the rest.
+ urls.clear();
+ lines.clear();
+ auto other = sha;
+ other[0] ^= 1;
+ result = run(other, [&](const HttpRequest& request) {
+ HttpResponse response;
+ if (request.url.find("/appinfo/31/") != std::string::npos) {
+ response.error = HttpError::kConnectionFailed;
+ return response;
+ }
+ response.status_code = 200;
+ response.body = gz;
+ return response;
+ }, &urls, &lines);
+ assert(result.ok() && result.buffers.empty());
+ assert((result.unanswered == std::map<std::uint32_t, std::string>{{30, "http"}, {31, "http"}}));
+ assert(urls.size() == 2 && has(lines, "offloaded=2 http_fetched=0 http_failed=1 http_skipped=1 ") && has(lines, "http_error="));
+}
+
std::shared_ptr<Script> DepotScript(std::int32_t key_result, std::uint64_t code) {
auto script = std::make_shared<Script>();
script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9))};
@@ -1236,6 +1367,8 @@ int main(int argc, char** argv) {
RefusedServiceCallIsNotARefusedLogon();
ResetCmBackoff();
AppInfoUsesAccessTokensAndCollectsMultipartBuffers();
+ AppInfoNamesWhyAppsWereNotAnswered();
+ AppInfoFetchesHashOnlyAppsOverHttp();
ResetCmBackoff();
DepotAccessReturnsKeysAndManifestCodes();
ResetCmBackoff();
diff --git a/tests/entitled_library_test.cpp b/tests/entitled_library_test.cpp
index 7ec664d..bb9ef4f 100644
--- a/tests/entitled_library_test.cpp
+++ b/tests/entitled_library_test.cpp
@@ -1,5 +1,7 @@
#include "steam/backend/entitled_library.h"
+#include <unistd.h>
+
#include <algorithm>
#include <atomic>
#include <cassert>
@@ -29,17 +31,31 @@ struct Acquisitions final : AcquisitionSource {
bool block_until_stopped = false;
std::atomic<bool> saw_stop{false};
std::map<std::uint32_t, std::string> app_info;
+ std::map<std::uint32_t, std::string> unanswered; // why the CM sent no buffer, for apps not in app_info
+ std::map<std::uint32_t, HashedAppInfo> hashed; // apps PICS answers with a hash only
+ std::mutex requests_mutex;
std::vector<std::vector<std::uint32_t>> app_info_requests;
- bool fail_app_info = false;
+ std::atomic<bool> fail_app_info{false};
AppInfoBuffers FetchAppInfo(const StoredSession&, const std::vector<std::uint32_t>& ids,
const std::atomic<bool>&) override {
- app_info_requests.push_back(ids);
+ {
+ std::lock_guard<std::mutex> lock(requests_mutex);
+ app_info_requests.push_back(ids);
+ }
if (fail_app_info) return {CmError::kNetwork, {}};
AppInfoBuffers result{CmError::kNone, {}};
for (const auto id : ids)
if (const auto found = app_info.find(id); found != app_info.end()) result.buffers[id] = found->second;
+ else if (const auto hash = hashed.find(id); hash != hashed.end()) {
+ result.unanswered[id] = "http";
+ result.hashed[id] = hash->second;
+ } else if (const auto reason = unanswered.find(id); reason != unanswered.end()) result.unanswered[id] = reason->second;
return result;
}
+ std::vector<std::vector<std::uint32_t>> Requests() {
+ std::lock_guard<std::mutex> lock(requests_mutex);
+ return app_info_requests;
+ }
AcquisitionResult FetchAcquisitionDates(const StoredSession&, const std::atomic<bool>& cancel) override {
while (block_until_stopped) {
if (cancel) {
@@ -54,6 +70,73 @@ struct Acquisitions final : AcquisitionSource {
StoredSession Session() { return StoredSession{123, "synthetic", "refresh", "access", {}}; }
+std::string AppInfoText(std::uint32_t id, const std::string& name, const std::string& type) {
+ return "\"appinfo\"\n{\n\t\"appid\"\t\"" + std::to_string(id) + "\"\n\t\"common\"\n\t{\n\t\t\"name\"\t\"" + name +
+ "\"\n\t\t\"type\"\t\"" + type + "\"\n\t\t\"icon\"\t\"abc123\"\n\t}\n}\n";
+}
+
+// A load, the background lookup it started, then a load that lists what the lookup named.
+LibraryResult Settled(EntitledLibraryBackend& backend, const StoredSession& session = Session()) {
+ std::atomic<bool> cancel{false};
+ backend.Fetch(session, cancel);
+ assert(backend.WaitForLookups(5s));
+ return backend.Fetch(session, cancel);
+}
+
+
+// Declared before the backend in each test: the family probe thread may still log while the backend stops it.
+struct Lines {
+ std::mutex mutex;
+ std::vector<std::string> lines;
+ FamilyLog Log() {
+ return [this](const std::string& line) {
+ std::lock_guard<std::mutex> lock(mutex);
+ std::printf("%s\n", line.c_str());
+ lines.push_back(line);
+ };
+ }
+ std::size_t Count(const std::string& text) {
+ std::lock_guard<std::mutex> lock(mutex);
+ return static_cast<std::size_t>(std::count_if(lines.begin(), lines.end(), [&](const auto& line) {
+ return line.find(text) != std::string::npos;
+ }));
+ }
+};
+
+// Waits for a line written by the family probe thread.
+bool WaitFor(Lines& lines, const std::string& text, std::size_t count = 1) {
+ const auto deadline = std::chrono::steady_clock::now() + 5s;
+ while (lines.Count(text) < count) {
+ if (std::chrono::steady_clock::now() > deadline) return false;
+ std::this_thread::sleep_for(1ms);
+ }
+ return true;
+}
+
+const GameSummary* Find(const LibraryResult& result, std::uint32_t app) {
+ const auto found = std::find_if(result.games.begin(), result.games.end(),
+ [&](const auto& game) { return game.id == SteamId(app); });
+ return found == result.games.end() ? nullptr : &*found;
+}
+
+// The family probe is off in these: no requests are answered.
+FamilyPerform NoFamilyService() {
+ return [](const HttpRequest&, const std::atomic<bool>&) {
+ HttpResponse response;
+ response.error = HttpError::kConnectionFailed;
+ return response;
+ };
+}
+
+
+HttpResponse Json(const std::string& body, long status = 200) {
+ HttpResponse response;
+ response.status_code = status;
+ response.body.assign(body.begin(), body.end());
+ return response;
+}
+
+
void DatesMergeIntoOwnedGames() {
Owned owned;
Acquisitions acquisitions;
@@ -130,13 +213,9 @@ void CancelReachesARunningCmSession() {
assert(!result.games[0].added_at_unix_seconds);
}
-std::string AppInfoText(std::uint32_t id, const std::string& name, const std::string& type) {
- return "\"appinfo\"\n{\n\t\"appid\"\t\"" + std::to_string(id) + "\"\n\t\"common\"\n\t{\n\t\t\"name\"\t\"" + name +
- "\"\n\t\t\"type\"\t\"" + type + "\"\n\t\t\"icon\"\t\"abc123\"\n\t}\n}\n";
-}
-
// A free-to-play game added with "Add to library" and never played: GetOwnedGames leaves it out,
-// its free license names it. Packages with a listed game, DLC and tools add nothing.
+// its free license names it. Packages with a listed game, DLC and tools add nothing. The load never waits for
+// the lookup: it lists the game once the background lookup named it.
void LicensedFreeGamesAreAdded() {
Owned owned;
Acquisitions acquisitions;
@@ -145,34 +224,39 @@ void LicensedFreeGamesAreAdded() {
{100, {10, 11}}, // a bought game and its DLC
{200, {2767030}}, // the free game
{300, {30}}, // DLC bought on its own
- {400, {40}}}; // an app Steam doesn't describe
+ {400, {40}}}; // an app Steam doesn't know
acquisitions.app_info = {{2767030, AppInfoText(2767030, "Synthetic Rivals", "Game")},
{30, AppInfoText(30, "Synthetic DLC", "DLC")},
{480, AppInfoText(480, "Spacewar", "Game")}};
+ acquisitions.unanswered = {{40, "unknown"}};
EntitledLibraryBackend backend(owned, acquisitions);
std::atomic<bool> cancel{false};
auto result = backend.Fetch(Session(), cancel);
- assert(result.error == LibraryError::kNone && result.games.size() == 3);
- const auto& added = result.games.back();
+ assert(result.error == LibraryError::kNone && result.games.size() == 2);
+ assert(backend.WaitForLookups(5s));
+ // Handed over once, for the load's account only.
+ assert(backend.TakeLateGames(456).empty());
+ auto late = backend.TakeLateGames(123);
+ assert(late.size() == 1 && backend.TakeLateGames(123).empty());
+ const auto& added = late.back();
assert(added.id == SteamId(2767030) && added.title == "Synthetic Rivals" && added.added_at_unix_seconds == 1700000000u);
assert(added.artwork_source == "https://media.steampowered.com/steamcommunity/public/images/apps/2767030/abc123.jpg");
- assert(acquisitions.app_info_requests.size() == 1);
- assert((acquisitions.app_info_requests[0] == std::vector<std::uint32_t>{30, 40, 2767030}));
+ assert((acquisitions.Requests() == std::vector<std::vector<std::uint32_t>>{{30, 40, 2767030}}));
+ result = backend.Fetch(Session(), cancel);
+ assert(result.games.size() == 3 && Find(result, 2767030));
- // A refresh asks only about apps it hasn't seen this run.
+ // A refresh asks only about apps it doesn't know.
acquisitions.result.package_apps[500] = {50};
acquisitions.app_info[50] = AppInfoText(50, "Synthetic New", "game");
+ result = Settled(backend);
+ assert(result.games.size() == 4 && Find(result, 50) && Find(result, 50)->title == "Synthetic New");
+ assert(acquisitions.Requests().size() == 2 && (acquisitions.Requests()[1] == std::vector<std::uint32_t>{50}));
result = backend.Fetch(Session(), cancel);
- assert(result.games.size() == 4 && std::any_of(result.games.begin(), result.games.end(),
- [](const auto& game) { return game.title == "Synthetic New"; }));
- assert(acquisitions.app_info_requests.size() == 2 &&
- (acquisitions.app_info_requests[1] == std::vector<std::uint32_t>{50}));
- result = backend.Fetch(Session(), cancel);
- assert(result.games.size() == 4 && acquisitions.app_info_requests.size() == 2);
+ assert(result.games.size() == 4 && acquisitions.Requests().size() == 2);
}
// A demo comes in a free package of its own, which GetOwnedGames leaves out. It is added and marked,
-// so the Library can hide it; games stay unmarked. A cached lookup keeps the mark.
+// so the Library can hide it; games stay unmarked. A known name keeps the mark.
void LicensedDemosAreAddedAndMarked() {
Owned owned;
Acquisitions acquisitions;
@@ -182,7 +266,7 @@ void LicensedDemosAreAddedAndMarked() {
EntitledLibraryBackend backend(owned, acquisitions);
std::atomic<bool> cancel{false};
for (int pass = 0; pass < 2; ++pass) {
- const auto result = backend.Fetch(Session(), cancel);
+ const auto result = pass ? backend.Fetch(Session(), cancel) : Settled(backend);
assert(result.error == LibraryError::kNone && result.games.size() == 4);
const auto demo = std::find_if(result.games.begin(), result.games.end(),
[](const auto& game) { return game.id == SteamId(60); });
@@ -190,51 +274,124 @@ void LicensedDemosAreAddedAndMarked() {
assert(std::none_of(result.games.begin(), result.games.end(),
[](const auto& game) { return game.demo && game.id != SteamId(60); }));
}
- assert(acquisitions.app_info_requests.size() == 1);
+ assert(acquisitions.Requests().size() == 1);
}
-// Declared before the backend in each test: the family probe thread may still log while the backend stops it.
-struct Lines {
- std::mutex mutex;
- std::vector<std::string> lines;
- FamilyLog Log() {
- return [this](const std::string& line) {
- std::lock_guard<std::mutex> lock(mutex);
- std::printf("%s\n", line.c_str());
- lines.push_back(line);
- };
- }
- std::size_t Count(const std::string& text) {
- std::lock_guard<std::mutex> lock(mutex);
- return static_cast<std::size_t>(std::count_if(lines.begin(), lines.end(), [&](const auto& line) {
- return line.find(text) != std::string::npos;
- }));
- }
-};
+// Apps only a Steam family member's licenses grant can be hash-only in PICS: the lookup fetches them over HTTP.
+void HashOnlyAppsAreFetchedOverHttp() {
+ // gzip of AppInfoText(90, "Synthetic Hashed", "game") plus its NUL (107 bytes), and the SHA-1 of the text.
+ const std::vector<std::uint8_t> gz = {
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x53, 0x4a, 0x2c, 0x28, 0xc8, 0xcc, 0x4b, 0xcb,
+ 0x57, 0xe2, 0xaa, 0xe6, 0xe2, 0x54, 0x02, 0x71, 0x52, 0x94, 0x38, 0x95, 0x2c, 0x0d, 0x94, 0x80, 0xbc, 0xe4,
+ 0xfc, 0xdc, 0xdc, 0xfc, 0x3c, 0x20, 0x0b, 0x28, 0xc5, 0xa9, 0x94, 0x97, 0x98, 0x9b, 0x0a, 0x94, 0x0a, 0xae,
+ 0xcc, 0x2b, 0xc9, 0x48, 0x2d, 0xc9, 0x4c, 0x56, 0xf0, 0x48, 0x2c, 0xce, 0x48, 0x4d, 0x51, 0x02, 0xc9, 0x95,
+ 0x54, 0x16, 0x80, 0xe4, 0xd2, 0x41, 0x4a, 0x40, 0xfc, 0xcc, 0x64, 0xa0, 0x3e, 0xa0, 0x71, 0x49, 0xc9, 0x86,
+ 0x46, 0xc6, 0x40, 0x91, 0x5a, 0xae, 0x5a, 0x2e, 0x06, 0x00, 0x10, 0x55, 0xd6, 0x54, 0x6b, 0x00, 0x00, 0x00};
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{900, {90}}};
+ acquisitions.result.shared_apps = {90};
+ acquisitions.hashed[90] = HashedAppInfo{{0x3d, 0xa8, 0xeb, 0x83, 0x16, 0xb6, 0x68, 0x11, 0xd5, 0x09,
+ 0x97, 0x05, 0x6d, 0x5a, 0x97, 0xc2, 0x72, 0xe3, 0xeb, 0x0f},
+ 107};
+ Lines lines;
+ std::atomic<int> fetches{0};
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetFamilyDiagnostics(
+ [&](const HttpRequest& request, const std::atomic<bool>&) {
+ HttpResponse response;
+ if (request.url.find("/appinfo/90/sha/3da8eb8316b66811d50997056d5a97c272e3eb0f.txt.gz") == std::string::npos) {
+ response.error = HttpError::kConnectionFailed; // no family service
+ return response;
+ }
+ ++fetches;
+ response.status_code = 200;
+ response.body = gz;
+ return response;
+ },
+ lines.Log());
+ const auto result = Settled(backend);
+ assert(Find(result, 90) && Find(result, 90)->title == "Synthetic Hashed" && Find(result, 90)->family_shared);
+ assert(fetches == 1 && lines.Count("family lookup http=1 fetched=1 failed=0 skipped=0") == 1);
+}
-// Waits for a line written by the family probe thread.
-bool WaitFor(Lines& lines, const std::string& text, std::size_t count = 1) {
- const auto deadline = std::chrono::steady_clock::now() + 5s;
- while (lines.Count(text) < count) {
- if (std::chrono::steady_clock::now() > deadline) return false;
- std::this_thread::sleep_for(1ms);
- }
- return true;
+// Each named game reaches the Library through the callback, after the load returned.
+void LateGamesReachTheCallback() {
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{700, {70}}};
+ acquisitions.app_info = {{70, AppInfoText(70, "Synthetic Free", "game")}};
+ std::atomic<int> calls{0};
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetLateGamesCallback([&calls] { ++calls; });
+ std::atomic<bool> cancel{false};
+ assert(backend.Fetch(Session(), cancel).games.size() == 2);
+ assert(backend.WaitForLookups(5s));
+ assert(calls >= 1 && backend.TakeLateGames(123).size() == 1);
+ backend.SetLateGamesCallback(nullptr);
}
-const GameSummary* Find(const LibraryResult& result, std::uint32_t app) {
- const auto found = std::find_if(result.games.begin(), result.games.end(),
- [&](const auto& game) { return game.id == SteamId(app); });
- return found == result.games.end() ? nullptr : &*found;
+// The names file holds its entries exactly; a damaged one reads as empty, and the newest entries are kept.
+void AppNamesFileRoundTrips() {
+ char root[] = "/tmp/playden-app-names-XXXXXX";
+ assert(mkdtemp(root));
+ Storage storage(root);
+ AppNames names;
+ names[10] = AppName{AppName::Kind::kGame, "Synthetic Game", "abc", 100};
+ names[11] = AppName{AppName::Kind::kDemo, "Synthetic Demo", "", 101};
+ names[12] = AppName{AppName::Kind::kOther, "", "", 102};
+ assert(SaveAppNames(storage, names));
+ auto loaded = LoadAppNames(storage);
+ assert(loaded.size() == 3 && loaded.at(10).name == "Synthetic Game" && loaded.at(10).icon == "abc" &&
+ loaded.at(11).kind == AppName::Kind::kDemo && loaded.at(12).kind == AppName::Kind::kOther &&
+ loaded.at(12).learned_at == 102);
+ auto bytes = storage.Read("app-names.cache").value();
+ bytes[bytes.size() / 2] ^= 1;
+ assert(storage.WriteAtomic("app-names.cache", bytes).ok());
+ assert(LoadAppNames(storage).empty());
+ AppNames many;
+ for (std::uint32_t id = 1; id <= kMaxAppNames + 5; ++id) many[id] = AppName{AppName::Kind::kOther, "", "", id};
+ assert(SaveAppNames(storage, many));
+ loaded = LoadAppNames(storage);
+ assert(loaded.size() == kMaxAppNames && !loaded.count(5) && loaded.count(6) && loaded.count(kMaxAppNames + 5));
+ // Long names: what is saved still fits what Load reads, newest first.
+ AppNames long_names;
+ for (std::uint32_t id = 1; id <= 5000; ++id)
+ long_names[id] = AppName{AppName::Kind::kGame, std::string(1000, 'x'), "", id};
+ assert(SaveAppNames(storage, long_names));
+ loaded = LoadAppNames(storage);
+ assert(loaded.size() > 3000 && loaded.size() < 5000 && loaded.count(5000) && !loaded.count(1));
+ std::remove((std::string(root) + "/app-names.cache").c_str());
+ rmdir(root);
}
-// The family probe is off in these: no requests are answered.
-FamilyPerform NoFamilyService() {
- return [](const HttpRequest&, const std::atomic<bool>&) {
- HttpResponse response;
- response.error = HttpError::kConnectionFailed;
- return response;
- };
+// Names are saved: the next run lists the game at once, without a lookup.
+void NamesAreSaved() {
+ char root[] = "/tmp/playden-app-names-XXXXXX";
+ assert(mkdtemp(root));
+ Storage storage(root);
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{700, {70}}, {300, {30}}};
+ acquisitions.app_info = {{70, AppInfoText(70, "Synthetic Free", "game")}, {30, AppInfoText(30, "Synthetic DLC", "DLC")}};
+ {
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetAppNameStorage(&storage);
+ assert(Settled(backend).games.size() == 3);
+ }
+ const auto names = LoadAppNames(storage);
+ assert(names.size() == 2 && names.at(70).kind == AppName::Kind::kGame && names.at(70).name == "Synthetic Free");
+ assert(names.at(30).kind == AppName::Kind::kOther && names.at(30).name.empty());
+ Acquisitions next;
+ next.result = acquisitions.result;
+ EntitledLibraryBackend backend(owned, next);
+ backend.SetAppNameStorage(&storage);
+ std::atomic<bool> cancel{false};
+ const auto result = backend.Fetch(Session(), cancel);
+ assert(result.games.size() == 3 && Find(result, 70) && Find(result, 70)->title == "Synthetic Free");
+ assert(backend.WaitForLookups(5s) && next.Requests().empty());
+ std::remove((std::string(root) + "/app-names.cache").c_str());
+ rmdir(root);
}
// Apps only a family member's licenses grant are added and marked; owned games never are.
@@ -255,7 +412,7 @@ void FamilySharedAppsAreMarked() {
backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());
std::atomic<bool> cancel{false};
for (int pass = 0; pass < 2; ++pass) {
- const auto result = backend.Fetch(Session(), cancel);
+ const auto result = pass ? backend.Fetch(Session(), cancel) : Settled(backend);
assert(result.error == LibraryError::kNone && result.games.size() == 5);
assert(Find(result, 80) && Find(result, 80)->family_shared && Find(result, 80)->title == "Synthetic Shared");
assert(Find(result, 90) && Find(result, 90)->family_shared);
@@ -263,10 +420,11 @@ void FamilySharedAppsAreMarked() {
assert(!Find(result, 10)->family_shared && !Find(result, 20)->family_shared && !Find(result, 11));
}
// The package with an owned game is passed over; the borrowed bundle only skips the owned game.
- assert((acquisitions.app_info_requests == std::vector<std::vector<std::uint32_t>>{{80, 90, 95}}));
+ assert((acquisitions.Requests() == std::vector<std::vector<std::uint32_t>>{{80, 90, 95}}));
// Each shared app is logged once per run; the summary once per load.
- assert(lines.Count("family library added app=80 demo=0") == 1);
- assert(lines.Count("family library added app=90 demo=0") == 1);
+ assert(lines.Count("family library added app=80 demo=0 source=saved") == 1);
+ assert(lines.Count("family library added app=90 demo=0 source=saved") == 1);
+ assert(lines.Count("family library shared=2 added=0 left_out=0 pending=2 in_owned_list=0") == 1);
assert(lines.Count("family library shared=2 added=2 left_out=0 pending=0 in_owned_list=0") == 2);
}
@@ -282,33 +440,58 @@ void OwnedAndBorrowedIsNotShared() {
std::atomic<bool> cancel{false};
const auto result = backend.Fetch(Session(), cancel);
assert(result.games.size() == 2 && !Find(result, 20)->family_shared);
- assert(acquisitions.app_info_requests.empty());
+ assert(acquisitions.Requests().empty());
assert(lines.Count("family library shared=1 added=0 left_out=0 pending=0 in_owned_list=1") == 1);
}
-// Shared apps PICS doesn't call a named game or demo stay out, with the reason logged.
+// Shared apps PICS doesn't call a named game or demo stay out, with the reason logged. Apps without an answer
+// stay pending and are asked again.
void SharedAppsLeftOutAreLogged() {
Owned owned;
Acquisitions acquisitions;
- acquisitions.result.package_apps = {{810, {81}}, {820, {82}}, {830, {83}}, {840, {84}}};
- acquisitions.result.shared_apps = {81, 82, 83, 84};
+ acquisitions.result.package_apps = {{810, {81}}, {820, {82}}, {830, {83}}, {840, {84}}, {850, {85}}};
+ acquisitions.result.shared_apps = {81, 82, 83, 84, 85};
acquisitions.app_info = {{81, AppInfoText(81, "Synthetic DLC", "DLC")},
{83, AppInfoText(83, "app_83", "game")},
{84, "not app info"}};
+ acquisitions.unanswered = {{85, "missing_token"}};
Lines lines;
EntitledLibraryBackend backend(owned, acquisitions);
backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());
- std::atomic<bool> cancel{false};
- const auto result = backend.Fetch(Session(), cancel);
+ const auto result = Settled(backend);
assert(result.games.size() == 2);
assert(lines.Count("family library left_out app=81 reason=type=dlc") == 1);
- assert(lines.Count("family library left_out app=82 reason=no_app_info") == 1);
assert(lines.Count("family library left_out app=83 reason=no_name") == 1);
- assert(lines.Count("family library left_out app=84 reason=app_info_unreadable") == 1);
- assert(lines.Count("family library shared=4 added=0 left_out=4 pending=0") == 1);
+ assert(lines.Count("family library shared=5 added=0 left_out=2 pending=3") == 1);
+ // The second load asked again about the three it couldn't name.
+ assert(backend.WaitForLookups(5s));
+ assert(lines.Count("family lookup end games=0 by_hash=0 unanswered=2") == 2);
+ assert((acquisitions.Requests().back() == std::vector<std::uint32_t>{82, 84, 85}));
+}
+
+// A shared app Steam sent no app info for is named by a later load's lookup.
+void SharedAppWithoutAppInfoIsAskedAgain() {
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{800, {80}}, {810, {81}}};
+ acquisitions.result.shared_apps = {80, 81};
+ acquisitions.app_info = {{81, AppInfoText(81, "Synthetic DLC", "DLC")}};
+ acquisitions.unanswered = {{80, "missing_token"}};
+ Lines lines;
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());
+ auto result = Settled(backend);
+ assert(!Find(result, 80));
+ assert(backend.WaitForLookups(5s));
+ acquisitions.app_info[80] = AppInfoText(80, "Synthetic Shared", "game");
+ result = Settled(backend);
+ assert(Find(result, 80) && Find(result, 80)->family_shared);
+ // Only the unanswered app is asked again; the DLC's answer is kept.
+ assert((acquisitions.Requests() == std::vector<std::vector<std::uint32_t>>{{80, 81}, {80}, {80}}));
+ assert(lines.Count("family library added app=80 demo=0") == 1);
}
-// When PICS fails the shared apps are logged as pending and asked again on the next load.
+// When PICS fails the lookup stops, and a later load asks again.
void SharedAppInfoFailureIsRetried() {
Owned owned;
Acquisitions acquisitions;
@@ -319,24 +502,87 @@ void SharedAppInfoFailureIsRetried() {
Lines lines;
EntitledLibraryBackend backend(owned, acquisitions);
backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());
- std::atomic<bool> cancel{false};
- auto result = backend.Fetch(Session(), cancel);
+ auto result = Settled(backend);
assert(result.games.size() == 2 && !Find(result, 80));
- assert(lines.Count("family library left_out app=80 reason=app_info_failed") == 1);
- assert(lines.Count("family library shared=1 added=0 left_out=0 pending=1") == 1);
+ assert(backend.WaitForLookups(5s));
+ assert(lines.Count("family lookup end games=0 by_hash=0 unanswered=0 error=network") == 2);
acquisitions.fail_app_info = false;
- result = backend.Fetch(Session(), cancel);
+ result = Settled(backend);
assert(Find(result, 80) && Find(result, 80)->family_shared);
assert(lines.Count("family library added app=80") == 1);
}
-HttpResponse Json(const std::string& body, long status = 200) {
- HttpResponse response;
- response.status_code = status;
- response.body.assign(body.begin(), body.end());
- return response;
+// An older family answer (this load's probe failed) still names games, but a shared app it doesn't list may
+// have been shared since: it is looked up instead of left out.
+void StaleFamilyListDoesNotHideNewGames() {
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{800, {80}}};
+ acquisitions.result.shared_apps = {80};
+ acquisitions.app_info = {{81, AppInfoText(81, "Synthetic Newly Shared", "game")}};
+ Lines lines;
+ std::atomic<bool> fail{false};
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetFamilyDiagnostics(
+ [&fail](const HttpRequest& request, const std::atomic<bool>&) {
+ if (fail) {
+ HttpResponse response;
+ response.error = HttpError::kTimeout;
+ return response;
+ }
+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)
+ return Json(R"({"response":{"family_groupid":"42"}})");
+ return Json(R"({"response":{"apps":[{"appid":80,"name":"Synthetic Family Game","app_type":1}]}})");
+ },
+ lines.Log());
+ std::atomic<bool> cancel{false};
+ assert(Find(backend.Fetch(Session(), cancel), 80));
+ assert(WaitFor(lines, "family webapi app=80 "));
+ fail = true;
+ acquisitions.result.package_apps[810] = {81};
+ acquisitions.result.shared_apps.insert(81);
+ const auto result = Settled(backend);
+ assert(Find(result, 80) && Find(result, 81) && Find(result, 81)->title == "Synthetic Newly Shared");
+ assert(lines.Count("family_list=stale") >= 1 && lines.Count("not_in_family_list") == 0);
+}
+
+// Steam's family service names the family's games: the load lists them at once, without a lookup. Shared
+// apps it leaves out are not games and are not looked up; a game it lists without a name is.
+void FamilyServiceNamesSharedGames() {
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.package_apps = {{800, {80, 81}}, {820, {82}}, {830, {83}}, {840, {84}}};
+ acquisitions.result.shared_apps = {80, 81, 82, 83, 84};
+ acquisitions.app_info = {{84, AppInfoText(84, "Synthetic Unnamed", "game")}};
+ Lines lines;
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetFamilyDiagnostics(
+ [](const HttpRequest& request, const std::atomic<bool>&) {
+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)
+ return Json(R"({"response":{"family_groupid":"42"}})");
+ return Json(R"({"response":{"apps":[
+ {"appid":80,"owner_steamids":["5"],"name":"Synthetic Family Game","app_type":1,"rt_time_acquired":1600000000},
+ {"appid":82,"owner_steamids":["5"],"name":"Synthetic Family Demo","app_type":8},
+ {"appid":83,"owner_steamids":["5"],"name":"Synthetic Family Tool","app_type":4},
+ {"appid":84,"owner_steamids":["5"]}]}})");
+ },
+ lines.Log());
+ std::atomic<bool> cancel{false};
+ const auto result = backend.Fetch(Session(), cancel);
+ assert(result.games.size() == 4);
+ assert(Find(result, 80)->title == "Synthetic Family Game" && Find(result, 80)->family_shared &&
+ Find(result, 80)->added_at_unix_seconds == 1600000000u && !Find(result, 80)->demo);
+ assert(Find(result, 82)->title == "Synthetic Family Demo" && Find(result, 82)->demo);
+ assert(lines.Count("family library left_out app=81 reason=not_in_family_list") == 1);
+ assert(lines.Count("family library left_out app=83 reason=app_type=4") == 1);
+ assert(lines.Count("named_family=2 named_saved=0 family_list=y lookups=1") == 1);
+ // Only the game listed without a name is looked up.
+ assert(backend.WaitForLookups(5s));
+ assert((acquisitions.Requests() == std::vector<std::vector<std::uint32_t>>{{84}}));
+ assert(backend.TakeLateGames(123).size() == 1);
}
+
// Without licenses the family log says so, and the probe still reports without comparing.
void CmFailureIsLoggedForFamily() {
Owned owned;
@@ -360,8 +606,8 @@ void CmFailureIsLoggedForFamily() {
assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=?") == 1);
}
-// The family service is asked once per run while the library loads; what it says only reaches the log.
-void FamilyServiceIsAskedOncePerRun() {
+// The family service is asked by every load; its comparison with the licenses is logged once per run.
+void FamilyServiceIsAskedByEveryLoad() {
Owned owned;
Acquisitions acquisitions;
acquisitions.result.package_apps = {{800, {80}}};
@@ -379,13 +625,11 @@ void FamilyServiceIsAskedOncePerRun() {
return Json(R"({"response":{"apps":[{"appid":80,"owner_steamids":["5"]},{"appid":81,"owner_steamids":["5"]}]}})");
},
lines.Log());
- std::atomic<bool> cancel{false};
- auto result = backend.Fetch(Session(), cancel);
+ auto result = Settled(backend);
assert(result.error == LibraryError::kNone && result.games.size() == 3);
assert(WaitFor(lines, "family webapi app=81 "));
- result = backend.Fetch(Session(), cancel);
- assert(result.games.size() == 3 && requests == 2);
- assert(lines.Count("family webapi group=y family_groupid=42 role=2 members=1 member=5:1") == 1);
+ assert(requests == 4);
+ assert(lines.Count("family webapi group=y family_groupid=42 role=2 members=1 member=5:1") == 2);
assert(lines.Count("family webapi shared_apps=2 excluded=0 owners=1 unlicensed=1 licenses=known") == 1);
assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=shared") == 1);
assert(lines.Count("family webapi app=81 owners=5 exclude_reason=0 licensed=n") == 1);
@@ -462,6 +706,7 @@ void StalledFamilyServiceHoldsNothingUp() {
Lines lines;
std::atomic<int> requests{0};
auto backend = std::make_unique<EntitledLibraryBackend>(owned, acquisitions);
+ backend->SetFamilyWait(50ms);
backend->SetFamilyDiagnostics(
[&](const HttpRequest&, const std::atomic<bool>& stop) {
++requests;
@@ -494,6 +739,7 @@ void LateFamilyAnswerIsLogged() {
Lines lines;
std::atomic<bool> release{false};
EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetFamilyWait(50ms);
backend.SetFamilyDiagnostics(
[&release](const HttpRequest& request, const std::atomic<bool>& stop) {
if (request.url.find("GetFamilyGroupForUser") != std::string::npos) {
@@ -506,6 +752,7 @@ void LateFamilyAnswerIsLogged() {
std::atomic<bool> cancel{false};
const auto result = backend.Fetch(Session(), cancel);
assert(result.error == LibraryError::kNone && lines.Count("family webapi") == 0);
+ assert(lines.Count("family_list=n") == 1);
release = true;
// The last line the probe writes.
assert(WaitFor(lines, "family webapi app=81 owners=5 exclude_reason=0 licensed=n"));
@@ -513,39 +760,42 @@ void LateFamilyAnswerIsLogged() {
assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=shared") == 1);
}
-// Per-app family lines stay bounded per load, and a lookup that keeps failing is logged once per app.
+// Per-app family lines stay bounded per load, and each app is logged once.
void FamilyAppLinesAreCapped() {
Owned owned;
Acquisitions acquisitions;
+ std::string apps;
for (std::uint32_t app = 1000; app < 1300; ++app) {
acquisitions.result.package_apps[app] = {app};
acquisitions.result.shared_apps.insert(app);
- acquisitions.app_info[app] = AppInfoText(app, "Synthetic " + std::to_string(app), "game");
+ apps += std::string(apps.empty() ? "" : ",") + R"({"appid":)" + std::to_string(app) + R"(,"name":"Synthetic )" +
+ std::to_string(app) + R"(","app_type":1})";
}
- acquisitions.fail_app_info = true;
Lines lines;
EntitledLibraryBackend backend(owned, acquisitions);
- backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());
+ backend.SetFamilyDiagnostics(
+ [apps](const HttpRequest& request, const std::atomic<bool>&) {
+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)
+ return Json(R"({"response":{"family_groupid":"42"}})");
+ return Json(R"({"response":{"apps":[)" + apps + "]}}");
+ },
+ lines.Log());
std::atomic<bool> cancel{false};
const auto load = [&] {
const auto before = lines.Count("family library ");
- backend.Fetch(Session(), cancel);
+ assert(backend.Fetch(Session(), cancel).games.size() == 302);
return lines.Count("family library ") - before;
};
// Each load writes at most 100 per-app lines, a truncated line and the summary; no app repeats.
- assert(load() == 102 && lines.Count("reason=app_info_failed") == 100);
+ assert(load() == 102 && lines.Count("family library added app=") == 100);
assert(lines.Count("family library truncated=200") == 1);
- assert(lines.Count("family library shared=300 added=0 left_out=0 pending=300") == 1);
- assert(load() == 102 && lines.Count("reason=app_info_failed") == 200 &&
- lines.Count("family library truncated=100") == 1);
- assert(load() == 101 && lines.Count("reason=app_info_failed") == 300);
- assert(load() == 1 && lines.Count("reason=app_info_failed") == 300);
+ assert(load() == 102 && lines.Count("family library added app=") == 200);
+ assert(load() == 101 && lines.Count("family library added app=") == 300);
+ assert(load() == 1);
for (std::uint32_t app = 1000; app < 1300; ++app)
- assert(lines.Count("family library left_out app=" + std::to_string(app) + " reason=app_info_failed") == 1);
- assert(lines.Count("family library shared=300 added=0 left_out=0 pending=300") == 4);
- acquisitions.fail_app_info = false;
- assert(load() == 102 && lines.Count("family library added app=") == 100);
- assert(lines.Count("family library shared=300 added=300 left_out=0 pending=0") == 1);
+ assert(lines.Count("family library added app=" + std::to_string(app) + " ") == 1);
+ assert(lines.Count("family library shared=300 added=300 left_out=0 pending=0") == 4);
+ assert(acquisitions.Requests().empty());
}
} // namespace
@@ -554,8 +804,11 @@ int main() {
FamilySharedAppsAreMarked();
OwnedAndBorrowedIsNotShared();
SharedAppsLeftOutAreLogged();
+ SharedAppWithoutAppInfoIsAskedAgain();
SharedAppInfoFailureIsRetried();
- FamilyServiceIsAskedOncePerRun();
+ FamilyServiceNamesSharedGames();
+ StaleFamilyListDoesNotHideNewGames();
+ FamilyServiceIsAskedByEveryLoad();
FamilyServiceNeverFailsTheLoad();
FamilyWithoutLicensesIsAskedAgain();
StalledFamilyServiceHoldsNothingUp();
@@ -564,6 +817,10 @@ int main() {
CmFailureIsLoggedForFamily();
LicensedFreeGamesAreAdded();
LicensedDemosAreAddedAndMarked();
+ HashOnlyAppsAreFetchedOverHttp();
+ LateGamesReachTheCallback();
+ NamesAreSaved();
+ AppNamesFileRoundTrips();
DatesMergeIntoOwnedGames();
LicensesBelongToTheirAccount();
CmFailureIsNeverFatal();
diff --git a/tests/family_groups_test.cpp b/tests/family_groups_test.cpp
index 1485e37..5fc285c 100644
--- a/tests/family_groups_test.cpp
+++ b/tests/family_groups_test.cpp
@@ -94,6 +94,11 @@ void ParsesSharedApps() {
assert(library->apps[0].appid == 620 && library->apps[0].owners == std::vector<std::uint64_t>{76561198000000002ULL});
assert(library->apps[1].appid == 730 && library->apps[1].owners.size() == 2 && !library->apps[1].exclude_reason);
assert(library->apps[2].appid == 440 && library->apps[2].exclude_reason == 3);
+ // The name, type and acquisition time name a game without PICS; a missing type is Steam's default, a game.
+ assert(library->apps[0].name == "Synthetic Shared" && library->apps[0].app_type == kFamilyAppTypeGame &&
+ library->apps[0].rt_time_acquired == 1600000000u);
+ assert(library->apps[1].name.empty() && library->apps[1].app_type == kFamilyAppTypeGame &&
+ !library->apps[1].rt_time_acquired);
const auto empty = ParseSharedLibraryApps(R"({"response":{}})");
assert(empty && empty->apps.empty());
assert(!ParseSharedLibraryApps("not json"));
diff --git a/tests/library_controller_test.cpp b/tests/library_controller_test.cpp
index f13a74e..ca30563 100644
--- a/tests/library_controller_test.cpp
+++ b/tests/library_controller_test.cpp
@@ -2,6 +2,8 @@
#include <algorithm>
#include <cassert>
#include <chrono>
+#include <functional>
+#include <utility>
#include <mutex>
#include <thread>
#include "fake_library_source.h"
@@ -195,4 +197,77 @@ void UpdateRefusesAnotherStoresGames() {
assert(model.state().games.empty());
}
}
-int main(){OtherSourceSurvivesSteam();StaleSteamCompletionKeepsOtherSource();UpdateRefusesAnotherStoresGames();FreshRefreshAndFailure();OfflineCacheAndClear();StaleCompletionCannotRepopulate();RejectedCacheStillAcceptsFreshResult();RejectedRequestStopsLoading();}
+// A backend whose games named after the load arrive through the callback.
+struct LateBackend final : LibraryBackend {
+ std::mutex mutex;
+ std::function<void()> callback;
+ std::vector<GameSummary> late;
+ std::uint64_t late_account=123;
+ std::atomic<int> calls{0};
+ LibraryResult Fetch(const StoredSession&,const std::atomic<bool>&) override {
+ ++calls;
+ return {LibraryError::kNone,{{SteamId(42),"Synthetic title",{},{},{}}},false,true};
+ }
+ std::vector<GameSummary> TakeLateGames(std::uint64_t account) override {
+ std::lock_guard<std::mutex> lock(mutex);
+ if(account!=late_account) return {};
+ return std::exchange(late,{});
+ }
+ void SetLateGamesCallback(std::function<void()> value) override { std::lock_guard<std::mutex> lock(mutex);callback=std::move(value); }
+ void Name(GameSummary game) {
+ std::function<void()> notify;
+ { std::lock_guard<std::mutex> lock(mutex);late.push_back(std::move(game));notify=callback; }
+ if(notify) notify();
+ }
+};
+// Games the backend names after a load completed join the Library and the cache, without a Loading state or
+// a status change; a sign-out drops them.
+void LateGamesJoinTheLibrary() {
+ Simulation model({}, {},ModelMode::Live);
+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});
+ Sessions sessions;Cache cache;LateBackend backend;
+ {
+ LibraryService service(backend,sessions,&cache,[]{return 12345;});
+ app::LibraryController controller(model,service);
+ controller.Activate(123,false);
+ Wait(controller,[&]{return !model.state().library_loading && model.state().games.size()==1;});
+ GameSummary late{SteamId(43),"Synthetic late",{},{},{}};late.family_shared=true;
+ backend.Name(late);
+ Wait(controller,[&]{return model.state().games.size()==2;});
+ assert(!model.state().library_loading && model.state().account().error.empty());
+ assert(cache.value && cache.value->games.size()==2 && cache.value->schema_version==7);
+ // The same game again, or one for another account, changes nothing.
+ backend.Name(late);
+ backend.late_account=456;
+ backend.Name({SteamId(44),"Synthetic other",{},{},{}});
+ for(int i=0;i<50;++i){controller.Tick();std::this_thread::sleep_for(1ms);}
+ assert(model.state().games.size()==2 && cache.value->games.size()==2);
+ backend.late_account=123;
+ // After a sign-out, late games are not shown.
+ controller.Reset();
+ backend.Name({SteamId(45),"Synthetic after reset",{},{},{}});
+ for(int i=0;i<50;++i){controller.Tick();std::this_thread::sleep_for(1ms);}
+ assert(std::none_of(model.state().games.begin(),model.state().games.end(),
+ [](const auto& game){return game.id==SteamId(45);}));
+ }
+ // The service's shutdown unhooked the callback.
+ assert(!backend.callback);
+}
+// Many late games while the UI isn't pumping: the updates collapse into one, so the completion isn't pushed out.
+void ManyLateGamesKeepTheCompletion() {
+ Simulation model({}, {},ModelMode::Live);
+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});
+ Sessions sessions;Cache cache;LateBackend backend;
+ LibraryService service(backend,sessions,&cache,[]{return 12345;});
+ app::LibraryController controller(model,service);
+ controller.Activate(123,false);
+ const auto deadline=std::chrono::steady_clock::now()+2s;
+ while(backend.calls==0 && std::chrono::steady_clock::now()<deadline) std::this_thread::sleep_for(1ms);
+ std::this_thread::sleep_for(50ms);
+ for(std::uint32_t app=100;app<200;++app) {
+ backend.Name({SteamId(app),"Synthetic late "+std::to_string(app),{},{},{}});
+ std::this_thread::sleep_for(1ms);
+ }
+ Wait(controller,[&]{return !model.state().library_loading && model.state().games.size()==101;});
+}
+int main(){OtherSourceSurvivesSteam();StaleSteamCompletionKeepsOtherSource();UpdateRefusesAnotherStoresGames();FreshRefreshAndFailure();OfflineCacheAndClear();StaleCompletionCannotRepopulate();RejectedCacheStillAcceptsFreshResult();RejectedRequestStopsLoading();LateGamesJoinTheLibrary();ManyLateGamesKeepTheCompletion();}