Play your Steam library's Windows games on a jailbroken PS5.
C++
Keep cached covers when a cover download fails
Leonardo Lobato7379b4d48dc6
diff --git a/src/homebrew/artwork_backend.cpp b/src/homebrew/artwork_backend.cppindex 9cf392d..38d4ea0 100644--- a/src/homebrew/artwork_backend.cpp+++ b/src/homebrew/artwork_backend.cpp@@ -9,6 +9,7 @@#include <cstddef>#include <cstdlib>#include <cstdint>+#include <cerrno>#include <ctime>#include <filesystem>#include <limits>@@ -219,6 +220,56 @@ struct HttpArtworkBackend::Cache {}return false;}++ // The cached file's bytes, and whether it is younger than the TTL.+ std::optional<std::vector<std::uint8_t>> Read(const std::string& path, const std::string& name, bool* fresh) {+ *fresh = false;+ if (!EnsureDir(path)) return std::nullopt;+ struct stat st{};+ if (!dir->InspectChild(name, &st) || !S_ISREG(st.st_mode) || st.st_size <= 0 ||+ static_cast<std::size_t>(st.st_size) > kMaxArtworkTransferBytes) return std::nullopt;+ const int fd = dir->OpenRegularFile(name);+ if (fd < 0) return std::nullopt;+ std::vector<std::uint8_t> bytes(static_cast<std::size_t>(st.st_size));+ std::size_t offset = 0;+ while (offset < bytes.size()) {+ const auto count = ::read(fd, bytes.data() + offset, bytes.size() - offset);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) break;+ offset += static_cast<std::size_t>(count);+ }+ ::close(fd);+ if (offset != bytes.size()) return std::nullopt;+ const std::time_t now = std::time(nullptr);+ *fresh = now < st.st_mtime || now - st.st_mtime < kArtworkCacheTtlSeconds;+ return bytes;+ }++ // Writes a unique temporary file and renames it over the cached one. The title-icon builder+ // has its own backend, so two writers can save the same file at once.+ void Save(const std::string& path, const std::string& name, const std::vector<std::uint8_t>& bytes) {+ if (bytes.empty() || bytes.size() > kMaxArtworkTransferBytes || !EnsureDir(path)) return;+ static std::atomic<std::uint64_t> sequence{0};+ const std::string temp_name = "." + name + "." + std::to_string(::getpid()) + "." ++ std::to_string(sequence.fetch_add(1)) + ".tmp";+ const int fd = dir->CreateExclusiveFile(temp_name, 0600);+ if (fd < 0) return;+ std::size_t offset = 0;+ bool written = true;+ while (offset < bytes.size()) {+ const auto count = ::write(fd, bytes.data() + offset, bytes.size() - offset);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) { written = false; break; }+ offset += static_cast<std::size_t>(count);+ }+ const bool synced = written && ::fsync(fd) == 0;+ const bool closed = ::close(fd) == 0;+ if (synced && closed && dir->RenameChild(temp_name, *dir, name, /*replace_existing=*/true)) {+ dir->Sync();+ return;+ }+ dir->RemoveRegularFile(temp_name);+ }};std::optional<ArtworkImage> artwork_internal::DecodeArtworkWithAllocationBudget(@@ -264,9 +315,16 @@ std::optional<ArtworkImage> DecodeArtwork(}HttpArtworkBackend::HttpArtworkBackend(std::string ca_bundle, std::string cache_dir)- : ca_bundle_(std::move(ca_bundle)),- cache_dir_(std::move(cache_dir)),- http_(std::make_unique<steam::HttpClient>(ca_bundle_)),+ : cache_dir_(std::move(cache_dir)),+ http_(std::make_unique<steam::HttpClient>(std::move(ca_bundle))),+ perform_([client = http_.get()](const steam::HttpRequest& request, const std::atomic<bool>& cancel) {+ return client->Perform(request, cancel);+ }),+ cache_(cache_dir_.empty() ? nullptr : std::make_unique<Cache>()) {}++HttpArtworkBackend::HttpArtworkBackend(Perform perform, std::string cache_dir)+ : cache_dir_(std::move(cache_dir)),+ perform_(std::move(perform)),cache_(cache_dir_.empty() ? nullptr : std::make_unique<Cache>()) {}HttpArtworkBackend::~HttpArtworkBackend() = default;@@ -275,146 +333,53 @@ std::optional<ArtworkImage> HttpArtworkBackend::Load(const ArtworkKey& key, const std::atomic<bool>& cancel) {if (!CanonicalKey(key) || cancel.load(std::memory_order_acquire))return std::nullopt;- if (!http_) http_ = std::make_unique<steam::HttpClient>(ca_bundle_);- const std::string file_name = CacheFileName(key);- bool cache_expired = false;-- // 1. Check persistent on-disk cache under ManagedDirectory- if (!file_name.empty() && cache_) {+ const bool cover = key.source.find("library_600x900.jpg") != std::string::npos;+ // A wide image in the cover slot is the header.jpg fallback: frame it as a portrait card.+ const auto framed = [cover](std::optional<ArtworkImage> image) {+ if (image && cover && image->width > image->height) image = FrameToPortrait(*image);+ return image;+ };+ const std::string file_name = cache_ ? CacheFileName(key) : std::string{};++ // A fresh cached copy is used without asking the CDN.+ std::optional<std::vector<std::uint8_t>> cached;+ bool fresh = false;+ if (!file_name.empty()) {std::lock_guard<std::mutex> lock(cache_->mutex);- if (cache_->EnsureDir(cache_dir_)) {- struct stat st{};- if (cache_->dir->InspectChild(file_name, &st) && S_ISREG(st.st_mode) &&- st.st_size > 0 && static_cast<std::size_t>(st.st_size) <= kMaxArtworkTransferBytes) {- const std::time_t now = std::time(nullptr);- cache_expired = (now >= st.st_mtime && (now - st.st_mtime) >= kArtworkCacheTtlSeconds);- if (!cache_expired) {- const int fd = cache_->dir->OpenRegularFile(file_name);- if (fd >= 0) {- std::vector<std::uint8_t> bytes(static_cast<std::size_t>(st.st_size));- std::size_t offset = 0;- bool read_ok = true;- while (offset < bytes.size()) {- const auto count = read(fd, bytes.data() + offset, bytes.size() - offset);- if (count < 0 && errno == EINTR) continue;- if (count <= 0) { read_ok = false; break; }- offset += static_cast<std::size_t>(count);- }- close(fd);- if (read_ok && offset == bytes.size()) {- auto image = DecodeArtwork(bytes);- if (image) {- if (key.source.find("library_600x900.jpg") != std::string::npos &&- image->width > image->height) {- image = FrameToPortrait(*image);- }- return image;- }- }- }- }- }- }+ cached = cache_->Read(cache_dir_, file_name, &fresh);}-+ if (cached && fresh)+ if (auto image = DecodeArtwork(*cached)) return framed(std::move(image));if (cancel.load(std::memory_order_acquire)) return std::nullopt;- // 2. Fetch from Steam CDNsteam::HttpRequest request;request.method = steam::HttpMethod::kGet;request.url = key.source;request.timeout_ms = kArtworkTimeoutMs;request.max_response_bytes = kMaxArtworkTransferBytes;- auto response = http_->Perform(request, cancel);-- // If library_600x900.jpg returned 404, fallback to header.jpg (standard Steam banner)- if ((!response.ok() || response.status_code != 200) &&- key.source.find("library_600x900.jpg") != std::string::npos &&- !cancel.load(std::memory_order_acquire)) {- const std::string base = "https://cdn.cloudflare.steamstatic.com/steam/apps/" +- ToKey(key.game_id) + "/";- steam::HttpRequest fallback_req = request;- fallback_req.url = base + "header.jpg";- auto fallback_resp = http_->Perform(fallback_req, cancel);- if (fallback_resp.ok() && fallback_resp.status_code == 200) {- response = std::move(fallback_resp);- }- }+ auto response = perform_(request, cancel);- if (!response.ok() || response.status_code != 200) {- // Offline / network failure fallback to existing cached image if expired- if (cache_expired && !file_name.empty() && cache_) {- std::lock_guard<std::mutex> lock(cache_->mutex);- if (cache_->EnsureDir(cache_dir_)) {- struct stat st{};- if (cache_->dir->InspectChild(file_name, &st) && st.st_size > 0 &&- static_cast<std::size_t>(st.st_size) <= kMaxArtworkTransferBytes) {- const int fd = cache_->dir->OpenRegularFile(file_name);- if (fd >= 0) {- std::vector<std::uint8_t> bytes(static_cast<std::size_t>(st.st_size));- std::size_t offset = 0;- bool read_ok = true;- while (offset < bytes.size()) {- const auto count = read(fd, bytes.data() + offset, bytes.size() - offset);- if (count < 0 && errno == EINTR) continue;- if (count <= 0) { read_ok = false; break; }- offset += static_cast<std::size_t>(count);- }- close(fd);- if (read_ok && offset == bytes.size()) {- auto img = DecodeArtwork(bytes);- if (img) {- if (key.source.find("library_600x900.jpg") != std::string::npos &&- img->width > img->height) {- img = FrameToPortrait(*img);- }- return img;- }- }- }- }- }- }- return std::nullopt;+ // A game with no portrait cover (a real 404, not a timeout or a 5xx) uses its header.jpg banner.+ if (cover && response.ok() && response.status_code == 404 && !cancel.load(std::memory_order_acquire)) {+ request.url = "https://cdn.cloudflare.steamstatic.com/steam/apps/" + ToKey(key.game_id) + "/header.jpg";+ response = perform_(request, cancel);}- // 3. Atomically write downloaded cover to cache via ManagedDirectory- if (!file_name.empty() && cache_ && !response.body.empty() &&- response.body.size() <= kMaxArtworkTransferBytes) {- std::lock_guard<std::mutex> lock(cache_->mutex);- if (cache_->EnsureDir(cache_dir_)) {- static std::atomic<std::uint64_t> sequence{0};- const std::string temp_name = "." + file_name + "." + std::to_string(getpid()) + "." +- std::to_string(sequence.fetch_add(1)) + ".tmp";- const int fd = cache_->dir->CreateExclusiveFile(temp_name, 0600);- if (fd >= 0) {- std::size_t offset = 0;- bool write_ok = true;- while (offset < response.body.size()) {- const auto count = write(fd, response.body.data() + offset, response.body.size() - offset);- if (count < 0 && errno == EINTR) continue;- if (count <= 0) { write_ok = false; break; }- offset += static_cast<std::size_t>(count);- }- const bool synced = write_ok && (fsync(fd) == 0);- const bool closed = (close(fd) == 0);- if (synced && closed) {- cache_->dir->RenameChild(temp_name, *cache_->dir, file_name, /*replace_existing=*/true);- cache_->dir->Sync();- } else {- if (!closed) close(fd);- cache_->dir->RemoveRegularFile(temp_name);- }+ // Only bytes that decode replace the cached copy, so a bad response never overwrites a good cover.+ if (response.ok() && response.status_code == 200) {+ if (auto image = DecodeArtwork(response.body)) {+ if (!file_name.empty()) {+ std::lock_guard<std::mutex> lock(cache_->mutex);+ cache_->Save(cache_dir_, file_name, response.body);}+ return framed(std::move(image));}}- auto image = DecodeArtwork(response.body);- if (image && key.source.find("library_600x900.jpg") != std::string::npos && image->width > image->height) {- image = FrameToPortrait(*image);- }- return image;+ // Offline, or the CDN failed: an expired cached copy is better than none.+ if (cached && !fresh) return framed(DecodeArtwork(*cached));+ return std::nullopt;}} // namespace playden::homebrewdiff --git a/src/homebrew/artwork_backend.hpp b/src/homebrew/artwork_backend.hppindex f7f17a7..989c92d 100644--- a/src/homebrew/artwork_backend.hpp+++ b/src/homebrew/artwork_backend.hpp@@ -1,15 +1,14 @@#pragma once#include "homebrew/artwork.hpp"+#include "steam/backend/http_client.h"+#include <atomic>+#include <functional>#include <memory>#include <string>#include <vector>-namespace playden::steam {-class HttpClient;-}-namespace playden::homebrew {inline constexpr std::size_t kMaxArtworkTransferBytes = 4 * 1024 * 1024;@@ -29,7 +28,10 @@ std::optional<ArtworkImage> DecodeArtworkWithAllocationBudget(class HttpArtworkBackend final : public ArtworkBackend {public:+ using Perform = std::function<steam::HttpResponse(const steam::HttpRequest&, const std::atomic<bool>&)>;+explicit HttpArtworkBackend(std::string ca_bundle, std::string cache_dir = "");+ HttpArtworkBackend(Perform perform, std::string cache_dir); // tests~HttpArtworkBackend() override;HttpArtworkBackend(const HttpArtworkBackend&) = delete;HttpArtworkBackend& operator=(const HttpArtworkBackend&) = delete;@@ -41,9 +43,9 @@ class HttpArtworkBackend final : public ArtworkBackend {private:struct Cache;- std::string ca_bundle_;std::string cache_dir_;std::unique_ptr<steam::HttpClient> http_;+ Perform perform_;std::unique_ptr<Cache> cache_;};diff --git a/tests/homebrew_artwork_backend_test.cpp b/tests/homebrew_artwork_backend_test.cppindex d781476..03d5c58 100644--- a/tests/homebrew_artwork_backend_test.cpp+++ b/tests/homebrew_artwork_backend_test.cpp@@ -5,9 +5,12 @@#include <cassert>#include <cstdio>#include <cstdint>+#include <ctime>#include <filesystem>+#include <functional>#include <string>#include <vector>+#include <sys/time.h>#include <unistd.h>#include "steam_id.h"@@ -165,34 +168,172 @@ void InvalidHttpIdentityIsRejectedWithoutTransport() {assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/42/header.jpg"}, cancel));}-void ReadsFromManagedDiskCache() {- char pattern[] = "/tmp/playden-art-cache-XXXXXX";- if (::mkdtemp(pattern)) {- const std::filesystem::path root = std::filesystem::canonical(pattern);- const std::filesystem::path art_dir = root / "art";+// A private cache folder under a temporary root, removed on exit.+struct CacheFolder {+ std::filesystem::path root;+ std::filesystem::path art;+ CacheFolder() {+ char pattern[] = "/tmp/playden-art-cache-XXXXXX";+ assert(::mkdtemp(pattern));+ root = std::filesystem::canonical(pattern);+ art = root / "art";+ }+ ~CacheFolder() { std::filesystem::remove_all(root); }++ void Write(const std::string& name, const std::vector<std::uint8_t>& bytes, bool expired) {auto parent = playden::platform::ManagedDirectory::Open(root, playden::platform::DirectoryPolicy::kApprovedTree);assert(parent);auto managed = parent->OpenChild("art", playden::platform::DirectoryPolicy::kPrivate, true, 0700);assert(managed);-- const int fd = managed->CreateExclusiveFile("42_600x900.jpg", 0600);+ const int fd = managed->CreateExclusiveFile(name, 0600);assert(fd >= 0);- const auto jpeg = SmallJpeg();- assert(::write(fd, jpeg.data(), jpeg.size()) == static_cast<ssize_t>(jpeg.size()));- assert(::fsync(fd) == 0 && ::close(fd) == 0);- assert(managed->Sync());+ assert(::write(fd, bytes.data(), bytes.size()) == static_cast<ssize_t>(bytes.size()));+ assert(::close(fd) == 0);+ if (expired) {+ const std::time_t old = std::time(nullptr) - 15 * 24 * 3600;+ const struct timeval times[2] = {{old, 0}, {old, 0}};+ assert(::utimes((art / name).c_str(), times) == 0);+ }+ }- HttpArtworkBackend backend("unused-ca.pem", art_dir.string());- assert(backend.cache_dir() == art_dir.string());- std::atomic<bool> cancel{false};- const auto image = backend.Load(- {1, SteamId(42),- "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg"},- cancel);- assert(image && image->width > 0 && image->height > 0);+ std::vector<std::uint8_t> Read(const std::string& name) const {+ std::vector<std::uint8_t> bytes;+ FILE* file = std::fopen((art / name).c_str(), "rb");+ if (!file) return bytes;+ std::uint8_t buffer[4096];+ std::size_t count = 0;+ while ((count = std::fread(buffer, 1, sizeof(buffer), file)) > 0) bytes.insert(bytes.end(), buffer, buffer + count);+ std::fclose(file);+ return bytes;+ }+};++bool EndsWith(const std::string& url, const std::string& name) {+ return url.size() >= name.size() && url.compare(url.size() - name.size(), name.size(), name) == 0;+}++// Answers by URL and records every URL asked for.+struct FakeCdn {+ std::vector<std::string> urls;+ std::function<playden::steam::HttpResponse(const std::string&)> answer;+ HttpArtworkBackend::Perform perform() {+ return [this](const playden::steam::HttpRequest& request, const std::atomic<bool>&) {+ urls.push_back(request.url);+ return answer(request.url);+ };+ }+ bool asked(const std::string& name) const {+ for (const auto& url : urls)+ if (EndsWith(url, name)) return true;+ return false;+ }+};++playden::steam::HttpResponse Status(long code, std::vector<std::uint8_t> body = {}) {+ playden::steam::HttpResponse response;+ response.status_code = code;+ response.body = std::move(body);+ return response;+}++playden::steam::HttpResponse Timeout() {+ playden::steam::HttpResponse response;+ response.error = playden::steam::HttpError::kTimeout;+ return response;+}++const char kCover[] = "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg";++void FreshCacheIsUsedWithoutTheNetwork() {+ CacheFolder folder;+ folder.Write("42_600x900.jpg", SmallJpeg(), false);+ FakeCdn cdn;+ cdn.answer = [](const std::string&) { return Status(500); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(backend.Load({1, SteamId(42), kCover}, cancel));+ assert(cdn.urls.empty());+}++void MissingCoverFallsBackToFramedHeader() {+ CacheFolder folder;+ FakeCdn cdn;+ cdn.answer = [](const std::string& url) {+ return EndsWith(url, "/header.jpg") ? Status(200, SmallPng()) : Status(404);+ };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ const auto image = backend.Load({1, SteamId(42), kCover}, cancel);+ // The 2x1 banner is framed into a 600x900 portrait card.+ assert(image && image->width == 600 && image->height == 900);+ assert(image->rgba.size() == 600u * 900u * 4u);+ assert(cdn.asked("/library_600x900.jpg") && cdn.asked("/header.jpg"));+ assert(folder.Read("42_600x900.jpg") == SmallPng());++ // The next start reads the cached banner and frames it the same way.+ cdn.urls.clear();+ HttpArtworkBackend again(cdn.perform(), folder.art.string());+ const auto cached = again.Load({1, SteamId(42), kCover}, cancel);+ assert(cached && cached->width == 600 && cached->height == 900 && cdn.urls.empty());+}++void HeroHasNoHeaderFallback() {+ CacheFolder folder;+ FakeCdn cdn;+ cdn.answer = [](const std::string&) { return Status(404); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_hero.jpg"}, cancel));+ assert(cdn.urls.size() == 1 && !cdn.asked("/header.jpg"));+}- std::filesystem::remove_all(root);+void OtherFailuresKeepTheCachedCover() {+ for (const bool timeout : {false, true}) {+ CacheFolder folder;+ folder.Write("42_600x900.jpg", SmallJpeg(), true);+ FakeCdn cdn;+ cdn.answer = [timeout](const std::string&) { return timeout ? Timeout() : Status(503); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(backend.Load({1, SteamId(42), kCover}, cancel));+ // No banner is fetched on a failure that is not a 404, and the cached cover stays.+ assert(cdn.urls.size() == 1 && !cdn.asked("/header.jpg"));+ assert(folder.Read("42_600x900.jpg") == SmallJpeg());}++ // With nothing cached, a failure that is not a 404 still never fetches the banner.+ CacheFolder folder;+ FakeCdn cdn;+ cdn.answer = [](const std::string&) { return Timeout(); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(!backend.Load({1, SteamId(42), kCover}, cancel));+ assert(cdn.urls.size() == 1);+}++void BadDownloadKeepsTheCachedCover() {+ CacheFolder folder;+ folder.Write("42_600x900.jpg", SmallJpeg(), true);+ FakeCdn cdn;+ cdn.answer = [](const std::string&) { return Status(200, {1, 2, 3, 4}); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(backend.Load({1, SteamId(42), kCover}, cancel));+ assert(cdn.urls.size() == 1);+ assert(folder.Read("42_600x900.jpg") == SmallJpeg());+ for (const auto& entry : std::filesystem::directory_iterator(folder.art))+ assert(entry.path().filename() == "42_600x900.jpg"); // no temporary file left behind+}++void ExpiredCacheIsReplacedByANewCover() {+ CacheFolder folder;+ folder.Write("42_600x900.jpg", SmallJpeg(), true);+ FakeCdn cdn;+ cdn.answer = [](const std::string&) { return Status(200, SmallPng()); };+ HttpArtworkBackend backend(cdn.perform(), folder.art.string());+ std::atomic<bool> cancel{false};+ assert(backend.Load({1, SteamId(42), kCover}, cancel));+ assert(folder.Read("42_600x900.jpg") == SmallPng());}} // namespace@@ -216,5 +357,10 @@ int main(int argc, char** argv) {RejectsEmptyCorruptAndTransferOverflow();RejectsOversizedPngDimensionsBeforePixelAllocation();InvalidHttpIdentityIsRejectedWithoutTransport();- ReadsFromManagedDiskCache();+ FreshCacheIsUsedWithoutTheNetwork();+ MissingCoverFallsBackToFramedHeader();+ HeroHasNoHeaderFallback();+ OtherFailuresKeepTheCachedCover();+ BadDownloadKeepsTheCachedCover();+ ExpiredCacheIsReplacedByANewCover();}