Skip to content

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

C++

Measure Steam download stages

Leonardo Lobato2581f38f72df
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index 181022e..bf23845 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -222,6 +222,8 @@ 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_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")
target_link_libraries(store_details_test PRIVATE playden_steam_core)
add_test(NAME store_details COMMAND store_details_test)
diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cpp
index 59334c8..2f29a1d 100644
--- a/src/homebrew/host.cpp
+++ b/src/homebrew/host.cpp
@@ -504,8 +504,11 @@ int main(int argc, char** argv) {
install_cdn = std::make_unique<playden::steam::CdnClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);
install_runner = std::make_unique<playden::steam::SteamInstallRunner>(*install_cm, *install_cdn);
install_runner->SetLog([log_directory](playden::GameId app, const char* step, const char* category, const char* detail) {
- char line[320];
- std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);
+ char line[640];
+ if (std::string(step) == "install-removal")
+ std::snprintf(line, sizeof(line), "install-removal done app=%u %s", app, detail);
+ else
+ std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);
playden::app::AppendLogLine(log_directory, "install.log", line);
});
install_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string());
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index ed78c7a..102b0cf 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -139,27 +139,31 @@ struct UsbKeyboard {
std::string title_root = "/app0";
std::string log_root = "/app0/logs";
-// Development aid for unattended console runs: /app0/dev/install-request.txt holding Steam app
-// IDs, one per line, queues those installs once. Nothing in the UI triggers it. The file stays
-// until Playden can queue them (its game runtime started); each ID is logged in install.log.
-std::vector<std::uint32_t> take_install_requests(bool runtime_ready) {
+// Development requests are processed in file order on the first frame.
+std::vector<playden::steam::InstallRequest> take_install_requests(bool runtime_ready) {
const std::string request_path = title_root + "/dev/install-request.txt";
- std::vector<std::uint32_t> apps;
FILE* request = std::fopen(request_path.c_str(), "r");
- if (!request) return apps;
+ if (!request) return {};
+ std::string text;
char line[64] = {};
- while (apps.size() < 64 && std::fgets(line, sizeof(line), request))
- if (const auto app = static_cast<std::uint32_t>(std::strtoul(line, nullptr, 10))) apps.push_back(app);
+ while (text.size() < 4096 && std::fgets(line, sizeof(line), request)) {
+ // Reject an overlong line rather than executing its truncated prefix.
+ if (!std::strchr(line, '\n') && !std::feof(request)) {
+ int value;
+ while ((value = std::fgetc(request)) != '\n' && value != EOF) {}
+ continue;
+ }
+ text += line;
+ }
std::fclose(request);
+ const auto requests = playden::steam::ParseInstallRequests(text);
if (!runtime_ready) {
playden::app::AppendLogLine(log_root, "install.log", "install-request kept: the game runtime is not available (" +
- std::to_string(apps.size()) + " app ids)");
+ std::to_string(requests.size()) + " commands)");
return {};
}
std::remove(request_path.c_str());
- for (const auto app : apps)
- playden::app::AppendLogLine(log_root, "install.log", "install-request queued app=" + std::to_string(app));
- return apps;
+ return requests;
}
} // namespace
@@ -269,8 +273,11 @@ int main() {
playden::steam::CdnClient install_cdn(paths.trust_store);
playden::steam::SteamInstallRunner install_runner(install_cm, install_cdn);
install_runner.SetLog([](playden::GameId app, const char* step, const char* category, const char* detail) {
- char line[320];
- std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);
+ char line[640];
+ if (std::string(step) == "install-removal")
+ std::snprintf(line, sizeof(line), "install-removal done app=%u %s", app, detail);
+ else
+ std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);
playden::app::AppendLogLine(log_root, "install.log", line);
});
playden::LocalSessionRepository install_sessions(paths.steam_state_root);
@@ -488,7 +495,15 @@ int main() {
presented = true;
playden::app::AppendLogLine(log_root, "launch.log", "first frame presented");
#if !PLAYDEN_UI_SIMULATION
- for (const auto app : take_install_requests(native_access.runtime_ready)) installs.Install(app);
+ for (const auto& request : take_install_requests(native_access.runtime_ready)) {
+ using Action = playden::steam::InstallRequest::Action;
+ const char* action = "queued";
+ if (request.action == Action::kUninstall) { action = "uninstall"; installs.Uninstall(request.app); }
+ else if (request.action == Action::kCancel) { action = "cancel"; installs.Cancel(request.app); }
+ else installs.Install(request.app);
+ playden::app::AppendLogLine(log_root, "install.log", "install-request " + std::string(action) +
+ " app=" + std::to_string(request.app));
+ }
#endif
}
// Work advances only through the documented manual fixture clock.
diff --git a/src/steam/backend/cdn_client.cpp b/src/steam/backend/cdn_client.cpp
index f6aa75e..0cfc476 100644
--- a/src/steam/backend/cdn_client.cpp
+++ b/src/steam/backend/cdn_client.cpp
@@ -45,6 +45,15 @@ CdnError CdnClient::Get(const std::string& url, std::size_t max_bytes, std::uint
response = http_->Perform(request, cancel);
}
const auto error = FromHttp(response);
+ ++stats_.requests;
+ if (error != CdnError::kNone) ++stats_.failures;
+ stats_.resolve_ms += response.timing.resolve_ms;
+ stats_.connect_ms += response.timing.connect_ms;
+ stats_.tls_ms += response.timing.tls_ms;
+ 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;
if (error == CdnError::kNone) {
*out = std::move(response.body);
} else {
diff --git a/src/steam/backend/cdn_client.h b/src/steam/backend/cdn_client.h
index 1fded68..306204e 100644
--- a/src/steam/backend/cdn_client.h
+++ b/src/steam/backend/cdn_client.h
@@ -18,6 +18,12 @@ struct ContentServer {
int load = 100;
};
+struct CdnStats {
+ std::uint64_t requests = 0, failures = 0;
+ std::uint64_t resolve_ms = 0, connect_ms = 0, tls_ms = 0, first_byte_ms = 0, total_ms = 0;
+ std::uint64_t new_connections = 0, bytes = 0;
+};
+
enum class CdnError { kNone, kCanceled, kNetwork, kNotFound, kProtocol };
// Steam CDN access over the verified HTTPS client: the content server list for the account's
@@ -40,6 +46,7 @@ class CdnClient {
// Bounded by the HTTP client's response cap.
static constexpr std::size_t kMaxManifestDownloadBytes = kMaxHttpResponseBytes;
// 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_; }
private:
@@ -49,6 +56,7 @@ class CdnClient {
Perform perform_;
std::unique_ptr<HttpClient> http_;
std::string last_failure_;
+ CdnStats stats_;
};
// A host or vhost from the directory may only contain DNS name characters.
diff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cpp
index ccdb210..da70fe7 100644
--- a/src/steam/backend/depot_installer.cpp
+++ b/src/steam/backend/depot_installer.cpp
@@ -12,6 +12,7 @@
#include <algorithm>
#include <cctype>
+#include <chrono>
#include <cstdio>
#include <cstring>
#include <limits>
@@ -22,6 +23,22 @@
namespace playden::steam {
namespace {
+using Clock = std::chrono::steady_clock;
+struct ScopeExit {
+ std::function<void()> fn;
+ ~ScopeExit() { fn(); }
+};
+// Accumulate full clock precision, converting only when a snapshot is emitted.
+template <class Fn>
+auto Timed(Clock::duration& elapsed, Fn fn) -> decltype(fn()) {
+ const auto start = Clock::now();
+ ScopeExit end{[&] { elapsed += Clock::now() - start; }};
+ return fn();
+}
+std::uint64_t Milliseconds(Clock::duration elapsed) {
+ return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count());
+}
+
std::string Hex(const std::array<std::uint8_t, 20>& bytes) {
static constexpr char kDigits[] = "0123456789abcdef";
std::string text;
@@ -37,7 +54,7 @@ std::string Lower(std::string text) {
return text;
}
-bool MakeDirs(const std::string& path) {
+bool MakeDirs(const std::string& path, std::uint64_t* created = nullptr) {
if (path.empty()) return false;
std::string current;
std::size_t start = 0;
@@ -48,7 +65,9 @@ bool MakeDirs(const std::string& path) {
if (!part.empty()) {
if (current.size() > 1 || (current.size() == 1 && current[0] != '/')) current += '/';
current += part;
- if (mkdir(current.c_str(), 0777) != 0) {
+ if (mkdir(current.c_str(), 0777) == 0) {
+ if (created) ++*created;
+ } else {
struct stat info {};
if (stat(current.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) return false;
}
@@ -217,6 +236,7 @@ DepotInstaller::DepotInstaller(CmClient& cm, CdnClient& cdn) {
std::size_t max_bytes, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out) {
return cdn.Chunk(server, depot, sha, max_bytes, cancel, out);
};
+ hooks_.cdn_stats = [&cdn] { return cdn.stats(); };
hooks_.free_bytes = &DefaultFreeBytes;
hooks_.last_failure = [&cdn, manifest_problem] {
return manifest_problem->empty() ? cdn.last_failure() : *manifest_problem;
@@ -234,6 +254,28 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
const std::atomic<bool>& cancel,
const std::function<void(const InstallProgress&)>& on_progress) {
InstallOutcome outcome;
+ InstallStats stats;
+ const auto initial_cdn = hooks_.cdn_stats ? hooks_.cdn_stats() : CdnStats{};
+ Clock::duration fetch{}, process{}, create{}, write{}, journal_time{}, backoff{};
+ auto phase_start = Clock::now();
+ Clock::time_point download_start{}, last_stats{};
+ bool loop_finished = false;
+ auto emit = [&](const char* phase) {
+ if (!hooks_.stats) return;
+ stats.fetch_ms = Milliseconds(fetch); stats.process_ms = Milliseconds(process);
+ stats.create_ms = Milliseconds(create); stats.write_ms = Milliseconds(write);
+ stats.journal_ms = Milliseconds(journal_time); stats.backoff_ms = Milliseconds(backoff);
+ if (download_start != Clock::time_point{} && !loop_finished)
+ stats.download_ms = Milliseconds(Clock::now() - download_start);
+ if (hooks_.cdn_stats) {
+ const auto current = hooks_.cdn_stats();
+#define CDN_DELTA(field) stats.field = current.field - initial_cdn.field
+ CDN_DELTA(requests); CDN_DELTA(failures); CDN_DELTA(resolve_ms); CDN_DELTA(connect_ms);
+ CDN_DELTA(tls_ms); CDN_DELTA(first_byte_ms); CDN_DELTA(total_ms); CDN_DELTA(new_connections); CDN_DELTA(bytes);
+#undef CDN_DELTA
+ }
+ hooks_.stats(phase, stats);
+ };
auto fail = [&outcome](InstallError error, const char* detail) {
outcome.error = error;
outcome.detail = detail;
@@ -259,11 +301,15 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
}
if (access.grants.size() != requests.size()) return fail(InstallError::kProtocol, "incomplete depot access");
+ stats.access_ms = Milliseconds(Clock::now() - phase_start);
+ phase_start = Clock::now();
std::vector<ContentServer> servers;
const auto listed = hooks_.servers(session.cell_id.value_or(0), cancel, &servers);
if (listed == CdnError::kCanceled) return fail(InstallError::kCanceled, "canceled");
if (listed != CdnError::kNone || servers.empty()) return fail(InstallError::kNetwork, "no content servers");
+ stats.servers_ms = Milliseconds(Clock::now() - phase_start);
+ phase_start = Clock::now();
trace("manifests");
// Manifests, in mounting order.
std::vector<DepotManifest> manifests(access.grants.size());
@@ -291,6 +337,8 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
}
}
+ stats.manifests_ms = Milliseconds(Clock::now() - phase_start);
+ phase_start = Clock::now();
trace("merge");
// Later depots replace the same path from earlier ones; identical copies stay with the first.
std::map<std::string, Placement> placements;
@@ -346,56 +394,92 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
for (const auto& [key, placement] : placements) {
if (placement.file->is_directory() || placement.file->is_symlink()) continue;
const auto depot_id = manifests[placement.depot].depot_id;
+ bool pending = placement.file->chunks.empty() && !Exists(target.install_root + "/" + placement.file->path);
for (const auto& chunk : placement.file->chunks) {
- if (done.count(JournalKey(depot_id, placement.file->path, chunk.offset))) progress.download_done += chunk.compressed_size;
- else remaining_bytes += chunk.original_size;
+ if (done.count(JournalKey(depot_id, placement.file->path, chunk.offset))) {
+ progress.download_done += chunk.compressed_size;
+ ++stats.chunks_skipped;
+ } else {
+ remaining_bytes += chunk.original_size;
+ ++stats.chunks_pending;
+ stats.bytes_pending += chunk.compressed_size;
+ pending = true;
+ }
}
+ if (pending) ++stats.files_pending;
}
trace("space");
if (hooks_.free_bytes(target.install_root) < remaining_bytes + 64ull * 1024 * 1024)
return fail(InstallError::kNoSpace, "not enough free space");
if (on_progress) on_progress(progress);
+ stats.prepare_ms = Milliseconds(Clock::now() - phase_start);
+ stats.files_total = progress.files_total;
+ stats.download_total = progress.download_total;
+ emit("shape");
trace("write");
FILE* journal = std::fopen(journal_path.c_str(), "a");
if (!journal) 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; }
+ };
std::size_t server_cursor = 0;
for (const auto& [key, placement] : placements) {
+ report_progress();
const auto& file = *placement.file;
const std::string path = target.install_root + "/" + file.path;
if (file.is_directory()) {
- if (!MakeDirs(path)) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create folder"); }
+ if (!Timed(create, [&] { return MakeDirs(path, &stats.folders_created); })) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create folder"); }
continue;
}
if (file.is_symlink()) continue; // recorded in the install record; the console has no symlinks
- if (!MakeDirs(Parent(path))) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create folder"); }
- if (file.chunks.empty() || !Exists(path)) {
- if (!EnsureFileSize(path, file.size)) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create file"); }
+ if (!Timed(create, [&] { return MakeDirs(Parent(path), &stats.folders_created); })) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create folder"); }
+ const bool existed = Exists(path);
+ if (file.chunks.empty() || !existed) {
+ if (!Timed(create, [&] { return EnsureFileSize(path, file.size); })) { std::fclose(journal); return fail(InstallError::kStorage, "cannot create file"); }
+ if (!existed) ++stats.files_created;
}
const auto& grant = access.grants[placement.depot];
for (const auto& chunk : file.chunks) {
+ report_progress();
const auto entry = JournalKey(grant.depot_id, file.path, chunk.offset);
if (done.count(entry)) continue;
if (cancel.load()) { std::fclose(journal); return fail(InstallError::kCanceled, "canceled"); }
if (progress.download_done == 0) trace("first-chunk");
std::vector<std::uint8_t> plain;
+ std::uint64_t compressed_bytes = 0;
InstallError result = InstallError::kNetwork;
const auto attempts = static_cast<std::size_t>(kChunkAttempts) * std::max<std::size_t>(1, std::min<std::size_t>(servers.size(), 2));
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
+ if (attempt > 0) ++stats.chunk_retries;
std::vector<std::uint8_t> encrypted;
- const auto fetched = hooks_.chunk(servers[server_cursor % servers.size()], grant.depot_id, Hex(chunk.sha),
- static_cast<std::size_t>(chunk.compressed_size) + 4096, cancel, &encrypted);
+ const auto fetched = Timed(fetch, [&] {
+ return hooks_.chunk(servers[server_cursor % servers.size()], grant.depot_id, Hex(chunk.sha),
+ static_cast<std::size_t>(chunk.compressed_size) + 4096, cancel, &encrypted);
+ });
+ report_progress();
if (fetched == CdnError::kCanceled) { std::fclose(journal); return fail(InstallError::kCanceled, "canceled"); }
if (fetched != CdnError::kNone) {
++server_cursor;
result = InstallError::kNetwork;
// 1, 2, 4, 8 s before the next try, so a short CDN outage does not end the download.
- if (hooks_.pause && attempt + 1 < attempts) hooks_.pause(1000 << std::min<std::size_t>(attempt, 3), cancel);
+ if (hooks_.pause && attempt + 1 < attempts)
+ Timed(backoff, [&] { hooks_.pause(1000 << std::min<std::size_t>(attempt, 3), cancel); });
continue;
}
- const auto processed = ProcessDepotChunk(encrypted, grant.key, chunk.original_size, chunk.crc, chunk.sha, &plain);
- if (processed == ChunkError::kNone) { result = InstallError::kNone; break; }
+ const auto processed = Timed(process, [&] {
+ return ProcessDepotChunk(encrypted, grant.key, chunk.original_size, chunk.crc, chunk.sha, &plain);
+ });
+ if (processed == ChunkError::kNone) {
+ compressed_bytes = encrypted.size();
+ result = InstallError::kNone;
+ break;
+ }
++server_cursor;
+ if (attempt + 1 < attempts) ++stats.corrupt_retries;
result = InstallError::kCorrupt;
}
if (result != InstallError::kNone) {
@@ -406,14 +490,21 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return outcome;
}
if (progress.download_done == 0) trace("first-write");
- if (!WriteAt(path, file.size, chunk.offset, plain)) { std::fclose(journal); return fail(InstallError::kStorage, "cannot write file"); }
- std::fprintf(journal, "%s\n", entry.c_str());
- std::fflush(journal);
+ if (!Timed(write, [&] { return WriteAt(path, file.size, chunk.offset, plain); })) { std::fclose(journal); return fail(InstallError::kStorage, "cannot write file"); }
+ Timed(journal_time, [&] {
+ std::fprintf(journal, "%s\n", entry.c_str());
+ std::fflush(journal);
+ });
+ ++stats.chunks_done;
+ stats.compressed_bytes += compressed_bytes;
+ stats.original_bytes += chunk.original_size;
progress.download_done += chunk.compressed_size;
if (on_progress) on_progress(progress);
}
}
std::fclose(journal);
+ stats.download_ms = Milliseconds(Clock::now() - download_start);
+ loop_finished = true;
// Install record, then drop the journal: the record marks a complete, verified install.
const std::string record_path = target.install_root + "/" + kInstallRecord;
diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.h
index 20413fe..6c9df7c 100644
--- a/src/steam/backend/depot_installer.h
+++ b/src/steam/backend/depot_installer.h
@@ -40,6 +40,16 @@ struct InstallProgress {
std::uint32_t files_total = 0;
};
+// Wall-clock phases and summed write-loop stages; bytes exclude resumed journal entries.
+struct InstallStats : CdnStats {
+ std::uint64_t access_ms = 0, servers_ms = 0, manifests_ms = 0, prepare_ms = 0, download_ms = 0;
+ std::uint64_t fetch_ms = 0, process_ms = 0, create_ms = 0, write_ms = 0, journal_ms = 0, backoff_ms = 0;
+ std::uint64_t chunks_done = 0, chunks_skipped = 0, compressed_bytes = 0, original_bytes = 0;
+ std::uint64_t files_created = 0, folders_created = 0, chunk_retries = 0, corrupt_retries = 0;
+ std::uint64_t files_total = 0, download_total = 0, chunks_pending = 0, files_pending = 0, bytes_pending = 0;
+ std::uint32_t slots = 1, reuse = 0;
+};
+
struct InstallOutcome {
InstallError error = InstallError::kProtocol;
InstallProgress progress;
@@ -58,6 +68,8 @@ struct InstallerHooks {
std::function<std::uint64_t(const std::string& path)> free_bytes;
// Optional: the last CDN failure detail for logs.
std::function<std::string()> last_failure;
+ std::function<CdnStats()> cdn_stats;
+ std::function<void(const char* phase, const InstallStats&)> stats;
// 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
@@ -85,6 +97,7 @@ class DepotInstaller {
private:
InstallerHooks hooks_;
public:
+ void SetStats(std::function<void(const char*, const InstallStats&)> stats) { hooks_.stats = std::move(stats); }
void SetTrace(std::function<void(const char*)> trace) { hooks_.trace = std::move(trace); }
};
diff --git a/src/steam/backend/http_client.cpp b/src/steam/backend/http_client.cpp
index 15e3dc9..aae4042 100644
--- a/src/steam/backend/http_client.cpp
+++ b/src/steam/backend/http_client.cpp
@@ -282,8 +282,17 @@ class HttpClient::Impl {
}
#undef PLAYDEN_SETOPT
- resolve_error = internal::AttachNativeResolution(easy, request.url, request.timeout_ms, cancel,
- &resolve_entries);
+ {
+ const auto start = Clock::now();
+ resolve_error = internal::AttachNativeResolution(easy, request.url, request.timeout_ms, cancel,
+ &resolve_entries);
+#if PLAYDEN_PLATFORM_PS5
+ transfer.response.timing.resolve_ms = static_cast<std::uint32_t>(
+ std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count());
+#else
+ (void)start;
+#endif
+ }
if (resolve_error != internal::NativeResolveError::kNone) {
canceled = resolve_error == internal::NativeResolveError::kCanceled;
result = canceled ? CURLE_ABORTED_BY_CALLBACK
@@ -344,6 +353,21 @@ class HttpClient::Impl {
if (result == CURLE_OK && transfer.response.status_code == 0) result = CURLE_WEIRD_SERVER_REPLY;
cleanup:
+ if (easy) {
+ curl_off_t lookup = 0, connect = 0, tls = 0, first = 0;
+ long connections = 0;
+ curl_easy_getinfo(easy, CURLINFO_NAMELOOKUP_TIME_T, &lookup);
+ curl_easy_getinfo(easy, CURLINFO_CONNECT_TIME_T, &connect);
+ curl_easy_getinfo(easy, CURLINFO_APPCONNECT_TIME_T, &tls);
+ curl_easy_getinfo(easy, CURLINFO_STARTTRANSFER_TIME_T, &first);
+ curl_easy_getinfo(easy, CURLINFO_NUM_CONNECTS, &connections);
+ const auto ms = [](curl_off_t us) { return static_cast<std::uint32_t>(std::max<curl_off_t>(0, us) / 1000); };
+ transfer.response.timing.connect_ms = ms(connect - lookup);
+ transfer.response.timing.tls_ms = ms(tls - connect);
+ transfer.response.timing.first_byte_ms = ms(first);
+ transfer.response.timing.new_connections = static_cast<std::uint32_t>(std::max(0L, connections));
+ }
+ transfer.response.timing.body_bytes = transfer.response.body.size();
if (added) curl_multi_remove_handle(multi, easy);
curl_slist_free_all(resolve_entries);
curl_slist_free_all(request_headers);
@@ -371,8 +395,12 @@ HttpClient::HttpClient(HttpClient&&) noexcept = default;
HttpClient& HttpClient::operator=(HttpClient&&) noexcept = default;
HttpResponse HttpClient::Perform(const HttpRequest& request, const std::atomic<bool>& cancel) {
- if (!impl_) return {HttpError::kInitializationFailed, 0, {}, {}};
- return impl_->Perform(request, cancel);
+ const auto start = std::chrono::steady_clock::now();
+ auto response = impl_ ? impl_->Perform(request, cancel)
+ : HttpResponse{HttpError::kInitializationFailed, 0, {}, {}};
+ response.timing.total_ms = static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - start).count());
+ return response;
}
} // namespace playden::steam
diff --git a/src/steam/backend/http_client.h b/src/steam/backend/http_client.h
index f682338..3fd18ea 100644
--- a/src/steam/backend/http_client.h
+++ b/src/steam/backend/http_client.h
@@ -46,6 +46,16 @@ struct HttpRequest {
std::size_t max_response_bytes = 1024 * 1024;
};
+struct HttpTiming {
+ std::uint32_t resolve_ms = 0;
+ std::uint32_t connect_ms = 0;
+ std::uint32_t tls_ms = 0;
+ std::uint32_t first_byte_ms = 0;
+ std::uint32_t total_ms = 0;
+ std::uint32_t new_connections = 0;
+ std::uint64_t body_bytes = 0;
+};
+
struct HttpResponse {
HttpError error = HttpError::kNone;
long status_code = 0;
@@ -54,6 +64,8 @@ struct HttpResponse {
std::vector<std::pair<std::string, std::string>> headers;
std::vector<std::uint8_t> body;
+ HttpTiming timing; // Retained when a failed response discards its payload.
+
bool ok() const { return error == HttpError::kNone; }
};
diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cpp
index 7199710..4a0c6dc 100644
--- a/src/steam/backend/steam_install_runner.cpp
+++ b/src/steam/backend/steam_install_runner.cpp
@@ -4,9 +4,47 @@
#include "steam/backend/app_info.h"
#include <set>
+#include <charconv>
namespace playden::steam {
+std::string FormatInstallStats(const char* phase, const InstallStats& stats) {
+ std::string detail;
+ const auto add = [&](const char* key, std::uint64_t value) {
+ if (!detail.empty()) detail += ' ';
+ detail += key; detail += '='; detail += std::to_string(value);
+ };
+ add("files_total", stats.files_total); add("download_total", stats.download_total);
+ if (std::string(phase) == "shape") {
+ add("chunks_pending", stats.chunks_pending); add("files_pending", stats.files_pending);
+ add("bytes_pending", stats.bytes_pending);
+ return detail;
+ }
+ add("dl_ms", stats.download_ms); add("cb", stats.compressed_bytes); add("ob", stats.original_bytes);
+ add("ch", stats.chunks_done); add("sk", stats.chunks_skipped);
+ add("fc", stats.files_created); add("dc", stats.folders_created);
+ add("fetch", stats.fetch_ms); add("proc", stats.process_ms); add("create", stats.create_ms);
+ add("write", stats.write_ms); add("jrnl", stats.journal_ms); add("back", stats.backoff_ms);
+ add("req", stats.requests); add("conn", stats.new_connections);
+ add("res", stats.resolve_ms); add("tcp", stats.connect_ms); add("tls", stats.tls_ms); add("ttfb", stats.first_byte_ms);
+ add("retry", stats.chunk_retries); add("bad", stats.corrupt_retries);
+ add("slots", stats.slots); add("reuse", stats.reuse);
+ add("access", stats.access_ms); add("servers", stats.servers_ms); add("manifest", stats.manifests_ms); add("prep", stats.prepare_ms);
+ add("http_ms", stats.total_ms); add("http_b", stats.bytes); add("fail", stats.failures);
+ return detail;
+}
+
+bool SteamInstallRunner::Remove(const std::string& root) {
+ const bool ok = RemoveManagedInstall(root);
+ const auto slash = root.rfind('/');
+ const auto name = root.substr(slash == std::string::npos ? 0 : slash + 1);
+ GameId app = 0;
+ const auto parsed = std::from_chars(name.data(), name.data() + name.size(), app);
+ if (log_ && app != 0 && parsed.ec == std::errc{} && parsed.ptr == name.data() + name.size())
+ log_(app, "install-removal", "done", ok ? "ok=1" : "ok=0");
+ return ok;
+}
+
const char* InstallFailureText(InstallError error) {
switch (error) {
case InstallError::kNone: return "";
diff --git a/src/steam/backend/steam_install_runner.h b/src/steam/backend/steam_install_runner.h
index d68af28..ecd903a 100644
--- a/src/steam/backend/steam_install_runner.h
+++ b/src/steam/backend/steam_install_runner.h
@@ -7,6 +7,8 @@
namespace playden::steam {
+std::string FormatInstallStats(const char* phase, const InstallStats& stats);
+
// Installs a Steam game: PICS app info for the depot selection (Windows, English, public
// branch), then the resumable depot installer.
class SteamInstallRunner final : public InstallRunner {
@@ -15,12 +17,18 @@ class SteamInstallRunner final : public InstallRunner {
Result Install(const StoredSession& session, GameId id, const std::string& root,
const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t)>& progress) override;
- bool Remove(const std::string& root) override { return RemoveManagedInstall(root); }
+ bool Remove(const std::string& root) override;
// Optional sanitized log: the Steam app ID, step, error category and a short detail; never
// tokens or account identifiers. Called on the install worker.
using LogFn = std::function<void(GameId app, const char* step, const char* category, const char* detail)>;
void SetLog(LogFn log) {
log_ = log;
+ installer_.SetStats([this, log](const char* phase, const InstallStats& stats) {
+ if (log) {
+ const auto detail = FormatInstallStats(phase, stats);
+ log(current_app_.load(), "stats", phase, detail.c_str());
+ }
+ });
installer_.SetTrace([this, log](const char* step) { if (log) log(current_app_.load(), "trace", step, ""); });
}
diff --git a/src/steam/install_service.cpp b/src/steam/install_service.cpp
index f5e82f7..ab4f078 100644
--- a/src/steam/install_service.cpp
+++ b/src/steam/install_service.cpp
@@ -7,8 +7,39 @@
#include <charconv>
#include <cstdio>
#include <cstring>
+#include <string_view>
namespace playden::steam {
+std::vector<InstallRequest> ParseInstallRequests(const std::string& text) {
+ std::vector<InstallRequest> requests;
+ std::string_view remaining(text);
+ while (!remaining.empty() && requests.size() < 64) {
+ const auto newline = remaining.find('\n');
+ auto line = remaining.substr(0, newline);
+ remaining = newline == std::string_view::npos ? std::string_view{} : remaining.substr(newline + 1);
+ const auto token = [&line]() {
+ const auto first = line.find_first_not_of(" \t\r\v\f");
+ if (first == std::string_view::npos) { line = {}; return std::string_view{}; }
+ line.remove_prefix(first);
+ const auto end = line.find_first_of(" \t\r\v\f");
+ const auto word = line.substr(0, end);
+ line = end == std::string_view::npos ? std::string_view{} : line.substr(end);
+ return word;
+ };
+ auto id = token();
+ if (id.empty()) continue;
+ InstallRequest request;
+ if (id == "uninstall" || id == "cancel") {
+ request.action = id == "uninstall" ? InstallRequest::Action::kUninstall : InstallRequest::Action::kCancel;
+ id = token();
+ }
+ if (id.empty() || !token().empty()) continue;
+ const auto parsed = std::from_chars(id.data(), id.data() + id.size(), request.app);
+ if (parsed.ec != std::errc{} || parsed.ptr != id.data() + id.size() || request.app == 0) continue;
+ requests.push_back(request);
+ }
+ return requests;
+}
namespace {
constexpr const char* kRecord = ".playden-install.json";
diff --git a/src/steam/install_service.h b/src/steam/install_service.h
index e4662fe..fa8c564 100644
--- a/src/steam/install_service.h
+++ b/src/steam/install_service.h
@@ -17,6 +17,14 @@
namespace playden::steam {
+struct InstallRequest {
+ enum class Action { kInstall, kUninstall, kCancel };
+ Action action = Action::kInstall;
+ std::uint32_t app = 0;
+};
+// Development request file: strict app IDs, preserving command order, at most 64 commands.
+std::vector<InstallRequest> ParseInstallRequests(const std::string& text);
+
enum class InstallJobState { kQueued, kRunning, kPaused, kFailed };
// A place games can be installed: a folder on one drive. `available` means the folder exists and
diff --git a/tests/cdn_client_test.cpp b/tests/cdn_client_test.cpp
index c559e69..75435de 100644
--- a/tests/cdn_client_test.cpp
+++ b/tests/cdn_client_test.cpp
@@ -15,6 +15,24 @@ HttpResponse Body(long status, const std::string& text) {
return response;
}
+void TotalsIncludeFailedRequests() {
+ int calls = 0;
+ CdnClient client([&](const HttpRequest&, const std::atomic<bool>&) {
+ auto response = Body(++calls == 1 ? 200 : 503, "payload");
+ response.timing = {1, 2, 3, 4, 5, 1, 7};
+ return response;
+ });
+ std::atomic<bool> cancel{false};
+ std::vector<std::uint8_t> out;
+ ContentServer server{"h.example.invalid", "v.example.invalid", 1};
+ assert(client.Chunk(server, 1, std::string(40, 'a'), 1024, cancel, &out) == CdnError::kNone);
+ assert(client.Chunk(server, 1, std::string(40, 'a'), 1024, cancel, &out) == CdnError::kNetwork);
+ const auto& stats = client.stats();
+ assert(stats.requests == 2 && stats.failures == 1 && stats.bytes == 14);
+ assert(stats.resolve_ms == 2 && stats.connect_ms == 4 && stats.tls_ms == 6);
+ assert(stats.first_byte_ms == 8 && stats.total_ms == 10 && stats.new_connections == 2);
+}
+
void ServersFilterAndSortByLoad() {
std::vector<std::string> urls;
CdnClient client([&](const HttpRequest& request, const std::atomic<bool>&) {
@@ -61,6 +79,7 @@ void ManifestAndChunkUrlsAndErrors() {
} // namespace
int main() {
+ TotalsIncludeFailedRequests();
ServersFilterAndSortByLoad();
ManifestAndChunkUrlsAndErrors();
}
diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cpp
index 6748cef..7024d93 100644
--- a/tests/depot_installer_test.cpp
+++ b/tests/depot_installer_test.cpp
@@ -1,5 +1,6 @@
#include "steam/backend/depot_chunk.h"
#include "steam/backend/depot_installer.h"
+#include "steam/backend/steam_install_runner.h"
#include <mbedtls/aes.h>
#include <mbedtls/sha1.h>
@@ -194,6 +195,126 @@ World MakeWorld() {
return world;
}
+void CountsActualUsefulCompressedBytes(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ // HTTP permits the advertised size plus padding; a verified body can differ from metadata.
+ for (auto& [id, manifest] : world.manifests)
+ for (auto& file : manifest.files)
+ for (auto& chunk : file.chunks) chunk.compressed_size += 16;
+ auto hooks = world.Hooks();
+ const auto fetch = hooks.chunk;
+ std::uint64_t received = 0;
+ hooks.chunk = [&](const ContentServer& server, std::uint32_t depot, const std::string& sha,
+ std::size_t cap, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out) {
+ const auto result = fetch(server, depot, sha, cap, cancel, out);
+ if (result == CdnError::kNone) received += out->size();
+ return result;
+ };
+ 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};
+ const auto outcome = installer.Run({}, Target(root), cancel);
+ CHECK(outcome.error == InstallError::kNone);
+ CHECK(last.compressed_bytes == received);
+ CHECK(last.compressed_bytes + 3 * 16 == outcome.progress.download_total);
+}
+
+void StorageFailureEndsStats(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ std::filesystem::create_directories(root);
+ std::ofstream(root / "DATA") << "not a directory";
+ auto hooks = world.Hooks();
+ int ends = 0;
+ hooks.stats = [&](const char* phase, const InstallStats&) { if (std::string(phase) == "end") ++ends; };
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, Target(root), cancel).error == InstallError::kStorage);
+ CHECK(ends == 1);
+}
+
+void StatsAndRemovalLogs(const std::filesystem::path& root) {
+ InstallStats stats;
+ stats.download_ms = 300000; stats.compressed_bytes = 6000000000ull;
+ stats.files_total = 48000; stats.files_created = 48000;
+ const auto line = FormatInstallStats("end", stats);
+ CHECK(line.size() < 480);
+ CHECK(line.find("dl_ms=300000") != std::string::npos && line.find("reuse=0") != std::string::npos);
+ CmClient cm(CmClientHooks{}, cm::DeviceIdentity{});
+ CdnClient cdn([](const HttpRequest&, const std::atomic<bool>&) { return HttpResponse{}; });
+ SteamInstallRunner runner(cm, cdn);
+ int removals = 0;
+ GameId expected_app = 440;
+ const char* expected_ok = "ok=1";
+ runner.SetLog([&](GameId app, const char* step, const char* result, const char* detail) {
+ CHECK(app == expected_app && std::string(step) == "install-removal" && std::string(result) == "done");
+ CHECK(std::string(detail) == expected_ok);
+ ++removals;
+ });
+ CHECK(runner.Remove((root / "440").string()));
+ CHECK(removals == 1);
+ expected_app = 441; expected_ok = "ok=0";
+ std::filesystem::create_directories(root / "441");
+ std::ofstream(root / "441" / "keep.txt") << "unmanaged";
+ CHECK(!runner.Remove((root / "441").string()));
+ CHECK(removals == 2);
+ CHECK(!runner.Remove((root / "account-name").string() + "/.."));
+ CHECK(removals == 2); // no unvalidated path/name is logged
+}
+
+void RunStats(const std::filesystem::path& base) {
+ for (int mode = 0; mode < 3; ++mode) {
+ auto world = MakeWorld();
+ world.manifests[441].files.pop_back(); // two files and three merged chunks
+ world.manifests[442].files[0].path = "data/level.dat"; // stable folder count on either filesystem
+ std::atomic<bool> cancel{false};
+ world.cancel = &cancel;
+ if (mode == 1) world.cancel_after = 1;
+ if (mode == 2) world.corrupt = true;
+ auto hooks = world.Hooks();
+ InstallStats last;
+ int ends = 0, shapes = 0;
+ hooks.stats = [&](const char* phase, const InstallStats& stats) {
+ if (std::string(phase) == "end") { ++ends; last = stats; }
+ if (std::string(phase) == "shape") {
+ ++shapes;
+ if (ends == 0) CHECK(stats.chunks_pending == 3 && stats.files_pending == 2 && stats.files_total == 2);
+ }
+ };
+ CdnStats totals;
+ totals.requests = 100;
+ hooks.cdn_stats = [&] { return totals; };
+ auto fetch = hooks.chunk;
+ hooks.chunk = [&](const ContentServer& server, std::uint32_t depot, const std::string& sha,
+ std::size_t cap, const std::atomic<bool>& canceled, std::vector<std::uint8_t>* out) {
+ ++totals.requests;
+ if (mode == 0) usleep(600);
+ return fetch(server, depot, sha, cap, canceled, out);
+ };
+ DepotInstaller installer(hooks);
+ auto target = Target(base / std::to_string(mode));
+ const auto outcome = installer.Run({}, target, cancel);
+ CHECK(ends == 1 && shapes == 1 && last.requests == static_cast<std::uint64_t>(world.chunk_calls));
+ CHECK(last.slots == 1 && last.reuse == 0);
+ if (mode == 0) {
+ CHECK(outcome.error == InstallError::kNone && last.chunks_done == 3 && last.files_created == 2);
+ CHECK(last.fetch_ms >= 1); // sub-millisecond chunks accumulate before conversion
+ CHECK(last.original_bytes == 39 && last.folders_created == 1);
+ CHECK(last.compressed_bytes == outcome.progress.download_total);
+ } else if (mode == 1) {
+ CHECK(outcome.error == InstallError::kCanceled && last.chunks_done == 1);
+ CHECK(last.original_bytes > 0 && last.compressed_bytes > 0);
+ cancel = false; world.cancel_after = -1;
+ installer.Run({}, target, cancel);
+ CHECK(ends == 2 && last.chunks_skipped == 1 && last.chunks_done == 2);
+ CHECK(last.files_created <= 1 && last.requests == static_cast<std::uint64_t>(world.chunk_calls - 2));
+ } else {
+ CHECK(outcome.error == InstallError::kCorrupt && last.chunks_done == 0);
+ CHECK(last.compressed_bytes == 0 && last.original_bytes == 0 && last.corrupt_retries == 5);
+ }
+ }
+}
+
void InstallsMergedDepotsAndWritesRecord(const std::filesystem::path& root) {
auto world = MakeWorld();
DepotInstaller installer(world.Hooks());
@@ -312,6 +433,10 @@ void RemovesOnlyManagedFolders(const std::filesystem::path& base) {
int main() {
const auto base = std::filesystem::temp_directory_path() / ("playden-installer-test-" + std::to_string(::getpid()));
std::filesystem::remove_all(base);
+ CountsActualUsefulCompressedBytes(base / "actual-compressed");
+ StorageFailureEndsStats(base / "storage-stats");
+ StatsAndRemovalLogs(base / "removal");
+ RunStats(base / "stats");
InstallsMergedDepotsAndWritesRecord(base / "install");
ResumesWithoutRefetchingFinishedChunks(base / "resume");
RefusesWhenSpaceIsShort(base / "space");
diff --git a/tests/http_client_test.cpp b/tests/http_client_test.cpp
index 15fc300..9aac3b0 100644
--- a/tests/http_client_test.cpp
+++ b/tests/http_client_test.cpp
@@ -43,6 +43,9 @@ int main(int argc, char** argv) {
Check(response.ok(), "verified GET should succeed");
Check(response.status_code == 200, "GET should retain HTTP status");
Check(Text(response.body) == "fixture-ok", "GET should retain response bytes");
+ Check(response.timing.new_connections == 1, "GET should measure a fresh connection");
+ Check(response.timing.resolve_ms == 0, "host has no native resolution phase");
+ Check(response.timing.total_ms > 0 && response.timing.body_bytes == 10, "GET should measure time and bytes");
bool found_result = false;
for (const auto& header : response.headers)
found_result |= header.first == "X-ErEsUlT" && header.second == "42";
@@ -62,6 +65,7 @@ int main(int argc, char** argv) {
timeout.timeout_ms = 100;
auto started = std::chrono::steady_clock::now();
response = client.Perform(timeout, cancel);
+ Check(response.timing.total_ms > 0, "failure should preserve timing");
Check(response.error == HttpError::kTimeout, "slow response should time out");
Check(std::chrono::steady_clock::now() - started < std::chrono::milliseconds(500),
"timeout should be enforced near its deadline");
diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cpp
index 25b9208..950d619 100644
--- a/tests/install_service_test.cpp
+++ b/tests/install_service_test.cpp
@@ -95,6 +95,17 @@ bool Installed(const InstallSnapshot& snapshot, GameId id) {
} // namespace
int main() {
+ const auto requests = ParseInstallRequests("uninstall 439490\n439490\ncancel 108600\n108600\n");
+ CHECK(requests.size() == 4);
+ CHECK(requests[0].action == InstallRequest::Action::kUninstall && requests[0].app == 439490);
+ CHECK(requests[1].action == InstallRequest::Action::kInstall && requests[1].app == 439490);
+ CHECK(requests[2].action == InstallRequest::Action::kCancel && requests[2].app == 108600);
+ CHECK(requests[3].action == InstallRequest::Action::kInstall && requests[3].app == 108600);
+ CHECK(ParseInstallRequests("0\n-1\n4294967296\n12x\nuninstall 12 extra\nunknown 12\n").empty());
+ CHECK(ParseInstallRequests(" cancel 42 \r\n")[0].app == 42);
+ std::string many_requests;
+ for (int app = 1; app <= 70; ++app) many_requests += std::to_string(app) + "\n";
+ CHECK(ParseInstallRequests(many_requests).size() == 64);
{
// Installed records must survive removal of the title's /app0 view.
const auto stable = std::filesystem::temp_directory_path() /
diff --git a/tests/test_download_speed_report.py b/tests/test_download_speed_report.py
new file mode 100644
index 0000000..8db117e
--- /dev/null
+++ b/tests/test_download_speed_report.py
@@ -0,0 +1,100 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+import importlib.util
+from pathlib import Path
+import unittest
+from unittest.mock import MagicMock, patch
+import ftplib
+
+spec = importlib.util.spec_from_file_location("download_speed_report", Path(__file__).resolve().parents[1] / "tools/download_speed_report.py")
+report = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(report)
+
+
+class DownloadSpeedReportTest(unittest.TestCase):
+ def test_completed_run_uses_end_and_filters(self):
+ text = """2026-10-12T10:00:00Z app=440 step=trace result=access detail=
+2026-10-12T10:00:01Z app=440 step=stats result=shape detail=files_total=2 download_total=4000000 chunks_pending=3 files_pending=2 bytes_pending=4000000
+2026-10-12T10:00:03Z app=440 step=stats result=end detail=dl_ms=2000 cb=4000000 fc=2 fetch=1000 proc=200 create=400 write=200 jrnl=100 back=0 req=3 conn=3 retry=0 slots=1 reuse=0
+2026-10-12T10:00:03Z app=440 step=install result=none detail=
+"""
+ rows = report.parse_runs(text)
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["outcome"], "none")
+ self.assertEqual(rows[0]["files_total"], 2)
+ self.assertEqual(rows[0]["mb_s"], 2.0)
+ self.assertEqual(rows[0]["fetch_pct"], 50.0)
+ self.assertEqual(rows[0]["creation_floor_ms"], 45.0)
+ self.assertEqual(report.filter_runs(rows, app=42), [])
+ self.assertEqual(report.filter_runs(rows, since="2026-10-12T10:01:00Z"), [])
+
+ def test_force_closed_progress_stays_separate_from_cancellation(self):
+ rows = report.parse_runs("""2026-10-12T10:00:00Z app=1 step=trace result=access detail=
+2026-10-12T10:05:00Z app=1 step=stats result=progress detail=dl_ms=300000 cb=600000000 fetch=250000 fc=4
+2026-10-12T10:06:00Z app=1 step=trace result=access detail=
+2026-10-12T10:06:01Z app=1 step=stats result=end detail=dl_ms=1 cb=0 fc=0
+2026-10-12T10:06:01Z app=1 step=install result=canceled detail=
+""")
+ self.assertEqual(len(rows), 2)
+ self.assertEqual(rows[0]["outcome"], "interrupted")
+ self.assertEqual(rows[0]["download_ms"], 300000)
+ self.assertEqual(rows[0]["mb_s"], 2.0)
+ self.assertEqual(rows[1]["outcome"], "canceled")
+
+ def test_pre_access_failures_and_interleaved_apps(self):
+ rows = report.parse_runs("""2026-10-12T10:00:00Z app=1 step=entitlements result=rejected detail=
+2026-10-12T10:00:01Z app=2 step=app_info result=network detail=
+2026-10-12T10:00:02Z app=3 step=trace result=access detail=
+2026-10-12T10:00:03Z app=4 step=trace result=access detail=
+2026-10-12T10:00:04Z app=3 step=install result=network detail=
+2026-10-12T10:00:05Z app=4 step=install result=none detail=
+""")
+ self.assertEqual([r["outcome"] for r in rows], ["entitlements:rejected", "app_info:network", "network", "none"])
+ self.assertIsNone(rows[0]["mb_s"])
+
+ def test_no_windows_depots_is_a_failed_prerequisite_run(self):
+ rows = report.parse_runs(
+ "2026-10-12T10:00:00Z app=440 step=depots result=none detail=no Windows depots\n")
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["app"], 440)
+ self.assertEqual(rows[0]["outcome"], "depots:none")
+ self.assertIsNone(rows[0]["download_ms"])
+ self.assertIsNone(rows[0]["compressed_bytes"])
+ self.assertIsNone(rows[0]["mb_s"])
+ self.assertEqual(report.parse_runs(
+ "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_missing_rotated_log_is_not_requested(self):
+ ftp = MagicMock()
+ ftp.__enter__.return_value = ftp
+ ftp.retrlines.side_effect = lambda command, callback: callback(
+ "-rw-r--r-- 1 root root 10 Oct 12 10:00 install.log")
+ ftp.retrbinary.side_effect = lambda command, callback, size: callback(b"a log\n")
+ with patch.object(report.ftplib, "FTP", return_value=ftp):
+ self.assertEqual(report.fetch_logs("console.invalid", 2120), "a log\n")
+ self.assertEqual(ftp.retrbinary.call_count, 1)
+ self.assertIn("install.log", ftp.retrbinary.call_args.args[0])
+ self.assertNotIn("install.log.1", ftp.retrbinary.call_args.args[0])
+
+ def test_present_log_transfer_failure_is_reported(self):
+ ftp = MagicMock()
+ ftp.__enter__.return_value = ftp
+ ftp.retrlines.side_effect = lambda command, callback: callback(
+ "-rw-r--r-- 1 root root 10 Oct 12 10:00 install.log")
+ ftp.retrbinary.side_effect = ftplib.error_temp("451 transfer failed")
+ with patch.object(report.ftplib, "FTP", return_value=ftp):
+ with self.assertRaises(ftplib.error_temp):
+ report.fetch_logs("console.invalid", 2120)
+
+ def test_rotation_partial_and_zero_duration_do_not_invent_measurements(self):
+ rows = report.parse_runs("""2026-10-12T10:00:00Z app=1 step=stats result=progress detail=dl_ms=0 cb=0 fc=0 req=2 conn=2
+2026-10-12T10:00:01Z app=1 step=install result=storage detail=
+""")
+ self.assertEqual(rows[0]["outcome"], "storage")
+ self.assertIsNone(rows[0]["mb_s"])
+ self.assertIsNone(rows[0]["files_total"])
+ self.assertEqual(rows[0]["sample"], "progress")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/download_speed_report.py b/tools/download_speed_report.py
new file mode 100644
index 0000000..904c200
--- /dev/null
+++ b/tools/download_speed_report.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-or-later
+"""Report Steam install measurements from the PS5's two rotating install logs.
+
+Install bytes count verified chunks written this run; HTTP bytes include retries and
+preparation requests. DNS/TCP/TLS/TTFB cover all CDN requests in the run. TTFB is
+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.
+
+Example: download_speed_report.py --host 192.168.1.50 --app 439490 \
+ --since 2026-10-12T10:00:00Z --csv results/baseline.csv
+"""
+import argparse
+import csv
+from datetime import datetime, timezone
+import ftplib
+import io
+import os
+from pathlib import Path
+import re
+import sys
+
+LOGS = "/data/homebrew/FAKE77031/logs"
+LINE = re.compile(r"^(\S+) app=(\d+) step=(\S+) result=(\S+) detail=(.*)$")
+METRIC = re.compile(r"\b([a-z_]+)=(\d+)\b")
+STAGES = ("fetch", "proc", "create", "write", "jrnl", "back")
+COLUMNS = ("app", "start", "outcome", "sample", "files_total", "compressed_bytes", "download_ms", "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",
+ "download_total", "chunks_pending", "files_pending", "bytes_pending")
+
+
+def timestamp(value):
+ """An ISO timestamp (UTC when unspecified), or Unix seconds."""
+ try:
+ return datetime.fromtimestamp(float(value), timezone.utc)
+ except ValueError:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed
+
+
+def parse_runs(text):
+ active, runs = {}, []
+
+ def begin(app, start):
+ run = {"app": app, "start": start, "outcome": "interrupted", "sample": "missing", "metrics": {}}
+ active[app] = run
+ runs.append(run)
+ return run
+
+ for line in text.splitlines():
+ match = LINE.match(line)
+ if not match:
+ continue
+ start, app, step, result, detail = match.groups()
+ app = int(app)
+ if step == "trace" and result == "access":
+ begin(app, start)
+ elif step == "stats" and result in ("shape", "progress", "end"):
+ run = active.get(app) or begin(app, start)
+ run["metrics"].update({key: int(value) for key, value in METRIC.findall(detail)})
+ if result != "shape":
+ run["sample"] = result
+ elif step == "install":
+ run = active.pop(app, None) or begin(app, start)
+ run["outcome"] = result
+ active.pop(app, None)
+ elif step == "depots" or (step in ("app_info", "entitlements") and result != "none"):
+ # Depots logs "none" for missing Windows content; it is a prerequisite failure.
+ # These errors occur before access; preserve failed precondition runs too.
+ run = begin(app, start)
+ run["outcome"] = step + ":" + result
+ active.pop(app, None)
+
+ rows = []
+ for run in runs:
+ metrics = run.pop("metrics")
+ row = {column: None for column in COLUMNS}
+ row.update(run)
+ row.update({key: value for key, value in metrics.items() if key in COLUMNS})
+ row["compressed_bytes"] = metrics.get("cb")
+ row["original_bytes"] = metrics.get("ob")
+ row["download_ms"] = metrics.get("dl_ms")
+ duration = row["download_ms"]
+ row["mb_s"] = metrics["cb"] / duration / 1000 if duration and "cb" in metrics else None
+ for stage in STAGES:
+ row[stage + "_pct"] = 100 * metrics[stage] / duration if duration and stage in metrics else None
+ row["creation_floor_ms"] = metrics["fc"] * 22.5 if "fc" in metrics else None
+ rows.append(row)
+ return rows
+
+
+def filter_runs(rows, since=None, app=None):
+ return [row for row in rows if (app is None or row["app"] == app)
+ and (since is None or timestamp(row["start"]) >= timestamp(since))]
+
+
+def fetch_logs(host, port):
+ parts = []
+ with ftplib.FTP() as ftp:
+ ftp.connect(host, port, timeout=15)
+ ftp.login()
+ # List first: zftpd answers 451, rather than 550, for an absent rotated log.
+ listing = []
+ ftp.retrlines("LIST " + LOGS, listing.append)
+ names = {line.split(None, 8)[8] for line in listing
+ if line.startswith("-") and len(line.split(None, 8)) == 9}
+ for name in ("install.log.1", "install.log"):
+ if name not in names:
+ continue
+ buffer = io.BytesIO()
+ try:
+ ftp.retrbinary("RETR " + LOGS + "/" + name, buffer.write, 1 << 20)
+ except ftplib.error_perm as error:
+ if str(error).startswith("550"):
+ continue
+ raise
+ parts.append(buffer.getvalue().decode("utf-8", errors="replace"))
+ if not parts:
+ raise ValueError("No install logs available")
+ return "\n".join(parts)
+
+
+def write_csv(rows, output):
+ writer = csv.DictWriter(output, fieldnames=COLUMNS)
+ writer.writeheader()
+ writer.writerows(rows)
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--host", default=os.environ.get("PLAYDEN_PS5_HOST"))
+ parser.add_argument("--port", type=int, default=2120)
+ parser.add_argument("--since", help="ISO UTC timestamp or Unix seconds")
+ parser.add_argument("--app", type=int)
+ parser.add_argument("--csv", nargs="?", const="-", help="CSV file, or stdout when no path is given")
+ parser.add_argument("--log", action="append", type=Path, help="Local log instead of FTP, oldest first")
+ parser.add_argument("--raw", type=Path, help="Save the fetched raw log lines")
+ args = parser.parse_args(argv)
+ if not args.log and not args.host:
+ parser.error("give --host / PLAYDEN_PS5_HOST, or --log")
+ try:
+ text = "\n".join(path.read_text() for path in args.log) if args.log else fetch_logs(args.host, args.port)
+ rows = filter_runs(parse_runs(text), args.since, args.app)
+ if args.raw:
+ args.raw.write_text(text)
+ if args.csv:
+ if args.csv == "-":
+ write_csv(rows, sys.stdout)
+ else:
+ with Path(args.csv).open("w", newline="") as output:
+ write_csv(rows, output)
+ else:
+ columns = COLUMNS[:21]
+ print("\t".join(columns))
+ for row in rows:
+ print("\t".join("-" if row[column] is None else
+ f"{row[column]:.2f}" if isinstance(row[column], float) else str(row[column])
+ for column in columns))
+ print("Stage shares use download_ms. CDN timings include preparation; TTFB overlaps TCP/TLS. "
+ "Creation floor is fc × 22.5 ms, a comparison estimate.", file=sys.stderr)
+ except (OSError, ValueError, ftplib.Error) as error:
+ print(f"download speed report failed: {type(error).__name__}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())