Skip to content

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

C++

Use chosen servers and report per-server download stats

Leonardo Lobato21173df28ad9
diff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cpp
index 243e3e7..85243c8 100644
--- a/src/steam/backend/depot_installer.cpp
+++ b/src/steam/backend/depot_installer.cpp
@@ -202,18 +202,23 @@ DownloadTuning ReadDownloadTuning(const std::string& path) {
FILE* input = std::fopen(path.c_str(), "r");
if (!input) return tuning;
ScopeExit close{[&] { std::fclose(input); }};
- char line[128];
- bool seen_slots = false, seen_ahead = false;
+ char line[272];
+ bool seen_slots = false, seen_ahead = false, seen_server = false;
while (std::fgets(line, sizeof(line), input)) {
std::string text(line);
while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back();
if (text.empty()) continue;
const auto equals = text.find('=');
if (equals == std::string::npos) return {};
+ const auto key = text.substr(0, equals);
+ if (key == "server" && !seen_server && ValidCdnHost(text.substr(equals + 1))) {
+ seen_server = true;
+ tuning.preferred_server = text.substr(equals + 1);
+ continue;
+ }
int value = 0;
const auto parsed = std::from_chars(text.data() + equals + 1, text.data() + text.size(), value);
if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) return {};
- const auto key = text.substr(0, equals);
if (key == "slots" && !seen_slots) {
seen_slots = true;
tuning.slots = std::clamp(value, 1, 8);
@@ -338,6 +343,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
}
hooks_.stats(phase, stats);
};
+ ScopeExit end_stats{[&] { emit("end"); emit("servers"); }};
auto fail = [&outcome](InstallError error, const char* detail) {
outcome.error = error;
outcome.detail = detail;
@@ -377,6 +383,16 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return outcome;
}
+ const auto order = PreferServer(&servers, tuning_.preferred_server);
+ if (hooks_.server_list)
+ hooks_.server_list(servers, tuning_.preferred_server.empty() ? "auto" : order.preferred_found ? "chosen" : "missing");
+ std::vector<InstallServerStats> coordinator_servers;
+ for (std::size_t i = 0; i < std::min<std::size_t>(servers.size(), 8); ++i)
+ coordinator_servers.push_back({CdnServerLabel(servers[i].host), i});
+ if (servers.size() > 8) coordinator_servers.push_back({"other", 8});
+ std::vector<Clock::duration> coordinator_fetch(coordinator_servers.size());
+ stats.server_stats = coordinator_servers;
+
stats.servers_ms = Milliseconds(Clock::now() - phase_start);
phase_start = Clock::now();
trace("manifests");
@@ -389,7 +405,18 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
// cut-off body) is followed by another, after 1, 2, 4 and 8 s, as for chunks.
const std::size_t attempts = std::min<std::size_t>(std::max<std::size_t>(servers.size() * 2, 4), 6);
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
- fetched = hooks_.manifest(servers[attempt % servers.size()], access.grants[index], cancel, &manifests[index]);
+ const auto server_index = attempt % servers.size();
+ const auto bucket = std::min<std::size_t>(server_index, 8);
+ const auto before = hooks_.cdn_stats ? hooks_.cdn_stats() : CdnStats{};
+ fetched = Timed(coordinator_fetch[bucket], [&] {
+ return hooks_.manifest(servers[server_index], access.grants[index], cancel, &manifests[index]);
+ });
+ auto& server = coordinator_servers[bucket];
+ ++server.requests;
+ if (fetched != InstallError::kNone) ++server.failures;
+ if (hooks_.cdn_stats) server.bytes += hooks_.cdn_stats().bytes - before.bytes;
+ server.fetch_ms = Milliseconds(coordinator_fetch[bucket]);
+ stats.server_stats = coordinator_servers;
if (fetched != InstallError::kNetwork && fetched != InstallError::kCorrupt) break;
network_failed = network_failed || fetched == InstallError::kNetwork;
if (hooks_.pause && attempt + 1 < attempts) hooks_.pause(1000 << std::min<std::size_t>(attempt, 3), cancel);
@@ -561,7 +588,6 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return fail(InstallError::kStorage, "cannot write journal");
}
download_start = last_stats = Clock::now();
- ScopeExit end_stats{[&] { emit("end"); }};
auto report_progress = [&] {
const auto now = Clock::now();
if (now - last_stats >= std::chrono::seconds(60)) { emit("progress"); last_stats = now; }
@@ -596,6 +622,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
std::uint64_t compressed_bytes = 0, retries = 0, corrupt_retries = 0;
Clock::duration fetch{}, process{}, backoff{};
CdnStats cdn;
+ std::vector<InstallServerStats> server_stats;
std::function<void()> run;
};
std::vector<std::unique_ptr<Worker>> workers;
@@ -624,9 +651,16 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
fetch = {}; process = {}; backoff = {}; worker_cdn = {};
stats.peak_active = peak_active; stats.peak_waiting = peak_waiting;
stats.chunk_retries = stats.corrupt_retries = 0;
+ stats.server_stats = coordinator_servers;
for (const auto& worker : workers) {
fetch += worker->fetch; process += worker->process; backoff += worker->backoff;
stats.chunk_retries += worker->retries; stats.corrupt_retries += worker->corrupt_retries;
+ for (std::size_t i = 0; i < worker->server_stats.size(); ++i) {
+ auto& server = stats.server_stats[i];
+ const auto& published = worker->server_stats[i];
+ server.requests += published.requests; server.failures += published.failures;
+ server.bytes += published.bytes; server.fetch_ms += published.fetch_ms;
+ }
#define SUM_CDN(field) worker_cdn.field += worker->cdn.field
SUM_CDN(requests); SUM_CDN(failures); SUM_CDN(resolve_ms); SUM_CDN(connect_ms); SUM_CDN(tls_ms);
SUM_CDN(first_byte_ms); SUM_CDN(total_ms); SUM_CDN(new_connections); SUM_CDN(bytes);
@@ -667,6 +701,13 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
// Destroy the HTTP client on the same thread that used it, after publishing its counters.
ScopeExit release_fetcher{[self] { self->fetcher = {}; }};
std::size_t server_cursor = 0;
+ std::uint64_t chunks_since_failover = 0;
+ unsigned failed_returns = 0;
+ bool returning = false;
+ // Both the counters and full-precision timers live on the heap, off the native worker stack.
+ std::vector<InstallServerStats> server_stats = coordinator_servers;
+ for (auto& server : server_stats) server.requests = server.failures = server.bytes = server.fetch_ms = 0;
+ std::vector<Clock::duration> server_fetch(server_stats.size());
Clock::duration fetch_time{}, process_time{}, backoff_time{};
std::uint64_t retries = 0, corrupt_retries = 0;
#if defined(__cpp_exceptions)
@@ -682,6 +723,16 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
++occupied;
peak_active = std::max(peak_active, static_cast<std::uint32_t>(occupied));
}
+ if (order.preferred_found && server_cursor % servers.size() != 0 && failed_returns < 4 &&
+ chunks_since_failover >= (32u << failed_returns)) {
+ server_cursor = 0;
+ returning = true;
+ }
+ const auto failed_over = [&] {
+ if (returning && server_cursor % servers.size() == 0) { ++failed_returns; returning = false; }
+ ++server_cursor;
+ chunks_since_failover = 0;
+ };
const auto& work = chunks[self->work];
const auto& placement = files[work.file].placement;
const auto& grant = access.grants[placement.depot];
@@ -694,13 +745,22 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
for (std::size_t attempt = 0; attempt < attempts && !stop.load(); ++attempt) {
if (attempt > 0) ++retries;
std::vector<std::uint8_t> encrypted;
+ const auto bucket = std::min<std::size_t>(server_cursor % servers.size(), 8);
+ const auto before = self->fetcher.stats ? self->fetcher.stats() : CdnStats{};
const auto fetched = Timed(fetch_time, [&] {
- return self->fetcher.fetch(servers[server_cursor % servers.size()], grant.depot_id, Hex(chunk.sha),
- static_cast<std::size_t>(chunk.compressed_size) + 4096, stop, &encrypted);
+ return Timed(server_fetch[bucket], [&] {
+ return self->fetcher.fetch(servers[server_cursor % servers.size()], grant.depot_id, Hex(chunk.sha),
+ static_cast<std::size_t>(chunk.compressed_size) + 4096, stop, &encrypted);
+ });
});
+ auto& server = server_stats[bucket];
+ ++server.requests;
+ if (fetched != CdnError::kNone) ++server.failures;
+ server.bytes += self->fetcher.stats ? self->fetcher.stats().bytes - before.bytes : encrypted.size();
+ server.fetch_ms = Milliseconds(server_fetch[bucket]);
if (fetched == CdnError::kCanceled || stop.load()) { result = InstallError::kCanceled; break; }
if (fetched != CdnError::kNone) {
- ++server_cursor;
+ failed_over();
result = InstallError::kNetwork;
if (hooks_.pause && attempt + 1 < attempts)
Timed(backoff_time, [&] { hooks_.pause(1000 << std::min<std::size_t>(attempt, 3), stop); });
@@ -710,9 +770,13 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return ProcessDepotChunk(encrypted, grant.key, chunk.original_size, chunk.crc, chunk.sha, &plain);
});
if (processed == ChunkError::kNone) {
+ if (server_cursor % servers.size() == 0) {
+ returning = false;
+ } else ++chunks_since_failover;
compressed_bytes = encrypted.size(); result = InstallError::kNone; break;
}
- ++server_cursor;
+ ++server.failures; // received bytes that failed verification are unusable too
+ failed_over();
if (attempt + 1 < attempts) ++corrupt_retries;
result = InstallError::kCorrupt;
}
@@ -729,6 +793,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
std::lock_guard<std::mutex> lock(mutex);
self->fetch = fetch_time; self->process = process_time; self->backoff = backoff_time;
self->retries = retries; self->corrupt_retries = corrupt_retries; self->cdn = cdn;
+ self->server_stats = server_stats;
if (result != InstallError::kNone) { fail_locked(result, std::move(detail)); break; }
self->plain = std::move(plain); self->compressed_bytes = compressed_bytes;
self->ready = true;
diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.h
index 28d0aea..b47965b 100644
--- a/src/steam/backend/depot_installer.h
+++ b/src/steam/backend/depot_installer.h
@@ -51,11 +51,19 @@ struct InstallProgress {
struct DownloadTuning {
int slots = 4;
int ahead_files = 256;
+ std::string preferred_server; // empty uses Automatic order
};
// A missing or malformed file uses defaults; valid slot counts are clamped to 1..8.
DownloadTuning ReadDownloadTuning(const std::string& path);
+// Manifest and chunk transfers, including failed and corrupt replies.
+struct InstallServerStats {
+ std::string label; // fixed provider label, never a host
+ std::size_t index = 0;
+ std::uint64_t requests = 0, failures = 0, bytes = 0, fetch_ms = 0;
+};
+
// Wall-clock phases and summed stages; worker durations can exceed wall time.
// Bytes exclude resumed journal entries; peak_active counts occupied chunk slots (including waiting).
struct InstallStats : CdnStats {
@@ -66,6 +74,7 @@ struct InstallStats : CdnStats {
std::uint64_t files_total = 0, download_total = 0, chunks_pending = 0, files_pending = 0, bytes_pending = 0;
std::uint32_t slots = 4, reuse = 1, ahead_files = 256;
std::uint32_t peak_waiting = 0, peak_active = 0;
+ std::vector<InstallServerStats> server_stats; // first eight servers, then one "other" bucket
};
struct InstallOutcome {
@@ -97,6 +106,7 @@ struct InstallerHooks {
std::function<std::string()> last_failure;
std::function<CdnStats()> cdn_stats;
std::function<void(const char* phase, const InstallStats&)> stats;
+ std::function<void(const std::vector<ContentServer>&, const char* preference)> server_list;
// Optional: step markers for diagnosing native failures (no identifiers).
std::function<void(const char* step)> trace;
// Optional: waits between attempts at a chunk the CDN refused (a busy server answers 503 for a
@@ -125,6 +135,9 @@ class DepotInstaller {
InstallerHooks hooks_;
public:
void SetStats(std::function<void(const char*, const InstallStats&)> stats) { hooks_.stats = std::move(stats); }
+ void SetServerList(std::function<void(const std::vector<ContentServer>&, const char*)> listed) {
+ hooks_.server_list = std::move(listed);
+ }
void SetTrace(std::function<void(const char*)> trace) { hooks_.trace = std::move(trace); }
void SetTuning(DownloadTuning tuning) { tuning_ = tuning; }
private:
diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cpp
index 801dc23..5a5ca4c 100644
--- a/src/steam/backend/steam_install_runner.cpp
+++ b/src/steam/backend/steam_install_runner.cpp
@@ -3,6 +3,7 @@
#include "runtime/steamworks.h"
#include "steam/backend/app_info.h"
+#include <algorithm>
#include <set>
#include <charconv>
@@ -15,6 +16,41 @@ void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* mar
else log(app, "trace", marker, "");
}
+std::string FormatInstallServerList(const std::vector<ContentServer>& servers, const char* preference) {
+ const std::string pref = preference ? preference : "auto";
+ std::string detail = "n=" + std::to_string(servers.size()) + " https=" +
+ std::to_string(std::count_if(servers.begin(), servers.end(), [](const ContentServer& server) { return server.https; })) +
+ " pref=" + (pref == "chosen" || pref == "missing" ? pref : "auto") + " first=" +
+ (servers.empty() ? "none" : CdnServerLabel(servers.front().host) + "@0") + " order=";
+ for (std::size_t i = 0; i < std::min<std::size_t>(servers.size(), 8); ++i) {
+ if (i) detail += ',';
+ detail += CdnServerLabel(servers[i].host) + ':' + std::to_string(std::clamp(servers[i].priority, 0, 9));
+ }
+ return detail;
+}
+
+std::vector<std::string> FormatInstallServerStats(const std::vector<InstallServerStats>& servers) {
+ std::vector<std::string> lines;
+ std::string detail;
+ for (std::size_t i = 0; i < std::min<std::size_t>(servers.size(), 9); ++i) {
+ const auto& server = servers[i];
+ if (!server.requests) continue;
+ const auto& label = server.label;
+ const bool known = label == "akamai" || label == "fastly" || label == "google" || label == "alibaba" ||
+ label == "edgenext" || label == "valve" || label == "cache" || label == "other";
+ const auto token = std::string(known ? label : "cache") + '@' + std::to_string(std::min<std::size_t>(server.index, 8)) +
+ ":req=" + std::to_string(server.requests) + ",fail=" + std::to_string(server.failures) +
+ ",mb=" + std::to_string(server.bytes / 1000000) + ",ms=" + std::to_string(server.fetch_ms);
+ // Leave room for timestamp, app, step and result in the native 640-byte log buffer.
+ if (!detail.empty() && detail.size() + 1 + token.size() > 360) { lines.push_back(std::move(detail)); detail.clear(); }
+ if (!detail.empty()) detail += ' ';
+ detail += token;
+ }
+ if (!detail.empty()) lines.push_back(std::move(detail));
+ if (lines.empty()) lines.push_back("n=0");
+ return lines;
+}
+
std::string FormatInstallStats(const char* phase, const InstallStats& stats) {
std::string detail;
const auto add = [&](const char* key, std::uint64_t value) {
diff --git a/src/steam/backend/steam_install_runner.h b/src/steam/backend/steam_install_runner.h
index 85e344c..7a9e381 100644
--- a/src/steam/backend/steam_install_runner.h
+++ b/src/steam/backend/steam_install_runner.h
@@ -8,6 +8,8 @@
namespace playden::steam {
std::string FormatInstallStats(const char* phase, const InstallStats& stats);
+std::string FormatInstallServerList(const std::vector<ContentServer>& servers, const char* preference);
+std::vector<std::string> FormatInstallServerStats(const std::vector<InstallServerStats>& servers);
using InstallLogFn = std::function<void(std::uint32_t app, const char* step, const char* category, const char* detail)>;
void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* marker);
@@ -30,10 +32,21 @@ class SteamInstallRunner final : public SessionInstallRunner {
log_ = log;
installer_.SetStats([this, log](const char* phase, const InstallStats& stats) {
if (log) {
+ if (std::string(phase) == "servers") {
+ for (const auto& detail : FormatInstallServerStats(stats.server_stats))
+ log(current_app_.load(), "stats", "servers", detail.c_str());
+ return;
+ }
const auto detail = FormatInstallStats(phase, stats);
log(current_app_.load(), "stats", phase, detail.c_str());
}
});
+ installer_.SetServerList([this, log](const std::vector<ContentServer>& servers, const char* preference) {
+ if (log) {
+ const auto detail = FormatInstallServerList(servers, preference);
+ log(current_app_.load(), "servers", "listed", detail.c_str());
+ }
+ });
installer_.SetTrace([this, log](const char* step) { LogInstallTrace(log, current_app_.load(), step); });
}
diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cpp
index d82636c..9a190ce 100644
--- a/tests/depot_installer_test.cpp
+++ b/tests/depot_installer_test.cpp
@@ -5,6 +5,7 @@
#include <mbedtls/aes.h>
#include <mbedtls/sha1.h>
+#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
@@ -545,14 +546,183 @@ void TuningFileDefaultsAndValidation(const std::filesystem::path& root) {
std::ofstream(path) << "slots=8\nahead=12\n";
tuning = ReadDownloadTuning(path);
CHECK(tuning.slots == 8 && tuning.ahead_files == 12);
+ std::ofstream(path) << "slots=6\nahead=32\nserver=fastly.cdn.steampipe.steamcontent.com\n";
+ tuning = ReadDownloadTuning(path);
+ CHECK(tuning.slots == 6 && tuning.ahead_files == 32 && tuning.preferred_server == "fastly.cdn.steampipe.steamcontent.com");
+ const std::string longest(253, 'a');
+ std::ofstream(path) << "server=" << longest << "\n";
+ CHECK(ReadDownloadTuning(path).preferred_server == longest);
std::ofstream(path) << "slots=99\n";
CHECK(ReadDownloadTuning(path).slots == 8);
std::ofstream(path) << "slots=0\n";
CHECK(ReadDownloadTuning(path).slots == 1);
- for (const auto text : {"slots=8\nahead=-1\n", "slots=abc\n", "slots=8garbage\n", "unknown=1\n", "slots=8\nslots=1\n"}) {
+ for (const auto text : {"slots=8\nahead=-1\n", "slots=abc\n", "slots=8garbage\n", "unknown=1\n", "slots=8\nslots=1\n", "server=bad host\n",
+ "server=https://host\n", "server=host\nserver=other\n", "server=\n"}) {
std::ofstream(path) << text;
tuning = ReadDownloadTuning(path);
- CHECK(tuning.slots == 4 && tuning.ahead_files == 256);
+ CHECK(tuning.slots == 4 && tuning.ahead_files == 256 && tuning.preferred_server.empty());
+ }
+}
+
+void PreferredServerFailover(const std::filesystem::path& base) {
+ // A single slot makes the return schedule independent of thread scheduling.
+ for (int mode = 0; mode < 6; ++mode) {
+ auto world = MakeWorld();
+ std::vector<std::string> pieces(600, "chunk");
+ world.manifests[441].files = {world.AddFile("payload", pieces)};
+ world.manifests[442].files.clear();
+ auto hooks = world.Hooks();
+ std::vector<std::string> manifests, requests;
+ std::vector<int> preferred_at;
+ int done = 0;
+ hooks.manifest = [&](const ContentServer& server, const DepotGrant& grant, const std::atomic<bool>&, DepotManifest* out) {
+ manifests.push_back(server.host); *out = world.manifests.at(grant.depot_id); return InstallError::kNone;
+ };
+ const auto fetch = hooks.chunk;
+ std::atomic<bool> cancel{false};
+ hooks.chunk = [&](const ContentServer& server, std::uint32_t depot, const std::string& sha,
+ std::size_t cap, const std::atomic<bool>& stop, std::vector<std::uint8_t>* out) {
+ requests.push_back(server.host);
+ const bool preferred = server.host == "b.example.invalid";
+ if (preferred) preferred_at.push_back(done);
+ if (mode == 5 && preferred) {
+ cancel.store(true);
+ while (!stop.load()) usleep(1000);
+ return CdnError::kCanceled;
+ }
+ if ((mode == 1 && preferred && preferred_at.size() == 1) || (mode == 2 && preferred) ||
+ ((mode == 3 || mode == 4) && requests.size() == 1)) return CdnError::kNetwork;
+ const auto result = fetch(server, depot, sha, cap, stop, out);
+ if (result == CdnError::kNone) ++done;
+ return result;
+ };
+ std::string listed;
+ hooks.server_list = [&](const std::vector<ContentServer>& servers, const char* preference) {
+ listed = FormatInstallServerList(servers, preference);
+ };
+ InstallStats last;
+ int ends = 0, server_ends = 0;
+ hooks.stats = [&](const char* phase, const InstallStats& stats) {
+ if (std::string(phase) == "end") { last = stats; ++ends; }
+ if (std::string(phase) == "servers") ++server_ends;
+ };
+ DepotInstaller installer(hooks);
+ DownloadTuning tuning{1, 256};
+ if (mode != 3 && mode != 4) tuning.preferred_server = "b.example.invalid";
+ if (mode == 4) tuning.preferred_server = "missing.example.invalid";
+ installer.SetTuning(tuning);
+ const auto outcome = installer.Run({}, Target(base / std::to_string(mode)), cancel);
+ CHECK(ends == 1 && server_ends == 1);
+ CHECK(listed.find(mode == 4 ? "pref=missing" : mode == 3 ? "pref=auto" : "pref=chosen") != std::string::npos);
+ CHECK(manifests.front() == (mode == 3 || mode == 4 ? "a.example.invalid" : "b.example.invalid"));
+ CHECK(requests.front() == manifests.front());
+ CHECK(outcome.error == (mode == 5 ? InstallError::kCanceled : InstallError::kNone));
+ CHECK(last.server_stats.size() == 2);
+ std::uint64_t counted = 0, failures = 0;
+ for (const auto& server : last.server_stats) { counted += server.requests; failures += server.failures; }
+ CHECK(counted == requests.size() + manifests.size());
+ if (mode == 0) CHECK(preferred_at.size() == 600 && failures == 0);
+ if (mode == 1) {
+ CHECK(preferred_at.size() == 569 && preferred_at[0] == 0 && preferred_at[1] == 32);
+ CHECK(requests[1] == "a.example.invalid" && failures == 1);
+ }
+ if (mode == 2) {
+ CHECK(preferred_at == std::vector<int>({0, 32, 96, 224, 480}));
+ CHECK(failures == 5 && last.server_stats[0].requests == 7);
+ }
+ if (mode == 3 || mode == 4) {
+ CHECK(requests.size() == 601 && failures == 1);
+ CHECK(requests[0] == "a.example.invalid");
+ for (std::size_t i = 1; i < requests.size(); ++i) CHECK(requests[i] == "b.example.invalid");
+ }
+ if (mode == 5) CHECK(failures == 1);
+ }
+}
+
+void ServerLogsAreBoundedAndPrivate() {
+ std::vector<ContentServer> servers{{"fastly.cdn.steampipe.steamcontent.com", "private-vhost", 0, true, 2},
+ {"steampipe.akamaized.net", "private-vhost", 0, true, 1},
+ {"isp.private.example", "private-vhost", 0, false, 9}};
+ CHECK(FormatInstallServerList(servers, "chosen") ==
+ "n=3 https=2 pref=chosen first=fastly@0 order=fastly:2,akamai:1,cache:9");
+ std::vector<InstallServerStats> stats{{"fastly", 0, 812, 0, 790000000, 301200}, {"akamai", 1, 3, 0, 2000000, 900}};
+ CHECK(FormatInstallServerStats(stats) == std::vector<std::string>{
+ "fastly@0:req=812,fail=0,mb=790,ms=301200 akamai@1:req=3,fail=0,mb=2,ms=900"});
+ for (int i = 3; i < 10; ++i) servers.push_back({"secret" + std::to_string(i) + ".example", "private-vhost", 0, true, 99});
+ const auto listed = FormatInstallServerList(servers, "auto");
+ CHECK(listed.find("secret") == std::string::npos && listed.find("private") == std::string::npos);
+ CHECK(listed.size() < 380);
+ CHECK(std::count(listed.begin(), listed.end(), ',') == 7);
+ stats.clear();
+ for (std::size_t i = 0; i < 9; ++i)
+ stats.push_back({i == 8 ? "other" : "edgenext", i, UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX});
+ const auto lines = FormatInstallServerStats(stats);
+ CHECK(lines.size() > 1);
+ for (const auto& line : lines) CHECK(line.size() < 380 && line.find("example") == std::string::npos);
+}
+
+void CorruptRepliesCountAsServerFailures(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ world.corrupt = true;
+ auto hooks = world.Hooks();
+ InstallStats last;
+ hooks.stats = [&](const char* phase, const InstallStats& stats) { if (std::string(phase) == "end") last = stats; };
+ DepotInstaller installer(hooks);
+ installer.SetTuning({1, 256});
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, Target(root), cancel).error == InstallError::kCorrupt);
+ CHECK(last.server_stats.size() == 2);
+ CHECK(last.server_stats[0].requests == 5 && last.server_stats[0].failures == 3);
+ CHECK(last.server_stats[1].requests == 3 && last.server_stats[1].failures == 3);
+}
+
+void ExtraServersShareOneBucket(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ auto hooks = world.Hooks();
+ hooks.servers = [](std::uint32_t, const std::atomic<bool>&, std::vector<ContentServer>* out) {
+ for (int i = 0; i < 12; ++i) out->push_back({"host" + std::to_string(i) + ".example", "vhost"});
+ return CdnError::kNone;
+ };
+ const auto fetch = hooks.chunk;
+ int requests = 0;
+ hooks.chunk = [&](const ContentServer& server, std::uint32_t depot, const std::string& sha, std::size_t cap,
+ const std::atomic<bool>& stop, std::vector<std::uint8_t>* out) {
+ ++requests;
+ usleep(600);
+ // First chunk reaches index 5; the next reaches index 9, then stays there.
+ if (requests != 6 && requests < 11) return CdnError::kNetwork;
+ return fetch(server, depot, sha, cap, stop, out);
+ };
+ InstallStats last;
+ hooks.stats = [&](const char* phase, const InstallStats& stats) { if (std::string(phase) == "end") last = stats; };
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ installer.SetTuning({1, 256});
+ CHECK(installer.Run({}, Target(root), cancel).error == InstallError::kNone);
+ CHECK(last.server_stats.size() == 9 && last.server_stats[8].label == "other" && last.server_stats[8].index == 8);
+ CHECK(last.server_stats[8].requests == 3 && last.server_stats[8].failures == 1);
+ CHECK(last.server_stats[8].bytes > 0 && last.server_stats[8].fetch_ms >= 1);
+}
+
+void EarlyFailuresLogServerTotals(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ for (int mode = 0; mode < 3; ++mode) {
+ auto hooks = world.Hooks();
+ std::atomic<bool> cancel{mode == 0};
+ if (mode == 1) hooks.servers = [](std::uint32_t, const std::atomic<bool>&, std::vector<ContentServer>*) {
+ return CdnError::kNetwork;
+ };
+ if (mode == 2) hooks.manifest = [](const ContentServer&, const DepotGrant&, const std::atomic<bool>&, DepotManifest*) {
+ return InstallError::kNetwork;
+ };
+ int ends = 0, servers = 0;
+ hooks.stats = [&](const char* phase, const InstallStats&) {
+ if (std::string(phase) == "end") ++ends;
+ if (std::string(phase) == "servers") ++servers;
+ };
+ DepotInstaller installer(hooks);
+ CHECK(installer.Run({}, Target(root), cancel).error != InstallError::kNone);
+ CHECK(ends == 1 && servers == 1);
}
}
@@ -1066,6 +1236,11 @@ int main() {
ParallelCorruptRetryAndResume(base / "parallel-resume");
FileCreationAheadIsBounded(base / "ahead");
TuningFileDefaultsAndValidation(base / "tuning");
+ PreferredServerFailover(base / "preferred");
+ ServerLogsAreBoundedAndPrivate();
+ EarlyFailuresLogServerTotals(base / "early-logs");
+ ExtraServersShareOneBucket(base / "server-buckets");
+ CorruptRepliesCountAsServerFailures(base / "corrupt-server");
ParallelMergedAndFullyResumed(base / "parallel-merged");
BorrowedDepotRefusedIsSkipped(base / "borrowed-depot");
CountsActualUsefulCompressedBytes(base / "actual-compressed");
diff --git a/tests/test_download_speed_report.py b/tests/test_download_speed_report.py
index 8db117e..dca97a3 100644
--- a/tests/test_download_speed_report.py
+++ b/tests/test_download_speed_report.py
@@ -64,6 +64,21 @@ class DownloadSpeedReportTest(unittest.TestCase):
"2026-10-12T10:00:00Z app=440 step=app_info result=none detail=\n"
"2026-10-12T10:00:00Z app=440 step=entitlements result=none detail=\n"), [])
+ def test_server_labels_and_split_throughput_lines(self):
+ rows = report.parse_runs("""2026-10-12T10:00:00Z app=440 step=trace result=access detail=
+2026-10-12T10:00:01Z app=440 step=servers result=listed detail=n=3 https=3 pref=chosen first=fastly@0 order=fastly:2,akamai:1,cache:1
+2026-10-12T10:00:03Z app=440 step=stats result=end detail=dl_ms=2000 cb=4000000
+2026-10-12T10:00:03Z app=440 step=stats result=servers detail=fastly@0:req=4,fail=0,mb=4,ms=2000 akamai@1:req=1,fail=1,mb=0,ms=0
+2026-10-12T10:00:03Z app=440 step=stats result=servers detail=cache@2:req=2,fail=0,mb=3,ms=1000
+2026-10-12T10:00:03Z app=440 step=install result=none detail=
+""")
+ self.assertEqual(rows[0]["first_server"], "fastly@0")
+ self.assertEqual(rows[0]["server_mb_s"], "fastly@0:2.00 akamai@1:- cache@2:3.00")
+ output = report.io.StringIO()
+ report.write_csv(rows, output)
+ self.assertIn("first_server,server_mb_s", output.getvalue())
+ self.assertIn("fastly@0:2.00", output.getvalue())
+
def test_missing_rotated_log_is_not_requested(self):
ftp = MagicMock()
ftp.__enter__.return_value = ftp
diff --git a/tools/download_speed_report.py b/tools/download_speed_report.py
index d9a91a0..d9db309 100644
--- a/tools/download_speed_report.py
+++ b/tools/download_speed_report.py
@@ -7,6 +7,8 @@ preparation requests. DNS/TCP/TLS/TTFB cover all CDN requests in the run. TTFB i
cumulative curl start-transfer time, so it overlaps TCP/TLS and is not a separate
write-loop stage. File creation floor is the requested comparison (22.5 ms/file),
not a measured duration. Interrupted runs use their last progress snapshot.
+Per-server MB/s uses the logged whole MB divided by summed fetch time, so parallel
+requests do not make it a wall-clock download rate.
Example: download_speed_report.py --host 192.168.1.50 --app 439490 \
--since 2026-10-12T10:00:00Z --csv results/baseline.csv
@@ -25,8 +27,12 @@ LOGS = "/data/playden/logs"
OLD_LOGS = "/data/homebrew/FAKE77031/logs" # before 0.6.0
LINE = re.compile(r"^(\S+) app=(\d+) step=(\S+) result=(\S+) detail=(.*)$")
METRIC = re.compile(r"\b([a-z_]+)=(\d+)\b")
+SERVER_LABEL = r"(?:akamai|fastly|google|alibaba|edgenext|valve|cache|other)"
+FIRST_SERVER = re.compile(r"\bfirst=(" + SERVER_LABEL + r"@[0-8])(?: |$)")
+SERVER_METRIC = re.compile(r"(" + SERVER_LABEL + r"@[0-8]):req=\d+,fail=\d+,mb=(\d+),ms=(\d+)(?: |$)")
STAGES = ("fetch", "proc", "create", "write", "jrnl", "back")
COLUMNS = ("app", "start", "outcome", "sample", "files_total", "compressed_bytes", "download_ms", "mb_s",
+ "first_server", "server_mb_s",
*(stage + "_pct" for stage in STAGES), "req", "conn", "retry", "bad", "slots", "reuse",
"creation_floor_ms", "res", "tcp", "tls", "ttfb", "http_ms", "http_b", "fail",
"access", "servers", "manifest", "prep", "ch", "sk", "fc", "dc", "original_bytes",
@@ -46,7 +52,8 @@ def parse_runs(text):
active, runs = {}, []
def begin(app, start):
- run = {"app": app, "start": start, "outcome": "interrupted", "sample": "missing", "metrics": {}}
+ run = {"app": app, "start": start, "outcome": "interrupted", "sample": "missing", "metrics": {},
+ "first_server": None, "server_rates": {}}
active[app] = run
runs.append(run)
return run
@@ -64,6 +71,14 @@ def parse_runs(text):
run["metrics"].update({key: int(value) for key, value in METRIC.findall(detail)})
if result != "shape":
run["sample"] = result
+ elif step == "servers" and result == "listed":
+ run = active.get(app) or begin(app, start)
+ first = FIRST_SERVER.search(detail)
+ run["first_server"] = first.group(1) if first else None
+ elif step == "stats" and result == "servers":
+ run = active.get(app) or begin(app, start)
+ for server, mb, milliseconds in SERVER_METRIC.findall(detail):
+ run["server_rates"][server] = int(mb) * 1000 / int(milliseconds) if int(milliseconds) else None
elif step == "install":
run = active.pop(app, None) or begin(app, start)
run["outcome"] = result
@@ -78,6 +93,9 @@ def parse_runs(text):
rows = []
for run in runs:
metrics = run.pop("metrics")
+ rates = run.pop("server_rates")
+ run["server_mb_s"] = " ".join(server + ":" + (f"{rate:.2f}" if rate is not None else "-")
+ for server, rate in rates.items()) or None
row = {column: None for column in COLUMNS}
row.update(run)
row.update({key: value for key, value in metrics.items() if key in COLUMNS})
@@ -162,7 +180,7 @@ def main(argv=None):
with Path(args.csv).open("w", newline="") as output:
write_csv(rows, output)
else:
- columns = COLUMNS[:21]
+ columns = COLUMNS[:23]
print("\t".join(columns))
for row in rows:
print("\t".join("-" if row[column] is None else