Skip to content

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

C++

List and measure Steam download servers

Leonardo Lobato920434152ab8
diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmake
index b6248b0..6418abf 100644
--- a/cmake/PlaydenCore.cmake
+++ b/cmake/PlaydenCore.cmake
@@ -37,6 +37,7 @@ add_library(playden_steam_core STATIC
"${CMAKE_SOURCE_DIR}/src/steam/session_store.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/service.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/app_details_service.cpp"
+ "${CMAKE_SOURCE_DIR}/src/steam/download_server_service.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/store_details_service.cpp"
"${CMAKE_SOURCE_DIR}/src/installs/install_service.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/install_volumes.cpp"
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index 28b7536..3e846e3 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -150,6 +150,7 @@ add_library(playden_steam_cm STATIC
"${CMAKE_SOURCE_DIR}/src/steam/backend/entitled_library.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/cm_app_details.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/cdn_client.cpp"
+ "${CMAKE_SOURCE_DIR}/src/steam/backend/download_server_source.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/depot_installer.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/steam_install_runner.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/backend/cloud_messages.cpp"
@@ -284,6 +285,13 @@ function(playden_register_steam_backend_tests)
add_executable(cdn_client_test "${CMAKE_SOURCE_DIR}/tests/cdn_client_test.cpp")
target_link_libraries(cdn_client_test PRIVATE playden_steam_cm)
add_test(NAME cdn_client COMMAND cdn_client_test)
+ add_executable(download_server_service_test "${CMAKE_SOURCE_DIR}/tests/download_server_service_test.cpp")
+ target_link_libraries(download_server_service_test PRIVATE playden_steam_core)
+ add_test(NAME download_server_service COMMAND download_server_service_test)
+ add_executable(download_server_source_test "${CMAKE_SOURCE_DIR}/tests/download_server_source_test.cpp")
+ target_link_libraries(download_server_source_test PRIVATE playden_steam_cm)
+ add_test(NAME download_server_source COMMAND download_server_source_test
+ "${CMAKE_SOURCE_DIR}/fixtures/steam/manifest")
add_test(NAME download_speed_report
COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/test_download_speed_report.py")
add_executable(store_details_test "${CMAKE_SOURCE_DIR}/tests/store_details_test.cpp")
diff --git a/src/steam/backend/cdn_client.cpp b/src/steam/backend/cdn_client.cpp
index 164433b..2f97198 100644
--- a/src/steam/backend/cdn_client.cpp
+++ b/src/steam/backend/cdn_client.cpp
@@ -98,7 +98,7 @@ CdnError CdnClient::Get(const std::string& url, std::size_t max_bytes, std::uint
stats_.first_byte_ms += response.timing.first_byte_ms;
stats_.total_ms += response.timing.total_ms;
stats_.new_connections += response.timing.new_connections;
- stats_.bytes += response.timing.body_bytes;
+ stats_.bytes += std::max<std::uint64_t>(response.timing.body_bytes, response.body.size());
if (error == CdnError::kNone) {
*out = std::move(response.body);
} else {
@@ -114,7 +114,7 @@ CdnError CdnClient::Servers(std::uint32_t cell_id, const std::atomic<bool>& canc
const auto error = Get(
"https://api.steampowered.com/IContentServerDirectoryService/GetServersForSteamPipe/v1/?cell_id=" +
std::to_string(cell_id) + "&format=json",
- 512 * 1024, 15'000, cancel, &body);
+ kMaxServerListDownloadBytes, 15'000, cancel, &body);
if (error != CdnError::kNone) return error;
const std::string_view text(body.empty() ? "" : reinterpret_cast<const char*>(body.data()), body.size());
const auto root = json::Parse(text, json::Limits{512 * 1024, 8, 8192, 4096});
@@ -162,11 +162,11 @@ CdnError CdnClient::Servers(std::uint32_t cell_id, const std::atomic<bool>& canc
CdnError CdnClient::Manifest(const ContentServer& server, std::uint32_t depot_id, std::uint64_t gid,
std::uint64_t request_code, const std::atomic<bool>& cancel,
- std::vector<std::uint8_t>* out) {
- if (!ValidCdnHost(server.vhost)) return CdnError::kProtocol;
+ std::vector<std::uint8_t>* out, std::size_t max_bytes) {
+ if (!ValidCdnHost(server.vhost) || !max_bytes) return CdnError::kProtocol;
return Get(Scheme(server) + server.vhost + "/depot/" + std::to_string(depot_id) + "/manifest/" +
std::to_string(gid) + "/5/" + std::to_string(request_code),
- kMaxManifestDownloadBytes, 60'000, cancel, out, !server.https);
+ std::min(max_bytes, kMaxManifestDownloadBytes), 60'000, cancel, out, !server.https);
}
CdnError CdnClient::Chunk(const ContentServer& server, std::uint32_t depot_id, const std::string& sha_hex,
diff --git a/src/steam/backend/cdn_client.h b/src/steam/backend/cdn_client.h
index 3df2237..5308541 100644
--- a/src/steam/backend/cdn_client.h
+++ b/src/steam/backend/cdn_client.h
@@ -46,12 +46,14 @@ class CdnClient {
// list holds no usable server, last_failure() says how many were listed and why none fit.
CdnError Servers(std::uint32_t cell_id, const std::atomic<bool>& cancel, std::vector<ContentServer>* out);
CdnError Manifest(const ContentServer& server, std::uint32_t depot_id, std::uint64_t gid,
- std::uint64_t request_code, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out);
+ std::uint64_t request_code, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out,
+ std::size_t max_bytes = kMaxHttpResponseBytes);
CdnError Chunk(const ContentServer& server, std::uint32_t depot_id, const std::string& sha_hex,
std::size_t max_bytes, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out);
// Bounded by the HTTP client's response cap.
static constexpr std::size_t kMaxManifestDownloadBytes = kMaxHttpResponseBytes;
+ static constexpr std::size_t kMaxServerListDownloadBytes = 512 * 1024;
// The last failure as "http=<status>" or "transport=<category>", for sanitized logs.
const CdnStats& stats() const { return stats_; }
const std::string& last_failure() const { return last_failure_; }
diff --git a/src/steam/backend/download_server_source.cpp b/src/steam/backend/download_server_source.cpp
new file mode 100644
index 0000000..0b214ab
--- /dev/null
+++ b/src/steam/backend/download_server_source.cpp
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/backend/download_server_source.h"
+
+#include "steam/backend/app_info.h"
+#include "steam/backend/depot_manifest.h"
+#include "steam/backend/gzip.h"
+
+#include <algorithm>
+#include <array>
+#include <mutex>
+#include <thread>
+
+namespace playden::steam {
+namespace {
+std::string Hex(const std::array<std::uint8_t, 20>& bytes) {
+ std::string result;
+ for (const auto byte : bytes) { result += "0123456789abcdef"[byte >> 4]; result += "0123456789abcdef"[byte & 15]; }
+ return result;
+}
+}
+
+CdnDownloadServerSource::CdnDownloadServerSource(CmClient& cm, CdnClient& cdn,
+ std::function<std::uint32_t()> newest_installed_app)
+ : CdnDownloadServerSource(cdn, Hooks{}, std::move(newest_installed_app)) {
+ hooks_.app_info = [&cm](const StoredSession& session, std::uint32_t app, const std::atomic<bool>& cancel) {
+ return cm.FetchAppInfo(session, {app}, cancel);
+ };
+ hooks_.access = [&cm](const StoredSession& session, std::uint32_t app, const std::vector<DepotRequest>& depots,
+ const std::atomic<bool>& cancel) { return cm.FetchDepotAccess(session, app, depots, cancel); };
+}
+CdnDownloadServerSource::CdnDownloadServerSource(CdnClient& cdn, Hooks hooks,
+ std::function<std::uint32_t()> newest_installed_app)
+ : cdn_(cdn), hooks_(std::move(hooks)), newest_installed_app_(std::move(newest_installed_app)) {
+ if (!hooks_.now) hooks_.now = [] { return Clock::now(); };
+}
+std::string CdnDownloadServerSource::DisplayName(const std::string& id) const { return CdnServerDisplayName(id); }
+std::string CdnDownloadServerSource::LogLabel(const std::string& id) const { return CdnServerLabel(id); }
+bool CdnDownloadServerSource::List(const std::atomic<bool>& cancel, std::vector<DownloadServerView>* out) {
+ std::vector<ContentServer> listed;
+ if (cdn_.Servers(0, cancel, &listed) != CdnError::kNone || cancel) return false;
+ servers_ = std::move(listed);
+ out->clear();
+ for (const auto& server : servers_) out->push_back({server.host, DisplayName(server.host), !server.https});
+ return !out->empty();
+}
+DownloadServerPreparation CdnDownloadServerSource::Prepare(const StoredSession& session, const std::atomic<bool>& cancel) {
+ chunks_.clear(); depot_ = 0;
+ // Also cover the directory request when Test had to list first. Reserve its complete cap
+ // even when the directory was already cached, so every test has the same hard byte ceiling.
+ metadata_budget_ = DownloadServerService::kTotalByteLimit - CdnClient::kMaxServerListDownloadBytes;
+ if (!hooks_.app_info || !hooks_.access || servers_.empty() || cancel) return {};
+ const auto primary = PrepareApp(session, 228980, true, cancel);
+ if (primary == PayloadResult::kReady) return {DownloadServerPreparation::Error::kNone, 228980, metadata_budget_};
+ if (primary != PayloadResult::kRejected || cancel) return {};
+ const auto fallback = newest_installed_app_ ? newest_installed_app_() : 0;
+ if (!fallback) return {DownloadServerPreparation::Error::kNeedsInstalledGame, 228980};
+ const auto result = PrepareApp(session, fallback, false, cancel);
+ return {result == PayloadResult::kReady ? DownloadServerPreparation::Error::kNone : DownloadServerPreparation::Error::kFailed, fallback, metadata_budget_};
+}
+CdnDownloadServerSource::PayloadResult CdnDownloadServerSource::PrepareApp(
+ const StoredSession& session, std::uint32_t app_id, bool common, const std::atomic<bool>& cancel) {
+ const auto fetched = hooks_.app_info(session, app_id, cancel);
+ if (!fetched.ok() || cancel) return PayloadResult::kFailed;
+ const auto buffer = fetched.buffers.find(app_id);
+ const auto app = buffer == fetched.buffers.end() ? std::nullopt : ParseAppInfo(app_id, buffer->second);
+ if (!app) return PayloadResult::kFailed;
+ std::vector<DepotInfo> depots;
+ if (common) {
+ for (const auto& depot : app->depots)
+ if (depot.id == 228990 && depot.manifest_gid) depots.push_back(depot);
+ } else if (!SelectDepots(*app, {app_id}, std::nullopt, &depots, nullptr)) return PayloadResult::kFailed;
+ if (depots.empty()) return PayloadResult::kFailed;
+ // Prefer the game's own depots over borrowed content. A refused depot does not prevent
+ // another readable depot of the installed game from supplying the sample.
+ std::stable_sort(depots.begin(), depots.end(), [](const DepotInfo& a, const DepotInfo& b) {
+ return !a.depot_from_app && b.depot_from_app.has_value();
+ });
+ for (const auto& depot : depots) {
+ if (!metadata_budget_ || cancel) return PayloadResult::kFailed;
+ const auto access = hooks_.access(session, app_id, {{depot.id, *depot.manifest_gid, false}}, cancel);
+ if (cancel) return PayloadResult::kFailed;
+ if (!access.ok()) {
+ if (access.error != CmError::kRejected) return PayloadResult::kFailed;
+ if (common) return PayloadResult::kRejected;
+ continue;
+ }
+ if (access.grants.size() != 1 || access.grants[0].depot_id != depot.id ||
+ access.grants[0].manifest_gid != *depot.manifest_gid) return PayloadResult::kFailed;
+ const auto& grant = access.grants[0];
+ for (std::size_t attempt = 0; attempt < std::min<std::size_t>(servers_.size(), 6) && !cancel; ++attempt) {
+ std::vector<std::uint8_t> zip, raw;
+ DepotManifest manifest;
+ if (!metadata_budget_) return PayloadResult::kFailed;
+ const auto cap = static_cast<std::size_t>(std::min<std::uint64_t>(metadata_budget_, CdnClient::kMaxManifestDownloadBytes));
+ const auto before = cdn_.stats().bytes;
+ const auto outcome = cdn_.Manifest(servers_[attempt], grant.depot_id, grant.manifest_gid,
+ grant.manifest_request_code, cancel, &zip, cap);
+ // HttpClient retains partial body byte counts on transport errors. All attempts and
+ // fallback depots draw from this ledger, and the next request is capped before it starts.
+ metadata_budget_ -= std::min(metadata_budget_, cdn_.stats().bytes - before);
+ if (outcome != CdnError::kNone ||
+ !UnzipFirstEntry(zip, &InflateRaw, &raw) || !ParseDepotManifest(raw, &manifest) ||
+ manifest.depot_id != grant.depot_id || manifest.gid != grant.manifest_gid) continue;
+ // Names and content remain encrypted. Only bounded chunk hashes and compressed sizes are used.
+ for (const auto& file : manifest.files) {
+ for (const auto& chunk : file.chunks) {
+ const std::uint64_t cap = static_cast<std::uint64_t>(chunk.compressed_size) + 4096;
+ if (!chunk.compressed_size || !chunk.original_size || cap > kMaxHttpResponseBytes) continue;
+ Chunk candidate{Hex(chunk.sha), static_cast<std::size_t>(cap)};
+ const auto pos = std::find_if(chunks_.begin(), chunks_.end(), [&](const Chunk& c) { return c.cap < candidate.cap; });
+ chunks_.insert(pos, std::move(candidate));
+ if (chunks_.size() > 4) chunks_.pop_back();
+ }
+ }
+ if (!chunks_.empty()) { depot_ = grant.depot_id; return PayloadResult::kReady; }
+ }
+ }
+ return PayloadResult::kFailed;
+}
+DownloadServerRate CdnDownloadServerSource::Measure(const std::string& id, std::uint64_t byte_budget,
+ const std::atomic<bool>& cancel) {
+ DownloadServerRate rate{id, 0, true};
+ byte_budget = std::min(byte_budget, DownloadServerService::kServerByteLimit);
+ const auto found = std::find_if(servers_.begin(), servers_.end(), [&](const ContentServer& s) { return s.host == id; });
+ if (found == servers_.end() || chunks_.empty() || !depot_ || !ValidCdnHost(found->vhost) || !byte_budget || cancel) return rate;
+ const ContentServer server = *found;
+ const auto started = hooks_.now();
+ const auto deadline = started + std::chrono::seconds(8);
+ std::mutex mutex;
+ std::uint64_t reserved = 0, bytes = 0;
+ std::size_t cursor = 0;
+ unsigned failures = 0;
+ std::vector<std::thread> transfers;
+ for (std::size_t slot = 0; slot < 4; ++slot) {
+ transfers.emplace_back([&, slot] {
+ // Each transfer owns an independent connection and DNS cache. Nothing touches the CDN
+ // directory/manifest client while these transfers are running.
+ std::unique_ptr<HttpClient> http;
+ if (!hooks_.perform) http = std::make_unique<HttpClient>(cdn_.ca_bundle());
+ for (;;) {
+ Chunk chunk;
+ std::uint32_t timeout = 0;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - hooks_.now()).count();
+ if (cancel || failures >= 2 || remaining <= 0) return;
+ bool fits = false;
+ for (std::size_t n = 0; n < chunks_.size(); ++n) {
+ const auto& candidate = chunks_[cursor++ % chunks_.size()];
+ if (candidate.cap <= byte_budget - reserved) { chunk = candidate; fits = true; break; }
+ }
+ if (!fits) return;
+ reserved += chunk.cap;
+ timeout = static_cast<std::uint32_t>(std::min<std::int64_t>(remaining, 8000));
+ }
+ HttpRequest request;
+ request.url = std::string(server.https ? "https://" : "http://") + server.vhost + "/depot/" +
+ std::to_string(depot_) + "/chunk/" + chunk.sha;
+ request.headers = {{"User-Agent", "Valve/Steam HTTP Client 1.0"}};
+ request.max_response_bytes = chunk.cap;
+ request.timeout_ms = timeout;
+ request.allow_plain_http = !server.https;
+ const auto response = hooks_.perform ? hooks_.perform(slot, request, cancel) : http->Perform(request, cancel);
+ std::lock_guard<std::mutex> lock(mutex);
+ // Reserve the full cap even for failed transfers: retries cannot spend the budget twice.
+ bytes += std::min<std::uint64_t>(chunk.cap, std::max<std::uint64_t>(response.body.size(), response.timing.body_bytes));
+ if (!response.ok() || response.status_code != 200 || response.body.empty() || response.body.size() > chunk.cap) ++failures;
+ }
+ });
+ }
+ for (auto& transfer : transfers) transfer.join();
+ const auto seconds = std::chrono::duration<double>(hooks_.now() - started).count();
+ rate.failed = failures >= 2 || !bytes;
+ if (seconds > 0) rate.mb_per_s = static_cast<double>(bytes) / 1'000'000 / seconds;
+ return rate;
+}
+
+} // namespace playden::steam
diff --git a/src/steam/backend/download_server_source.h b/src/steam/backend/download_server_source.h
new file mode 100644
index 0000000..75a3c2a
--- /dev/null
+++ b/src/steam/backend/download_server_source.h
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "steam/download_server_service.h"
+#include "steam/backend/cdn_client.h"
+#include "steam/backend/cm_client.h"
+
+#include <chrono>
+#include <functional>
+
+namespace playden::steam {
+
+class CdnDownloadServerSource final : public DownloadServerSource {
+ public:
+ using Clock = std::chrono::steady_clock;
+ struct Hooks {
+ std::function<AppInfoBuffers(const StoredSession&, std::uint32_t, const std::atomic<bool>&)> app_info;
+ std::function<DepotAccessResult(const StoredSession&, std::uint32_t, const std::vector<DepotRequest>&,
+ const std::atomic<bool>&)> access;
+ // A separate slot identifies each independently owned transfer client.
+ std::function<HttpResponse(std::size_t, const HttpRequest&, const std::atomic<bool>&)> perform;
+ std::function<Clock::time_point()> now;
+ };
+ CdnDownloadServerSource(CmClient& cm, CdnClient& cdn,
+ std::function<std::uint32_t()> newest_installed_app = {});
+ CdnDownloadServerSource(CdnClient& cdn, Hooks hooks,
+ std::function<std::uint32_t()> newest_installed_app = {});
+ bool List(const std::atomic<bool>& cancel, std::vector<DownloadServerView>* out) override;
+ DownloadServerPreparation Prepare(const StoredSession&, const std::atomic<bool>& cancel) override;
+ DownloadServerRate Measure(const std::string& id, std::uint64_t byte_budget,
+ const std::atomic<bool>& cancel) override;
+ std::string DisplayName(const std::string& id) const override;
+ std::string LogLabel(const std::string& id) const override;
+
+ private:
+ enum class PayloadResult { kReady, kRejected, kFailed };
+ PayloadResult PrepareApp(const StoredSession&, std::uint32_t app, bool common,
+ const std::atomic<bool>& cancel);
+ struct Chunk { std::string sha; std::size_t cap = 0; };
+ CdnClient& cdn_;
+ Hooks hooks_;
+ std::function<std::uint32_t()> newest_installed_app_;
+ std::vector<ContentServer> servers_;
+ std::vector<Chunk> chunks_;
+ std::uint32_t depot_ = 0;
+ std::uint64_t metadata_budget_ = 0;
+};
+
+} // namespace playden::steam
diff --git a/src/steam/download_server_service.cpp b/src/steam/download_server_service.cpp
new file mode 100644
index 0000000..0bc743d
--- /dev/null
+++ b/src/steam/download_server_service.cpp
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/download_server_service.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+
+namespace playden::steam {
+
+DownloadServerService::DownloadServerService(DownloadServerSource& source, SessionRepository& sessions)
+ : source_(source), sessions_(sessions), worker_([this] { Run(); }) {}
+DownloadServerService::~DownloadServerService() { Shutdown(); }
+void DownloadServerService::List() { Queue(Request::kList); }
+void DownloadServerService::Test() { Queue(Request::kTest); }
+void DownloadServerService::Queue(Request request) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_ || pending_ != Request::kNone || (active_ != Request::kNone && !cancel_)) return;
+ if (active_ == Request::kNone) cancel_.store(false);
+ pending_ = request;
+ pending_cancel_ = false;
+ snapshot_.needs_sign_in = snapshot_.needs_installed_game = false;
+ snapshot_.testing_index = 0;
+ snapshot_.phase = request == Request::kList || snapshot_.servers.empty()
+ ? DownloadServerSnapshot::Phase::kListing : DownloadServerSnapshot::Phase::kTesting;
+ wake_.notify_all();
+}
+void DownloadServerService::CancelTest() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (active_ == Request::kTest) cancel_.store(true);
+ if (pending_ == Request::kTest) pending_cancel_ = true;
+}
+void DownloadServerService::Invalidate() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ ++revision_;
+ pending_ = Request::kNone;
+ cancel_.store(true);
+ snapshot_.rates.clear();
+ snapshot_.needs_sign_in = snapshot_.needs_installed_game = false;
+ snapshot_.phase = snapshot_.servers.empty() ? DownloadServerSnapshot::Phase::kIdle : DownloadServerSnapshot::Phase::kListed;
+}
+DownloadServerSnapshot DownloadServerService::Snapshot() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return snapshot_;
+}
+std::string DownloadServerService::DisplayName(const std::string& id) const { return source_.DisplayName(id); }
+void DownloadServerService::SetLog(LogFn log) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ log_ = std::move(log);
+}
+void DownloadServerService::Shutdown() {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ stopping_ = true;
+ cancel_.store(true);
+ }
+ wake_.notify_all();
+ if (worker_.joinable()) worker_.join();
+}
+void DownloadServerService::LogResults(std::uint32_t app, const char* result, const DownloadServerSnapshot& snapshot) {
+ LogFn log;
+ { std::lock_guard<std::mutex> lock(mutex_); log = log_; }
+ if (!log) return;
+ std::string line;
+ for (std::size_t i = 0; i < snapshot.rates.size(); ++i) {
+ const auto& rate = snapshot.rates[i];
+ auto label = source_.LogLabel(rate.id);
+ if (label != "akamai" && label != "fastly" && label != "google" && label != "alibaba" &&
+ label != "edgenext" && label != "valve" && label != "cache") label = "cache";
+ char number[40];
+ std::snprintf(number, sizeof(number), "%.1f", std::clamp(std::isfinite(rate.mb_per_s) ? rate.mb_per_s : 0.0, 0.0, 999999.9));
+ const auto token = label + '@' + std::to_string(i) + (rate.failed ? ":failed" : ":mb_s=" + std::string(number));
+ if (!line.empty() && line.size() + token.size() + 1 > 360) {
+ log(app, "server-test", result, line.c_str()); line.clear();
+ }
+ if (!line.empty()) line += ' ';
+ line += token;
+ }
+ log(app, "server-test", result, line.empty() ? "n=0" : line.c_str());
+}
+void DownloadServerService::Run() {
+ for (;;) {
+ Request request;
+ std::uint64_t revision;
+ DownloadServerSnapshot state;
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ wake_.wait(lock, [this] { return stopping_ || pending_ != Request::kNone; });
+ if (stopping_) return;
+ request = active_ = pending_;
+ pending_ = Request::kNone;
+ revision = revision_;
+ state = snapshot_;
+ cancel_.store(pending_cancel_);
+ pending_cancel_ = false;
+ }
+ std::uint32_t app = 0;
+ std::uint64_t measurement_budget = 0;
+ DownloadServerSnapshot measured;
+ bool failed = false;
+ if (request == Request::kList || state.servers.empty()) {
+ std::vector<DownloadServerView> listed;
+ if (!cancel_ && source_.List(cancel_, &listed) && !listed.empty()) state.servers = std::move(listed);
+ else { state.servers.clear(); failed = true; }
+ state.phase = failed ? DownloadServerSnapshot::Phase::kListFailed : DownloadServerSnapshot::Phase::kListed;
+ }
+ if (request == Request::kTest && !failed && !cancel_) {
+ const auto session = sessions_.Load();
+ if (!session.ok() || !session.value()) { state.needs_sign_in = true; failed = true; }
+ else {
+ const auto prepared = source_.Prepare(*session.value(), cancel_);
+ app = prepared.app_id;
+ failed = prepared.error != DownloadServerPreparation::Error::kNone;
+ measurement_budget = std::min(kTotalByteLimit, prepared.measurement_byte_budget);
+ failed = failed || measurement_budget == 0;
+ state.needs_installed_game = prepared.error == DownloadServerPreparation::Error::kNeedsInstalledGame;
+ }
+ if (!failed && !cancel_) {
+ state.rates.clear();
+ const auto budget = std::min(kServerByteLimit, measurement_budget / state.servers.size());
+ for (std::size_t i = 0; i < state.servers.size() && !cancel_; ++i) {
+ state.phase = DownloadServerSnapshot::Phase::kTesting;
+ state.testing_index = i;
+ { std::lock_guard<std::mutex> lock(mutex_); if (revision == revision_ && !stopping_ && !cancel_) snapshot_ = state; }
+ auto rate = source_.Measure(state.servers[i].id, budget, cancel_);
+ if (!cancel_) {
+ measured.rates.push_back(rate);
+ state.rates.push_back(std::move(rate));
+ }
+ }
+ }
+ state.phase = failed ? DownloadServerSnapshot::Phase::kTestFailed : DownloadServerSnapshot::Phase::kTested;
+ }
+ if (cancel_) state.phase = state.servers.empty() ? DownloadServerSnapshot::Phase::kIdle : DownloadServerSnapshot::Phase::kListed;
+ if (request == Request::kTest) LogResults(app, cancel_ ? "canceled" : failed ? "failed" : "done", measured);
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (revision == revision_ && !stopping_ && pending_ == Request::kNone) snapshot_ = std::move(state);
+ active_ = Request::kNone;
+ cancel_.store(false);
+ if (stopping_) return;
+ }
+ }
+}
+
+} // namespace playden::steam
diff --git a/src/steam/download_server_service.h b/src/steam/download_server_service.h
new file mode 100644
index 0000000..0f27a7f
--- /dev/null
+++ b/src/steam/download_server_service.h
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "steam/session_store.h"
+
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace playden::steam {
+
+inline constexpr std::uint64_t kDownloadServerTestByteLimit = 160'000'000;
+
+struct DownloadServerView { std::string id; std::string name; bool plain_http = false; };
+struct DownloadServerRate { std::string id; double mb_per_s = 0; bool failed = false; };
+struct DownloadServerSnapshot {
+ enum class Phase { kIdle, kListing, kListed, kListFailed, kTesting, kTested, kTestFailed };
+ Phase phase = Phase::kIdle;
+ std::vector<DownloadServerView> servers;
+ std::vector<DownloadServerRate> rates;
+ std::size_t testing_index = 0;
+ bool needs_sign_in = false;
+ bool needs_installed_game = false;
+};
+
+struct DownloadServerPreparation {
+ enum class Error { kNone, kFailed, kNeedsInstalledGame } error = Error::kFailed;
+ std::uint32_t app_id = 0;
+ // Remaining after directory and manifest preparation, including failed transfers.
+ std::uint64_t measurement_byte_budget = kDownloadServerTestByteLimit;
+};
+
+// Network methods run on the service worker. The name/label helpers must be thread safe.
+class DownloadServerSource {
+ public:
+ virtual ~DownloadServerSource() = default;
+ virtual bool List(const std::atomic<bool>& cancel, std::vector<DownloadServerView>* out) = 0;
+ virtual DownloadServerPreparation Prepare(const StoredSession&, const std::atomic<bool>& cancel) = 0;
+ virtual DownloadServerRate Measure(const std::string& id, std::uint64_t byte_budget,
+ const std::atomic<bool>& cancel) = 0;
+ virtual std::string DisplayName(const std::string& id) const { return id; }
+ virtual std::string LogLabel(const std::string&) const { return "cache"; }
+};
+
+// One worker; source and repository must outlive the service. Results are session memory only.
+class DownloadServerService {
+ public:
+ using LogFn = std::function<void(std::uint32_t, const char*, const char*, const char*)>;
+ DownloadServerService(DownloadServerSource& source, SessionRepository& sessions);
+ ~DownloadServerService();
+ DownloadServerService(const DownloadServerService&) = delete;
+ DownloadServerService& operator=(const DownloadServerService&) = delete;
+ void List();
+ void Test();
+ void CancelTest();
+ void Invalidate();
+ DownloadServerSnapshot Snapshot();
+ std::string DisplayName(const std::string& id) const;
+ void SetLog(LogFn log);
+ void Shutdown();
+
+ static constexpr std::uint64_t kServerByteLimit = 32'000'000;
+ static constexpr std::uint64_t kTotalByteLimit = kDownloadServerTestByteLimit;
+
+ private:
+ enum class Request { kNone, kList, kTest };
+ void Run();
+ void Queue(Request request);
+ void LogResults(std::uint32_t app, const char* result, const DownloadServerSnapshot& snapshot);
+ DownloadServerSource& source_;
+ SessionRepository& sessions_;
+ std::mutex mutex_;
+ std::condition_variable wake_;
+ DownloadServerSnapshot snapshot_;
+ LogFn log_;
+ Request pending_ = Request::kNone;
+ Request active_ = Request::kNone;
+ bool pending_cancel_ = false;
+ std::uint64_t revision_ = 0;
+ bool stopping_ = false;
+ std::atomic<bool> cancel_{false};
+ std::thread worker_;
+};
+
+} // namespace playden::steam
diff --git a/tests/download_server_service_test.cpp b/tests/download_server_service_test.cpp
new file mode 100644
index 0000000..5798f6c
--- /dev/null
+++ b/tests/download_server_service_test.cpp
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/download_server_service.h"
+
+#include <cassert>
+#include <chrono>
+#include <thread>
+
+using namespace playden;
+using namespace playden::steam;
+using namespace std::chrono_literals;
+
+namespace {
+class Sessions final : public SessionRepository {
+ public:
+ bool signed_in = true;
+ Result<std::optional<StoredSession>> Load() const override {
+ return Result<std::optional<StoredSession>>::Success(signed_in ? std::optional<StoredSession>(StoredSession{1,"","r","a",{}}) : std::nullopt);
+ }
+ Result<void> Save(const StoredSession&) const override { return Result<void>::Success(); }
+ Result<void> Clear() const override { return Result<void>::Success(); }
+};
+class Source final : public DownloadServerSource {
+ public:
+ bool list_ok = true;
+ bool installed = true;
+ std::atomic<bool> block{false}, entered{false};
+ std::atomic<bool> block_prepare{false}, preparing{false};
+ std::uint64_t budget = 60'000'000;
+ std::vector<std::uint64_t> budgets;
+ bool List(const std::atomic<bool>&, std::vector<DownloadServerView>* out) override {
+ for (int i = 0; i < 8; ++i) out->push_back({"private-host-" + std::to_string(i), "Server", false});
+ return list_ok;
+ }
+ DownloadServerPreparation Prepare(const StoredSession&, const std::atomic<bool>& cancel) override {
+ preparing = true;
+ while (block_prepare && !cancel) std::this_thread::sleep_for(1ms);
+ return {installed ? DownloadServerPreparation::Error::kNone : DownloadServerPreparation::Error::kNeedsInstalledGame, 228980, budget};
+ }
+ DownloadServerRate Measure(const std::string& id, std::uint64_t budget, const std::atomic<bool>& cancel) override {
+ budgets.push_back(budget);
+ entered = true;
+ while (block && !cancel) std::this_thread::sleep_for(1ms);
+ return {id, 12.5, false};
+ }
+ std::string LogLabel(const std::string&) const override { return "private-host-must-not-leak"; }
+};
+DownloadServerSnapshot Await(DownloadServerService& service, DownloadServerSnapshot::Phase phase) {
+ for (int i = 0; i < 2000; ++i) {
+ const auto s = service.Snapshot();
+ if (s.phase == phase) return s;
+ std::this_thread::sleep_for(1ms);
+ }
+ assert(false && "worker did not finish");
+ return {};
+}
+void ListingAndLimits() {
+ Sessions sessions;
+ Source source;
+ DownloadServerService service(source, sessions);
+ std::vector<std::string> logs;
+ service.SetLog([&](std::uint32_t app, const char* step, const char* result, const char* detail) {
+ assert(app == 228980 && std::string(step) == "server-test" && std::string(result) == "done");
+ logs.push_back(detail);
+ });
+ service.List();
+ const auto listed = Await(service, DownloadServerSnapshot::Phase::kListed);
+ assert(listed.servers.size() == 8 && listed.servers[0].id == "private-host-0");
+ service.Test();
+ const auto tested = Await(service, DownloadServerSnapshot::Phase::kTested);
+ service.Shutdown();
+ assert(tested.rates.size() == 8 && tested.rates[0].mb_per_s == 12.5);
+ std::uint64_t total = 0;
+ for (const auto budget : source.budgets) { assert(budget <= 32'000'000); total += budget; }
+ assert(total <= 60'000'000); // preparation has already consumed the other 100 MB
+ assert(!logs.empty());
+ for (const auto& line : logs) { assert(line.size() <= 360); assert(line.find("private-host") == std::string::npos); }
+}
+void FailuresAndSignIn() {
+ Sessions sessions;
+ Source source;
+ source.list_ok = false;
+ DownloadServerService service(source, sessions);
+ service.List();
+ assert(Await(service, DownloadServerSnapshot::Phase::kListFailed).servers.empty());
+ source.list_ok = true;
+ sessions.signed_in = false;
+ service.Test();
+ assert(Await(service, DownloadServerSnapshot::Phase::kTestFailed).needs_sign_in);
+ sessions.signed_in = true;
+ source.installed = false;
+ service.Test();
+ assert(Await(service, DownloadServerSnapshot::Phase::kTestFailed).needs_installed_game);
+}
+void CancellationAndInvalidation() {
+ Sessions sessions;
+ Source source;
+ source.block = true;
+ DownloadServerService service(source, sessions);
+ service.Test();
+ while (!source.entered) std::this_thread::sleep_for(1ms);
+ service.CancelTest();
+ Await(service, DownloadServerSnapshot::Phase::kListed);
+ assert(source.budgets.size() == 1);
+ service.Invalidate();
+ assert(service.Snapshot().rates.empty());
+ service.List();
+ assert(Await(service, DownloadServerSnapshot::Phase::kListed).servers.size() == 8);
+ source.block = false;
+ service.Test();
+ assert(Await(service, DownloadServerSnapshot::Phase::kTested).rates.size() == 8);
+}
+void LogsNeverReusePreviousSamples() {
+ Sessions sessions;
+ Source source;
+ DownloadServerService service(source, sessions);
+ std::vector<std::pair<std::string, std::string>> logs;
+ service.SetLog([&](std::uint32_t, const char*, const char* result, const char* detail) {
+ logs.emplace_back(result, detail);
+ });
+ service.Test();
+ Await(service, DownloadServerSnapshot::Phase::kTested);
+ source.installed = false;
+ service.Test();
+ Await(service, DownloadServerSnapshot::Phase::kTestFailed);
+ assert(logs.back() == std::make_pair(std::string("failed"), std::string("n=0")));
+ source.installed = true;
+ source.preparing = false;
+ source.block_prepare = true;
+ service.Test();
+ while (!source.preparing) std::this_thread::sleep_for(1ms);
+ service.CancelTest();
+ Await(service, DownloadServerSnapshot::Phase::kListed);
+ service.Shutdown();
+ assert(logs.back() == std::make_pair(std::string("canceled"), std::string("n=0")));
+}
+} // namespace
+int main() { ListingAndLimits(); FailuresAndSignIn(); CancellationAndInvalidation(); LogsNeverReusePreviousSamples(); }
diff --git a/tests/download_server_source_test.cpp b/tests/download_server_source_test.cpp
new file mode 100644
index 0000000..f5b64ad
--- /dev/null
+++ b/tests/download_server_source_test.cpp
@@ -0,0 +1,207 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "steam/backend/download_server_source.h"
+
+#include <cassert>
+#include <chrono>
+#include <cstdio>
+#include <mutex>
+#include <thread>
+
+using namespace playden;
+using namespace playden::steam;
+using namespace std::chrono_literals;
+namespace {
+std::vector<std::uint8_t> Read(const std::string& path) {
+ FILE* file = std::fopen(path.c_str(), "rb"); assert(file);
+ std::vector<std::uint8_t> bytes;
+ int c; while ((c = std::fgetc(file)) != EOF) bytes.push_back(static_cast<std::uint8_t>(c));
+ std::fclose(file); return bytes;
+}
+HttpResponse Reply(const std::string& text) {
+ HttpResponse response; response.status_code = 200;
+ response.body.assign(text.begin(), text.end()); return response;
+}
+void ListingPolicy() {
+ std::atomic<bool> cancel{false};
+ for (bool mixed : {false, true}) {
+ CdnClient cdn([&](const HttpRequest& request, const std::atomic<bool>&) {
+ assert(request.url.find("cell_id=0") != std::string::npos);
+ return Reply(std::string(R"({"response":{"servers":[{"type":"CDN","host":"http.example","https_support":"unavailable"})") +
+ (mixed ? R"(,{"type":"CDN","host":"fastly.cdn.steampipe.steamcontent.com","https_support":"mandatory"})" : "") + "]}}");
+ });
+ CdnDownloadServerSource source(cdn, {});
+ std::vector<DownloadServerView> servers;
+ assert(source.List(cancel, &servers) && servers.size() == 1);
+ assert(servers[0].plain_http == !mixed);
+ assert(servers[0].name == (mixed ? "Fastly" : "http.example"));
+ }
+}
+void PayloadAndTransfers(const std::string& fixtures) {
+ const auto manifest = Read(fixtures + "/manifest_encrypted_deflated.zip");
+ std::atomic<bool> cancel{false};
+ CdnClient cdn([&](const HttpRequest& request, const std::atomic<bool>&) {
+ if (request.url.find("/manifest/") != std::string::npos) { auto r = Reply(""); r.body = manifest; return r; }
+ return Reply(R"({"response":{"servers":[{"type":"CDN","host":"fastly.cdn.steampipe.steamcontent.com"},{"type":"CDN","host":"google2.cdn.steampipe.steamcontent.com"}]}})");
+ });
+ std::atomic<std::uint64_t> milliseconds{0}, reserved{0};
+ std::atomic<int> requests{0};
+ CmError primary_error = CmError::kRejected;
+ int fallback_calls = 0;
+ std::vector<std::uint32_t> fallback_depots;
+ CdnDownloadServerSource::Hooks hooks;
+ hooks.app_info = [&](const StoredSession&, std::uint32_t app, const std::atomic<bool>&) {
+ AppInfoBuffers info; info.error = CmError::kNone;
+ info.buffers[app] = "\"appinfo\" { \"appid\" \"" + std::to_string(app) + "\" \"depots\" { \"" +
+ std::string(app == 228980 ? "228990" : "4242001") + "\" { \"manifests\" { \"public\" { \"gid\" \"7234567890123456789\" } } } } }";
+ if (app != 228980) {
+ auto& text = info.buffers[app];
+ const auto depots = text.find("\"depots\" {");
+ text.insert(depots + 10, " \"4242000\" { \"manifests\" { \"public\" { \"gid\" \"4\" } } } ");
+ }
+ return info;
+ };
+ hooks.access = [&](const StoredSession&, std::uint32_t app, const std::vector<DepotRequest>& requests, const std::atomic<bool>&) {
+ DepotAccessResult result;
+ result.error = app == 228980 ? primary_error : CmError::kNone;
+ if (app != 228980) {
+ fallback_depots.push_back(requests[0].depot_id);
+ if (requests[0].depot_id == 4242000) result.error = CmError::kRejected;
+ }
+ if (result.ok()) result.grants.push_back({requests[0].depot_id, requests[0].manifest_gid, {}, 9});
+ return result;
+ };
+ hooks.now = [&] { return CdnDownloadServerSource::Clock::time_point{} + std::chrono::milliseconds(milliseconds.load()); };
+ hooks.perform = [&](std::size_t slot, const HttpRequest& request, const std::atomic<bool>& stop) {
+ assert(slot < 4 && request.timeout_ms <= 8000 && request.max_response_bytes <= 16 * 1024 * 1024);
+ assert(!request.allow_plain_http && request.url.find("/depot/4242001/chunk/") != std::string::npos);
+ assert(!stop);
+ reserved += request.max_response_bytes;
+ ++requests;
+ milliseconds += request.url.find("google2") != std::string::npos ? 200 : 100;
+ auto result = Reply(""); result.body.resize(1000); return result;
+ };
+ CdnDownloadServerSource source(cdn, hooks, [&] { ++fallback_calls; return 440; });
+ std::vector<DownloadServerView> servers;
+ assert(source.List(cancel, &servers) && servers.size() == 2);
+ const auto prepared = source.Prepare({}, cancel);
+ assert(prepared.error == DownloadServerPreparation::Error::kNone && prepared.app_id == 440 && fallback_calls == 1);
+ assert((fallback_depots == std::vector<std::uint32_t>{4242000, 4242001}));
+ const auto fast = source.Measure(servers[0].id, 100'000, cancel);
+ const auto fast_requests = requests.load();
+ assert(!fast.failed && fast.mb_per_s > 0 && reserved <= 100'000 && fast_requests > 0);
+ reserved = 0; requests = 0; milliseconds = 0;
+ const auto slow = source.Measure(servers[1].id, 100'000, cancel);
+ assert(!slow.failed && slow.mb_per_s < fast.mb_per_s && reserved <= 100'000);
+ primary_error = CmError::kNetwork;
+ assert(source.Prepare({}, cancel).error == DownloadServerPreparation::Error::kFailed && fallback_calls == 1);
+ primary_error = CmError::kRejected;
+ CdnDownloadServerSource no_game(cdn, hooks);
+ assert(no_game.List(cancel, &servers));
+ assert(no_game.Prepare({}, cancel).error == DownloadServerPreparation::Error::kNeedsInstalledGame);
+ // A clock crossing the shared deadline prevents subsequent requests and gives each in-flight
+ // transfer only the remaining time, independently of the full eight-second ceiling.
+ hooks.perform = [&](std::size_t, const HttpRequest& request, const std::atomic<bool>&) {
+ assert(request.timeout_ms <= 8000);
+ milliseconds = 8000;
+ auto response = Reply(""); response.body.resize(1000); return response;
+ };
+ CdnDownloadServerSource deadline(cdn, hooks, [] { return 440; });
+ milliseconds = 0;
+ assert(deadline.List(cancel, &servers));
+ assert(deadline.Prepare({}, cancel).error == DownloadServerPreparation::Error::kNone);
+ assert(!deadline.Measure(servers[0].id, 32'000'000, cancel).failed);
+ assert(milliseconds == 8000);
+ requests = 0;
+ hooks.perform = [&](std::size_t, const HttpRequest&, const std::atomic<bool>&) {
+ ++requests;
+ HttpResponse response; response.error = HttpError::kConnectionFailed; return response;
+ };
+ CdnDownloadServerSource failed(cdn, hooks, [] { return 440; });
+ assert(failed.List(cancel, &servers));
+ assert(failed.Prepare({}, cancel).error == DownloadServerPreparation::Error::kNone);
+ assert(failed.Measure(servers[0].id, 32'000'000, cancel).failed);
+ assert(requests >= 2 && requests <= 5); // two failures plus already in-flight slots
+
+ // Every slot must be independently usable; one blocked transfer cannot serialize the others.
+ std::atomic<unsigned> slots{0};
+ hooks.perform = [&](std::size_t slot, const HttpRequest&, const std::atomic<bool>& stop) {
+ slots.fetch_or(1u << slot);
+ while (!stop) std::this_thread::sleep_for(1ms);
+ HttpResponse response; response.error = HttpError::kCanceled; return response;
+ };
+ CdnDownloadServerSource canceled(cdn, hooks, [] { return 440; });
+ assert(canceled.List(cancel, &servers));
+ assert(canceled.Prepare({}, cancel).error == DownloadServerPreparation::Error::kNone);
+ std::thread measurement([&] { canceled.Measure(servers[0].id, 32'000'000, cancel); });
+ const auto wait_until = std::chrono::steady_clock::now() + 2s;
+ while (slots != 15 && std::chrono::steady_clock::now() < wait_until) std::this_thread::sleep_for(1ms);
+ assert(slots == 15);
+ cancel = true;
+ measurement.join();
+ cancel = false;
+
+ // A manifest returned under a different authorized GID is never used as the sample payload.
+ const auto normal_info = hooks.app_info;
+ hooks.app_info = [normal_info](const StoredSession& session, std::uint32_t app, const std::atomic<bool>& stop) {
+ auto result = normal_info(session, app, stop);
+ auto& text = result.buffers[app];
+ const auto gid = text.find("7234567890123456789");
+ assert(gid != std::string::npos);
+ text.replace(gid, 19, "1");
+ return result;
+ };
+ CdnDownloadServerSource mismatched(cdn, hooks, [] { return 440; });
+ assert(mismatched.List(cancel, &servers));
+ assert(mismatched.Prepare({}, cancel).error == DownloadServerPreparation::Error::kFailed);
+}
+void MetadataSharesTheTotalBudget(const std::string& fixtures) {
+ const auto manifest = Read(fixtures + "/manifest_encrypted_deflated.zip");
+ std::atomic<bool> cancel{false};
+ for (const bool exhaust : {false, true}) {
+ std::vector<std::size_t> caps;
+ CdnClient cdn([&](const HttpRequest& request, const std::atomic<bool>&) {
+ if (request.url.find("/manifest/") == std::string::npos)
+ return Reply(R"({"response":{"servers":[{"type":"CDN","host":"a.example"},{"type":"CDN","host":"b.example"}]}})");
+ caps.push_back(request.max_response_bytes);
+ if (exhaust || caps.size() <= 2) {
+ HttpResponse response;
+ response.error = HttpError::kTimeout;
+ response.timing.body_bytes = request.max_response_bytes;
+ return response;
+ }
+ auto response = Reply(""); response.body = manifest; return response;
+ });
+ CdnDownloadServerSource::Hooks hooks;
+ hooks.app_info = [](const StoredSession&, std::uint32_t app, const std::atomic<bool>&) {
+ AppInfoBuffers result; result.error = CmError::kNone;
+ auto& text = result.buffers[app];
+ text = "\"appinfo\" { \"appid\" \"" + std::to_string(app) + "\" \"depots\" { ";
+ if (app == 228980) text += "\"228990\" { \"manifests\" { \"public\" { \"gid\" \"1\" } } } ";
+ else for (int depot = 4242000; depot < 4242010; ++depot)
+ text += "\"" + std::to_string(depot) + "\" { \"manifests\" { \"public\" { \"gid\" \"7234567890123456789\" } } } ";
+ text += "} }";
+ return result;
+ };
+ hooks.access = [](const StoredSession&, std::uint32_t app, const std::vector<DepotRequest>& requests, const std::atomic<bool>&) {
+ DepotAccessResult result; result.error = app == 228980 ? CmError::kRejected : CmError::kNone;
+ if (result.ok()) result.grants.push_back({requests[0].depot_id, requests[0].manifest_gid, {}, 9});
+ return result;
+ };
+ CdnDownloadServerSource source(cdn, hooks, [] { return 440; });
+ std::vector<DownloadServerView> servers;
+ assert(source.List(cancel, &servers));
+ const auto prepared = source.Prepare({}, cancel);
+ std::uint64_t reserved = 0;
+ for (const auto cap : caps) { assert(cap > 0 && cap <= 16 * 1024 * 1024); reserved += cap; }
+ if (exhaust) {
+ assert(prepared.error == DownloadServerPreparation::Error::kFailed);
+ assert(reserved == 160'000'000 - 512 * 1024);
+ assert(caps.back() < 16 * 1024 * 1024);
+ } else {
+ assert(prepared.error == DownloadServerPreparation::Error::kNone);
+ assert(prepared.measurement_byte_budget == 160'000'000 - 512 * 1024 - 2 * 16 * 1024 * 1024 - manifest.size());
+ }
+ }
+}
+} // namespace
+int main(int argc, char** argv) { assert(argc == 2); ListingPolicy(); PayloadAndTransfers(argv[1]); MetadataSharesTheTotalBudget(argv[1]); }