Play your Steam library's Windows games on a jailbroken PS5.
C++
Keep imported games safe while copying into Playden
Leonardo Lobato98fe2d1891fd
diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 4ba40cd..c34bb51 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -1821,6 +1821,16 @@ RuntimeRelocationResult RuntimeHost::RunRelocate(Composition& c, const RuntimeRereturn result;};const auto app = std::to_string(request.runtime_number);+ // A queued preparation names the old folder and would move the game back there (RunPrepare's+ // drive move): it goes first, and the caller tries again later.+ if (request.runtime_number != 0) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (std::any_of(prepare_requests_.begin(), prepare_requests_.end(),+ [&](const auto& waiting) { return waiting.runtime_number == request.runtime_number; })) {+ Log("relocate app=" + app + " waits: a preparation is queued");+ return answer(Outcome::kBusy, "Finish setting up the game first.");+ }+ }std::optional<rt::RuntimeInstall> found;if (request.runtime_number != 0)for (const auto& record : c.repository.Snapshot())diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex e54c17e..c035aa7 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -345,7 +345,8 @@ struct RuntimeRelocation {std::string volume_id; // the install volume of `to`// The move itself, run on the worker under the game's publication lease once its title is// stopped (and at once for a game without a title): empty, or why not. It must be safe to run- // again after it succeeded (a restart in between). Empty: the files are at `to` already (a copy).+ // again after it succeeded (a restart in between). For a copy it copies again the files+ // changed since they were copied. Empty: the files are at `to` already.std::function<std::string()> move_files;};@@ -440,9 +441,10 @@ class RuntimeHost {// stopped, move_files runs, then one record write names the new folder (moved_from the old one)// and the game is published again at its revision. A publication that can't be verified falls// back to removing the old title, keeping its saves (prepare_again). A record already naming `to`- // (a restart after its write) only finishes the republish. Blocks the calling thread (never the- // worker's) until the worker answers; a request the worker hasn't started within `timeout` is- // dropped and answers kBusy. Once Playden is closing (BeginClosing), a request not started yet+ // (a restart after its write) only finishes the republish. A preparation queued for the game+ // answers kBusy (it names the old folder). Blocks the calling thread (never the worker's) until+ // the worker answers; a request the worker hasn't started within `timeout` is dropped and answers+ // kBusy. Once Playden is closing (BeginClosing), a request not started yet// answers kBusy with kRelocationClosing at once: the copy or move resumes at the next start.RuntimeRelocationResult Relocate(RuntimeRelocation request, std::chrono::milliseconds timeout);// Playden is quitting: callers waiting in Relocate for a relocation the worker hasn't started stopdiff --git a/src/installs/install_service.cpp b/src/installs/install_service.cppindex f4f3d88..692e83b 100644--- a/src/installs/install_service.cpp+++ b/src/installs/install_service.cpp@@ -570,7 +570,7 @@ void InstallService::Cancel(GameId id) {const auto root = volume && volume->available ? RootOn(job->view.volume_id, id) : std::string();jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),jobs_.end());- if (!root.empty()) removals_.push_back({id.store, root});+ if (!root.empty()) removals_.push_back({id.store, root, std::nullopt});}Publish();wake_.notify_all();@@ -586,7 +586,9 @@ void InstallService::Uninstall(GameId id) {if (!found->available && (!volume || !volume->available)) return;const auto root = found->available ? RootOn(found->volume_id, id) : std::string();installed_.erase(found);- if (!root.empty()) removals_.push_back({id.store, root});+ // Its runner still hears of it, to forget what it keeps of the game.+ if (!root.empty()) removals_.push_back({id.store, root, std::nullopt});+ else removals_.push_back({id.store, {}, id});Publish();wake_.notify_all();}@@ -716,7 +718,10 @@ void InstallService::Run() {}}if (removal) {- if (auto* remover = RunnerFor(removal->store)) remover->Remove(removal->root);+ if (auto* remover = RunnerFor(removal->store)) {+ if (removal->forget) remover->Forget(*removal->forget);+ else remover->Remove(removal->root);+ }std::lock_guard<std::mutex> lock(mutex_);Publish();continue;@@ -767,15 +772,17 @@ void InstallService::Run() {std::unique_lock<std::mutex> lock(mutex_);active_.reset();auto* job = Find(*next);- if (job && job->cancel_requested) {- jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),- jobs_.end());- remove_files = true;- } else if (job && result.ok) {+ if (job && result.ok) {+ // Installed, even when a cancel arrived meanwhile: it came too late (a copy may already have+ // deleted its source), so the game stays and can be uninstalled.const auto volume_id = job->view.volume_id;jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),jobs_.end());installed_.push_back({*next, result.install_bytes, next_root, volume_id, true, WallNow()});+ } else if (job && job->cancel_requested) {+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),+ jobs_.end());+ remove_files = true;} else if (job && job->view.state == InstallJobState::kRunning && result.canceled && stopping_) {// Playden is closing: the download stays queued, so the next start carries on with it.job->view.state = InstallJobState::kQueued;diff --git a/src/installs/install_service.h b/src/installs/install_service.hindex 5306851..b7f9826 100644--- a/src/installs/install_service.h+++ b/src/installs/install_service.h@@ -128,6 +128,8 @@ class InstallRunner {const std::function<void(std::uint64_t done, std::uint64_t total, std::uint64_t held)>& progress,const std::function<void(InstallStep)>& step) = 0;virtual bool Remove(const std::string& root) = 0;+ // An uninstalled game whose folder is missing: forgotten with nothing to delete (on the worker).+ virtual void Forget(const GameId& id) { (void)id; }};// Install queue for real games under <volume games_root>/<key>. One install runs at a time; jobs@@ -203,6 +205,7 @@ class InstallService {struct Removal {Store store = Store::kSteam;std::string root;+ std::optional<GameId> forget; // set: InstallRunner::Forget instead of deleting `root`};void Run();void Scan();diff --git a/src/stores/local/copy_plan.cpp b/src/stores/local/copy_plan.cppindex b86089d..de01295 100644--- a/src/stores/local/copy_plan.cpp+++ b/src/stores/local/copy_plan.cpp@@ -20,6 +20,12 @@ constexpr int kOpenAny = O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC;constexpr std::size_t kMaxLineBytes = 16 * 1024;constexpr const char* kFileList = ".playden-files"; // DepotInstaller::kFileList+// Names Playden writes at the top of a managed install (DepotInstaller's and the copy's own).+bool ReservedName(const std::string& name) {+ return name == kCopyJournalDir || name == kFileList || name == ".playden-files.tmp" || name == ".playden-install.json" ||+ name == ".playden-install.json.tmp" || name == ".playden-download";+}+bool Unsupported(int error) { return error == ENOSYS || error == EINVAL; }bool IsLinkError(int error) { return error == ELOOP || error == EMLINK; }@@ -119,7 +125,7 @@ bool WriteDurably(const std::string& path, const std::string& text) {bool MakeFolder(const std::string& path) {if (::mkdir(path.c_str(), 0777) == 0) return true;struct stat info {};- return errno == EEXIST && ::stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);+ return errno == EEXIST && ::lstat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);}// One value of the plan's line layout: the line without its end and trailing comma.@@ -206,6 +212,10 @@ CopyPlanBuild BuildCopyPlan(const std::string& source_path, std::size_t max_file}const std::string name = entry->d_name;if (name == "." || name == "..") continue;+ if (frame.relative.empty() && ReservedName(name)) {+ build.skipped.push_back(name);+ continue;+ }const auto relative = frame.relative.empty() ? name : frame.relative + "/" + name;if (entry->d_type == DT_LNK) return fail(LinkWords(relative), ELOOP);const int child = platform::OpenWalkChildUnprivileged(frame.fd, name.c_str(), kOpenAny, static_cast<std::uint64_t>(entry->d_fileno));diff --git a/src/stores/local/copy_plan.h b/src/stores/local/copy_plan.hindex 56ba53e..4ab92c6 100644--- a/src/stores/local/copy_plan.h+++ b/src/stores/local/copy_plan.h@@ -51,11 +51,14 @@ struct CopyPlanBuild {CopyPlan plan;std::string failure; // a sentence for the player, naming the path when one is at faultint error = 0; // errno of the failure, when there was one+ std::vector<std::string> skipped; // top-level names left out: Playden's own (for the log)};// Walks `source` (absolute): every folder and regular file, hidden ones included, no depth limit.// A link anywhere fails it, naming the link; so do an unreadable entry and more than `max_files`-// files or `max_bytes` bytes. Other kinds of entries (sockets, devices) are left out.+// files or `max_bytes` bytes. Other kinds of entries (sockets, devices) are left out, and so are+// Playden's own names at the top level (the copy journal, the install record and file list, the+// download journal): never copied over Playden's, and never deleted from a drop folder.CopyPlanBuild BuildCopyPlan(const std::string& source, std::size_t max_files = kMaxCopyFiles,std::uint64_t max_bytes = kMaxCopyBytes);diff --git a/src/stores/local/copy_runner.cpp b/src/stores/local/copy_runner.cppindex eb15673..d6dec15 100644--- a/src/stores/local/copy_runner.cpp+++ b/src/stores/local/copy_runner.cpp@@ -148,8 +148,15 @@ bool WriteAll(int fd, const char* data, std::size_t size, int* error) {return true;}-CopyStatus CopyOne(SourceWalk& walk, const CopyFile& file, const std::string& destination, std::vector<char>& buffer,- const std::atomic<bool>& cancel, const std::function<void(std::uint64_t)>& copied_bytes) {+// The temporary name of the plan's file `index`: in the copy journal, so it never meets a game file.+std::string PartPath(const std::string& root, std::size_t index) {+ return root + "/" + kCopyJournalDir + "/" + std::to_string(index) + ".part";+}++// Copies the file through `part` (fsync, rename to `destination`), checking it against the plan.+CopyStatus CopyOne(SourceWalk& walk, const CopyFile& file, const std::string& part, const std::string& destination,+ std::vector<char>& buffer, const std::atomic<bool>& cancel,+ const std::function<void(std::uint64_t)>& copied_bytes) {const int in = walk.OpenFile(file.path);if (in < 0) {const int error = errno;@@ -161,8 +168,7 @@ CopyStatus CopyOne(SourceWalk& walk, const CopyFile& file, const std::string& destruct stat before {};if (::fstat(in, &before) != 0) { ::close(in); return CopyStatus::kReadFailed; }if (!AsPlanned(before, file)) { ::close(in); return CopyStatus::kChanged; }- const auto part = destination + ".part";- const int out = ::open(part.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0666);+ const int out = ::open(part.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0666);if (out < 0) {const int error = errno;::close(in);@@ -206,10 +212,11 @@ CopyStatus CopyOne(SourceWalk& walk, const CopyFile& file, const std::string& dereturn CopyStatus::kOk;}+// A link in place of a folder is refused, not followed.bool MakeFolder(const std::string& path) {if (::mkdir(path.c_str(), 0777) == 0) return true;struct stat info {};- return errno == EEXIST && ::stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);+ return errno == EEXIST && ::lstat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);}// The install record, as the depot installer writes it for another store's game.@@ -234,10 +241,19 @@ bool WriteRecord(const std::string& root, const GameId& game, const CopyPlan& plreturn ok;}-// Partial files the plan's list doesn't name, so RemoveManagedInstall can remove exactly its paths.-void RemoveParts(const std::string& root, const CopyPlan* plan) {- if (!plan) return;- for (const auto& file : plan->files) std::remove((root + "/" + file.path + ".part").c_str());+// Partial files in the copy journal, which RemoveManagedInstall doesn't know, so it can remove+// exactly the plan's paths and then the journal folder.+void RemoveParts(const std::string& root) {+ const auto journal = root + "/" + kCopyJournalDir;+ DIR* folder = ::opendir(journal.c_str());+ if (!folder) return;+ std::vector<std::string> parts;+ while (const auto* item = ::readdir(folder)) {+ const std::string name = item->d_name;+ if (name.size() > 5 && name.compare(name.size() - 5, 5, ".part") == 0) parts.push_back(name);+ }+ ::closedir(folder);+ for (const auto& name : parts) std::remove((journal + "/" + name).c_str());}bool IsFolder(const std::string& path) {@@ -321,6 +337,8 @@ std::string LocalCopyRunner::Enqueue(installs::InstallService& service, const ImLog("import copy plan failed id=" + entry.id + " errno=" + std::to_string(build.error) + ": " + build.failure);return build.failure;}+ for (const auto& name : build.skipped)+ Log("import copy leaves out id=" + entry.id + " path=" + name + " (Playden's own name)");auto& plan = build.plan;plan.program = entry.program;plan.runtime_number = runtime_number;@@ -362,8 +380,8 @@ std::string LocalCopyRunner::Enqueue(installs::InstallService& service, const Im}installs::InstallRunner::Result LocalCopyRunner::Abandon(const ImportEntry& entry, const std::string& root,- const CopyPlan* plan, const std::string& failure) {- RemoveParts(root, plan);+ const std::string& failure) {+ RemoveParts(root);steam::RemoveManagedInstall(root);store_.CancelCopy(entry.id, failure);Log("import copy failed id=" + entry.id + ": " + failure);@@ -409,8 +427,8 @@ installs::InstallRunner::Result LocalCopyRunner::Install(}Changed();}- const auto plan = LoadCopyPlan(root);- if (!plan) return Abandon(*entry, root, nullptr, kCopyStoppedFailure);+ auto plan = LoadCopyPlan(root);+ if (!plan) return Abandon(*entry, root, kCopyStoppedFailure);// What a resume already has: files at their final name and planned size.std::vector<char> done(plan->files.size(), 0);@@ -461,7 +479,7 @@ installs::InstallRunner::Result LocalCopyRunner::Install(}const auto& file = plan->files[index];const auto before = copied;- const auto status = CopyOne(walk, file, root + "/" + file.path, buffer, cancel, on_bytes);+ const auto status = CopyOne(walk, file, PartPath(root, index), root + "/" + file.path, buffer, cancel, on_bytes);if (status != CopyStatus::kOk && copied != before) {copied = before; // the file's bytes went with its .partif (progress) progress(copied, plan->total, copied);@@ -471,7 +489,7 @@ installs::InstallRunner::Result LocalCopyRunner::Install(case CopyStatus::kCanceled: result.canceled = true; return result;case CopyStatus::kChanged:Log("import copy source changed id=" + entry->id + " path=" + file.path);- return Abandon(*entry, root, &*plan, kCopyChangedFailure);+ return Abandon(*entry, root, kCopyChangedFailure);case CopyStatus::kReadFailed:Log("import copy read failed id=" + entry->id + " path=" + file.path + " errno=" + std::to_string(errno));result.failure = "Could not read the game's files. Check the drive, then Resume.";@@ -490,11 +508,11 @@ installs::InstallRunner::Result LocalCopyRunner::Install(const auto size = FileSize(root + "/" + file.path);if (!size || *size != file.bytes) {Log("import copy verify failed id=" + entry->id + " path=" + file.path);- return Abandon(*entry, root, &*plan, "The copy could not be verified. Copy it again.");+ return Abandon(*entry, root, "The copy could not be verified. Copy it again.");}}if (!PlanHasFile(*plan, plan->program) || CheckProgram(root, plan->program) != ProgramCheck::kOk)- return Abandon(*entry, root, &*plan, "The game's program is missing from the copy. Copy it again.");+ return Abandon(*entry, root, "The game's program is missing from the copy. Copy it again.");// A game set up to play from its drive folder: its PS5 title follows the copy first. Until that// commits the drive folder stays the active one; a resume after a restart finds the files copied@@ -504,6 +522,9 @@ installs::InstallRunner::Result LocalCopyRunner::Install(relocation.game = id;relocation.runtime_number = plan->runtime_number;relocation.root = root; // its volume: the job's (the relocate hook asks the service)+ // Once the title is stopped (the game may have played from its folder meanwhile): files+ // changed since they were copied are copied again. Runs before Relocate returns.+ relocation.move_files = [this, &plan, &root, id = entry->id]() { return CopyChangedFiles(id, root, *plan); };const auto relocated = Relocate(relocation);if (relocated.outcome == LocalRelocationResult::Outcome::kBusy) {Log("import copy waits id=" + entry->id + ": " + relocated.message);@@ -524,13 +545,14 @@ installs::InstallRunner::Result LocalCopyRunner::Install(return result;}const auto journal = root + "/" + kCopyJournalDir;+ RemoveParts(root);std::remove(CopyPlanPath(root).c_str());::rmdir(journal.c_str());result.ok = true;result.install_bytes = plan->total;// A drop-folder game copied to a drive: committed, it plays from the copy, so its drop-folder// files go and it isn't stored twice. A failure there leaves them, and the copy stays done.- const auto left_behind = RemoveDropFolderSource(*entry, *plan);+ const auto left_behind = RemoveDropFolderSource(*entry, *plan, root);if (options_.before_finish && !options_.before_finish(id, root)) {Log("import copy complete id=" + entry->id + "; entry left copying");return result;@@ -543,7 +565,68 @@ installs::InstallRunner::Result LocalCopyRunner::Install(return result;}-std::string LocalCopyRunner::RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan) {+std::string LocalCopyRunner::CopyChangedFiles(const std::string& id, const std::string& root, CopyPlan& plan) {+ // Each planned file as the source has it now, through the same walk as the copy (no links).+ SourceWalk walk(plan.source);+ std::vector<std::size_t> changed;+ for (std::size_t index = 0; index < plan.files.size(); ++index) {+ auto& file = plan.files[index];+ const int fd = walk.OpenFile(file.path);+ if (fd < 0) {+ const int error = errno;+ if (error == ENOENT) continue; // gone from the source: the copy keeps what it took+ Log("import copy recheck failed id=" + id + " path=" + file.path + " errno=" + std::to_string(error));+ return "Playden can't check the game's files. Check the drive, then Resume.";+ }+ struct stat info {};+ const bool read = ::fstat(fd, &info) == 0;+ ::close(fd);+ if (!read || !S_ISREG(info.st_mode)) {+ Log("import copy recheck failed id=" + id + " path=" + file.path + (read ? " not a file" : " fstat"));+ return "Playden can't check the game's files. Check the drive, then Resume.";+ }+ if (AsPlanned(info, file)) continue;+ file.bytes = info.st_size > 0 ? static_cast<std::uint64_t>(info.st_size) : 0;+#if defined(__APPLE__)+ file.mtime = std::max<std::int64_t>(0, static_cast<std::int64_t>(info.st_mtimespec.tv_sec));+ file.mtime_nsec = static_cast<std::int64_t>(info.st_mtimespec.tv_nsec);+#else+ file.mtime = std::max<std::int64_t>(0, static_cast<std::int64_t>(info.st_mtim.tv_sec));+ file.mtime_nsec = static_cast<std::int64_t>(info.st_mtim.tv_nsec);+#endif+ changed.push_back(index);+ }+ if (changed.empty()) return {};+ // The plan first: a stop while copying leaves the file short of its new size, so Resume copies it.+ plan.total = 0;+ for (const auto& file : plan.files) plan.total += file.bytes;+ if (const auto saved = SaveCopyPlan(plan, root); !saved.empty()) return saved;+ std::vector<char> buffer(options_.buffer_bytes);+ const std::atomic<bool> never{false};+ bool program = false;+ for (const auto index : changed) {+ const auto& file = plan.files[index];+ Log("import copy copies again id=" + id + " path=" + file.path + " bytes=" + std::to_string(file.bytes));+ const auto status =+ CopyOne(walk, file, PartPath(root, index), root + "/" + file.path, buffer, never, [](std::uint64_t) {});+ const auto size = status == CopyStatus::kOk ? FileSize(root + "/" + file.path) : std::nullopt;+ if (!size || *size != file.bytes) {+ Log("import copy copy again failed id=" + id + " path=" + file.path ++ " status=" + std::to_string(static_cast<int>(status)));+ if (status == CopyStatus::kNoSpace) return "Not enough free space. Make room, then Resume.";+ if (status == CopyStatus::kChanged) return "The game's files are still changing. Close the game, then Resume.";+ return "Could not copy the game's changed files. Check the drive, then Resume.";+ }+ program = program || file.path == plan.program;+ if (options_.after_file) options_.after_file(file.path);+ }+ if (program && CheckProgram(root, plan.program) != ProgramCheck::kOk)+ return "The game's program is not a program any more. Check the game's folder.";+ return {};+}++std::string LocalCopyRunner::RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan,+ const std::string& root) {if (entry.volume != ImportStore::kDropFolderVolume) return {};// Only playden-import/<name>, and only when the copy's source is that very folder.constexpr const char* kPrefix = "playden-import/";@@ -555,11 +638,26 @@ std::string LocalCopyRunner::RemoveDropFolderSource(const ImportEntry& entry, coLog("import copy keeps the drop folder id=" + entry.id + ": " + plan.source + " is not " + console);return "The game is in Playden, but Playden didn't delete " + console + ". Delete it over FTP.";}- std::set<std::string> copied;- for (const auto& file : plan.files) copied.insert(file.path);+ // The copy's folders on the storage first: the drop folder goes only once its copy would survive+ // a power cut.+ bool synced = SyncFolder(root);+ for (const auto& dir : plan.dirs) synced = SyncFolder(root + "/" + dir) && synced;+ if (!synced) {+ Log("import copy keeps the drop folder id=" + entry.id + ": the copy's folders could not be synced errno=" ++ std::to_string(errno));+ return "The game is in Playden, but Playden didn't delete " + console + ". Delete it over FTP.";+ }+ // Only files the copy took, and only as it took them: one changed since (played from the drop+ // folder, or rewritten over FTP) stays.+ std::unordered_map<std::string, const CopyFile*> copied;+ for (const auto& file : plan.files) copied.emplace(file.path, &file);const auto removal = RemoveDropFolderEntry(- drop_folder, name, [&copied](const std::string& relative) { return copied.count(relative) > 0; }, options_.as_root,- [this](const std::string& line) { Log(line); });+ drop_folder, name,+ [&copied](const std::string& relative, const struct stat& info) {+ const auto found = copied.find(relative);+ return found != copied.end() && AsPlanned(info, *found->second);+ },+ options_.as_root, [this](const std::string& line) { Log(line); });if (removal.ok) {Log("import copy freed the drop folder id=" + entry.id + " path=" + console);return {};@@ -617,6 +715,8 @@ std::string LocalCopyRunner::Move(installs::InstallService& service, const ImporLog("import move plan failed id=" + entry.id + " errno=" + std::to_string(build.error) + ": " + build.failure);return build.failure;}+ for (const auto& name : build.skipped)+ Log("import move leaves out id=" + entry.id + " path=" + name + " (Playden's own name)");plan = std::move(build.plan);if (!PlanHasFile(plan, entry.program)) return "The program is not in the game's folder.";MakeFolder(volume->games_root);@@ -708,8 +808,7 @@ std::string LocalCopyRunner::Move(installs::InstallService& service, const Impor}bool LocalCopyRunner::Remove(const std::string& root) {- const auto plan = LoadCopyPlan(root);- RemoveParts(root, plan ? &*plan : nullptr);+ RemoveParts(root);const bool removed = steam::RemoveManagedInstall(root);const auto game = ParseKey(Basename(root));if (!game || game->store != Store::kLocal || !store_.loaded()) return removed;@@ -729,4 +828,20 @@ bool LocalCopyRunner::Remove(const std::string& root) {return removed;}+void LocalCopyRunner::Forget(const GameId& id) {+ // As Remove, with no folder to delete (its folder is missing).+ if (id.store != Store::kLocal || !store_.loaded()) return;+ const auto entry = store_.Find(id.value);+ if (!entry) return;+ if (entry->state == ImportState::kCopyQueued || entry->state == ImportState::kCopying) {+ store_.CancelCopy(entry->id);+ Log("import copy forgotten id=" + entry->id + " (its folder is missing)");+ Changed();+ } else if (entry->state == ImportState::kCopied) {+ store_.Uninstalled(entry->id);+ Log("import copy uninstalled id=" + entry->id + " (its folder is missing)");+ Changed();+ }+}+} // namespace playden::stores::localdiff --git a/src/stores/local/copy_runner.h b/src/stores/local/copy_runner.hindex fd2d5a0..16a4a59 100644--- a/src/stores/local/copy_runner.h+++ b/src/stores/local/copy_runner.h@@ -3,14 +3,15 @@// imported game is copied from its drive folder into <games_root>/local-<id> on the chosen volume// and becomes a managed install there; the drive folder is never touched. A drop-folder game's// folder (/data/playden-import/<name>) is deleted once its copy is committed, so the game isn't-// stored twice; until then it plays from the drop folder.+// stored twice (files changed since they were copied stay); until then it plays from the drop folder.//// Flow: Enqueue (on the Local source's worker) walks the folder into a copy plan, saves it in the// destination (copy_plan.h), sets the entry copy_queued and queues the job with the plan's total// (the service's free-space check). Install (on the service's worker) sets it copying, checks free-// space again, copies the files in plan order (<path>.part, fsync, rename; a resume skips files-// already at their planned size), verifies every file and the program, writes the install record-// and sets the entry copied. Remove (cancel or uninstall) deletes the folder and moves the entry+// space again, copies the files in plan order (.playden-copy/<index>.part, fsync, rename; a resume+// skips files already at their planned size), verifies every file and the program, has the title+// follow the copy (files changed in the drive folder meanwhile are copied again), writes the+// install record and sets the entry copied. Remove (cancel or uninstall) deletes the folder and moves the entry// back to in_place (a copy) or to the removed list (a copied game).//// A game already prepared to play from its folder keeps its PS5 title, runtime number and bottle:@@ -54,8 +55,8 @@ struct LocalRelocation {std::uint32_t runtime_number = 0; // 0: none yet (no PS5 title)std::string root; // the folder in Playden, as this process opens itstd::string volume_id; // the install volume of `root`; empty: the game's copy job's- // The move's rename (empty for a copy): run once the game's title is stopped; empty, or why not.- // Safe to run again after it succeeded.+ // Run once the game's title is stopped: the move's rename, or for a copy, copying again the files+ // that changed since they were copied. Empty, or why not. Safe to run again after it succeeded.std::function<std::string()> move_files;};struct LocalRelocationResult {@@ -71,7 +72,7 @@ struct LocalCopyOptions {std::function<std::optional<steam::VolumeSpace>(const std::string& path)> space;std::size_t buffer_bytes = 1024 * 1024;// Moves the game's PS5 title to its folder in Playden (RuntimeHost::Relocate): after a copy is- // verified, and for a move (which runs move_files). Empty: no game has a title (move_files runs at+ // verified, and for a move; both run move_files. Empty: no game has a title (move_files runs at// once).std::function<LocalRelocationResult(const LocalRelocation&)> relocate;// Runs work with root raised (ps5::WithRoot): the move's rename of a root-owned drop folder.@@ -112,13 +113,19 @@ class LocalCopyRunner final : public installs::InstallRunner {const std::function<void(std::uint64_t done, std::uint64_t total, std::uint64_t held)>& progress,const std::function<void(installs::InstallStep)>& step) override;bool Remove(const std::string& root) override;+ void Forget(const GameId& id) override;private:LocalRelocationResult Relocate(const LocalRelocation& relocation);- // After a drop-folder game's copy committed: its drop-folder files (those the copy took) are- // deleted. Empty, or the sentence kept on the entry when some stay.- std::string RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan);- Result Abandon(const ImportEntry& entry, const std::string& root, const CopyPlan* plan, const std::string& failure);+ // Before the title follows the copy (LocalRelocation::move_files): every planned file the source+ // has changed since it was copied is planned again as it is now (the plan saved) and copied again.+ // A file gone from the source stays as copied. Empty, or why not.+ std::string CopyChangedFiles(const std::string& id, const std::string& root, CopyPlan& plan);+ // After a drop-folder game's copy (in `root`) committed: the copy's folders are synced, then its+ // drop-folder files (those the copy took, unchanged since) are deleted. Empty, or the sentence+ // kept on the entry when some stay.+ std::string RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan, const std::string& root);+ Result Abandon(const ImportEntry& entry, const std::string& root, const std::string& failure);void Changed();void Log(const std::string& line) const;diff --git a/src/stores/local/drop_folder_access.cpp b/src/stores/local/drop_folder_access.cppindex d3b0ead..1bf6b29 100644--- a/src/stores/local/drop_folder_access.cpp+++ b/src/stores/local/drop_folder_access.cpp@@ -329,9 +329,25 @@ int RemoveWalkChild(int parent, const char* name, bool folder) {#endif}+// Stats `name` in the held folder `parent` without following it.+int StatWalkChild(int parent, const char* name, struct stat* info) {+ if (!PlainName(name ? name : "")) { errno = EINVAL; return -1; }+#if defined(PLAYDEN_WALK_BY_PATH)+ // By path, as RemoveWalkChild: once the path still names the held parent; lstat never follows.+ fs::path parent_path;+ if (!platform::walk_detail::PathOf(parent, &parent_path)) return -1;+ struct stat held{}, named{};+ if (::fstat(parent, &held) != 0 || ::lstat(parent_path.c_str(), &named) != 0) return -1;+ if (!S_ISDIR(named.st_mode) || named.st_dev != held.st_dev || named.st_ino != held.st_ino) { errno = ESTALE; return -1; }+ return ::lstat((parent_path / name).c_str(), info);+#else+ return ::fstatat(parent, name, info, AT_SYMLINK_NOFOLLOW);+#endif+}+class Removal {public:- Removal(const std::function<bool(const std::string&)>& planned, const runtime::WritableFoldersAsRoot& as_root)+ Removal(const DropFolderPlanned& planned, const runtime::WritableFoldersAsRoot& as_root): planned_(planned), as_root_(as_root) {}~Removal() {for (auto& frame : stack_) if (frame.fd >= 0) ::close(frame.fd);@@ -443,8 +459,13 @@ class Removal {if (child.type == DT_DIR || error != ENOTDIR) { Fail(relative, "open=" + Error(error)); return; }}if (child.type != DT_REG && child.type != DT_UNKNOWN) { ++result_.kept; return; }- // A file: only one the copy took goes.- if (!planned_ || !planned_(relative.generic_string())) { ++result_.kept; return; }+ // A file: only one the copy took goes, and only as the copy took it.+ struct stat info{};+ if (StatWalkChild(folder.fd, child.name.c_str(), &info) != 0) {+ if (errno != ENOENT) ++result_.kept; // can't be checked: left alone+ return;+ }+ if (!S_ISREG(info.st_mode) || !planned_ || !planned_(relative.generic_string(), info)) { ++result_.kept; return; }if (Remove(folder.fd, child.name, false)) ++result_.files;else if (errno != ENOENT) Fail(relative, "unlink=" + Error(errno));}@@ -458,7 +479,7 @@ class Removal {return result_;}- const std::function<bool(const std::string&)>& planned_;+ const DropFolderPlanned& planned_;const runtime::WritableFoldersAsRoot& as_root_;std::vector<Frame> stack_;std::size_t entries_ = 0;@@ -469,7 +490,7 @@ class Removal {} // namespaceDropFolderRemoval RemoveDropFolderEntry(const std::string& drop_folder, const std::string& name,- const std::function<bool(const std::string& relative)>& planned,+ const DropFolderPlanned& planned,const runtime::WritableFoldersAsRoot& as_root,const std::function<void(const std::string&)>& log) {DropFolderRemoval result;diff --git a/src/stores/local/drop_folder_access.h b/src/stores/local/drop_folder_access.hindex d819f8e..eefefc9 100644--- a/src/stores/local/drop_folder_access.h+++ b/src/stores/local/drop_folder_access.h@@ -27,6 +27,7 @@#include <functional>#include <optional>#include <string>+#include <sys/stat.h>#include <sys/types.h>namespace playden::stores::local {@@ -64,8 +65,9 @@ DropFolderAccessResult OpenDropFolderEntry(const std::string& entry, const DropF// twice. Only the entry `name` (one plain folder name) directly inside `drop_folder` (the drop// folder as this process opens it: /data/playden-import on the console) is walked, through// platform/directory_walk.h, never following a link: a link is never followed nor deleted, and-// neither is a file `planned` doesn't name (relative to the entry, '/' separators: what the copy-// took). A folder still holding something then stays, and the result says so. Root is raised (as_root)+// neither is a file `planned` doesn't name (relative to the entry, '/' separators, with the file's+// lstat: what the copy took, unchanged since). A folder still holding something then stays, and the+// result says so. Root is raised (as_root)// only for one removal the app user may not do (FTP leaves root-owned folders). Run with no root// held by this thread.struct DropFolderRemoval {@@ -75,8 +77,9 @@ struct DropFolderRemoval {std::size_t kept = 0; // entries left: links, files the copy didn't takestd::size_t raises = 0;};+using DropFolderPlanned = std::function<bool(const std::string& relative, const struct stat& info)>;DropFolderRemoval RemoveDropFolderEntry(const std::string& drop_folder, const std::string& name,- const std::function<bool(const std::string& relative)>& planned,+ const DropFolderPlanned& planned,const runtime::WritableFoldersAsRoot& as_root,const std::function<void(const std::string&)>& log = {});diff --git a/src/stores/local/library_source.cpp b/src/stores/local/library_source.cppindex 99875af..f456142 100644--- a/src/stores/local/library_source.cpp+++ b/src/stores/local/library_source.cpp@@ -409,6 +409,10 @@ void LocalLibrarySource::Execute(const Job& job) {return std::any_of(service.installed.begin(), service.installed.end(),[&](const installs::InstalledGame& game) { return game.id == id; });};+ const auto available = [&](const GameId& id) {+ return std::any_of(service.installed.begin(), service.installed.end(),+ [&](const installs::InstalledGame& game) { return game.id == id && game.available; });+ };const auto queued = [&](const GameId& id) {return std::any_of(service.jobs.begin(), service.jobs.end(),[&](const installs::InstallJobView& view) { return view.id == id; });@@ -417,12 +421,16 @@ void LocalLibrarySource::Execute(const Job& job) {for (const auto& game : store_.Games()) {if (game.state != ImportState::kCopyQueued && game.state != ImportState::kCopying) continue;const auto id = GameId::Local(game.id);- if (installed(id)) {+ if (available(id)) {// The copy committed its install record; Playden stopped before imports.json said so.if (game.state == ImportState::kCopyQueued) store_.StartCopy(game.id);const auto finished = store_.FinishCopy(game.id);Log("import copy reconciled id=" + game.id + (finished.ok() ? " copied" : " failed: " + finished.message()));changed = true;+ } else if (installed(id)) {+ // Listed on a drive that isn't there (a copy queued there, or its folder missing): nothing+ // says whether it finished, so it stays as it is until the drive is back.+ Log("import copy reconcile waits id=" + game.id + ": its install is unavailable");} else if (!queued(id)) {// A move renames the drop folder away: one whose rename happened is finished, never put// back in place (its folder is in Playden now).diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex cdbd0df..7256236 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -4235,6 +4235,38 @@ void CopiedGameKeepsItsTitle() {host.Shutdown();}+// A preparation queued for the game names its old folder (it would move the game back there):+// the relocation waits for it, and goes once it's withdrawn.+void RelocationWaitsForQueuedPreparation() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ const auto config = MoveConfig(fixture, kit, &uuids, move);+ const std::string drive = "/mnt/usb0/playden/import/Imported";+ const auto imported = PrepareImported(fixture, config, drive);+ fs::create_directories(fixture.root / "data/playden-games");+ fs::copy(fixture.root / fs::path(drive).relative_path(), fixture.root / fs::path(kImportedRoot).relative_path(),+ fs::copy_options::recursive);+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ host.HoldPreparations(true);+ host.Prepare(ImportedRequest(imported.number, drive));+ unsigned copies = 0;+ const auto refused = RelocateNow(host, imported.number, [&]() -> std::string { ++copies; return {}; });+ CHECK(refused.outcome == RuntimeRelocationResult::Outcome::kBusy &&+ refused.message == "Finish setting up the game first.");+ CHECK(copies == 0 && host.Snapshot().installs[0].install_path == drive);+ CHECK(host.WithdrawPrepare(imported.number));+ host.HoldPreparations(false);+ const auto result = RelocateNow(host, imported.number, [&]() -> std::string { ++copies; return {}; });+ if (!result.message.empty()) std::fprintf(stderr, "Relocate: %s\n", result.message.c_str());+ CHECK(result.outcome == RuntimeRelocationResult::Outcome::kDone && copies == 1);+ CheckRelocated(fixture, host, imported, "internal");+ host.Shutdown();+}+// Move: the drop folder renamed under the title's publication lease; refused while the title runs.void MovedGameKeepsItsTitle() {Fixture fixture;@@ -4569,6 +4601,7 @@ int main(int argc, char** argv) {for (int scenario = 0; scenario <= 9; ++scenario) UnownedUpgradeAfterCommittedSettingsUpdates(scenario);MovedGameWithUnreadableOperationRepublishes();CopiedGameKeepsItsTitle();+ RelocationWaitsForQueuedPreparation();MovedGameKeepsItsTitle();RelocationResumesAfterRestart();RelocationFallsBackToANewTitle();diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cppindex e4f253b..64a58c8 100644--- a/tests/install_service_test.cpp+++ b/tests/install_service_test.cpp@@ -322,14 +322,16 @@ int AttemptsAt(Runner& runner, const std::filesystem::path& root) {class LocalRunner final : public InstallRunner {public:std::atomic<bool> block{false};+ std::atomic<bool> ignore_cancel{false}; // the run finishes whatever a cancel says (it came too late)std::mutex mutex;std::vector<GameId> installed;std::vector<std::string> removed;+ std::vector<GameId> forgotten;Result Install(const GameId& id, const std::string& root, const std::atomic<bool>& cancel,const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,const std::function<void(InstallStep)>&) override {while (block) {- if (cancel) return {false, true, {}, 0};+ if (cancel && !ignore_cancel) return {false, true, {}, 0};std::this_thread::sleep_for(1ms);}std::filesystem::create_directories(root);@@ -345,8 +347,61 @@ class LocalRunner final : public InstallRunner {std::filesystem::remove_all(root);return true;}+ void Forget(const GameId& id) override {+ std::lock_guard<std::mutex> lock(mutex);+ forgotten.push_back(id);+ }};+// A cancel that arrives while the run finishes comes too late: the run's install stays, and+// nothing is removed (a copy may already have deleted its source). An uninstall of a game whose+// folder is missing deletes nothing but tells its runner to forget it.+void LateCancelKeepsTheInstall(const std::filesystem::path& root) {+ const auto local = GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ std::filesystem::remove_all(root);+ {+ Sessions sessions;+ Runner steam(sessions);+ LocalRunner imports;+ imports.block = true;+ imports.ignore_cancel = true;+ InstallService service({{Store::kSteam, &steam}, {Store::kLocal, &imports}},+ {{InstallService::kPrimaryVolumeId, "Console storage", root.string(), true}});+ service.Install(local, 7);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {+ const auto* job = JobOf(s, local);+ return job && job->state == InstallJobState::kRunning;+ });+ service.Cancel(local);+ imports.block = false;+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return Installed(s, local) && s.jobs.empty(); });+ {+ std::lock_guard<std::mutex> lock(imports.mutex);+ CHECK(imports.removed.empty() && imports.installed.size() == 1);+ }+ CHECK(std::filesystem::exists(root / ToKey(local) / ".playden-install.json"));+ }+ // Its folder goes missing while Playden is closed: listed unavailable, then uninstalled.+ std::filesystem::remove_all(root / ToKey(local));+ {+ Sessions sessions;+ Runner steam(sessions);+ LocalRunner imports;+ InstallService service({{Store::kSteam, &steam}, {Store::kLocal, &imports}},+ {{InstallService::kPrimaryVolumeId, "Console storage", root.string(), true}});+ const auto listed = service.Snapshot();+ CHECK(listed.installed.size() == 1 && listed.installed[0].id == local && !listed.installed[0].available);+ service.Uninstall(local);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {+ std::lock_guard<std::mutex> lock(imports.mutex);+ return !Installed(s, local) && imports.forgotten.size() == 1;+ });+ std::lock_guard<std::mutex> lock(imports.mutex);+ CHECK(imports.forgotten[0] == local && imports.removed.empty());+ }+ std::filesystem::remove_all(root);+}+// Jobs waiting to try again never hold up the queue: another store's job behind a Steam job that// waits for the sign-in runs, two waiting Steam jobs both keep trying, and a waiting job can be// canceled, paused and resumed.@@ -524,6 +579,7 @@ int main() {LiveTelemetryDecaysWithoutCallbacks(std::filesystem::temp_directory_path() / ("playden-rate-service-" + std::to_string(::getpid())));UnreachableSteamWaits(std::filesystem::temp_directory_path() / ("playden-unreachable-service-" + std::to_string(::getpid())));WaitingJobsDontBlockTheQueue(std::filesystem::temp_directory_path() / ("playden-waiting-service-" + std::to_string(::getpid())));+ LateCancelKeepsTheInstall(std::filesystem::temp_directory_path() / ("playden-late-cancel-service-" + std::to_string(::getpid())));SignInEndsSteamWait(std::filesystem::temp_directory_path() / ("playden-signin-wait-service-" + std::to_string(::getpid())));CompletedDownloadsList(std::filesystem::temp_directory_path() / ("playden-completed-service-" + std::to_string(::getpid())));const auto requests = ParseInstallRequests("uninstall 439490\n439490\ncancel 108600\n108600\n");@@ -685,6 +741,8 @@ int main() {CHECK(JobOf(service.Snapshot(), SteamId(610))->state == InstallJobState::kRunning);service.Cancel(SteamId(620));service.Cancel(SteamId(610));+ // The run stops for the cancel first (one that finished meanwhile would stay installed).+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return !JobOf(s, SteamId(610)); });runner.block = false;AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {std::lock_guard<std::mutex> lock(runner.mutex);diff --git a/tests/local_copy_test.cpp b/tests/local_copy_test.cppindex 078bd58..13b91d1 100644--- a/tests/local_copy_test.cpp+++ b/tests/local_copy_test.cpp@@ -337,6 +337,9 @@ void CopyRelocatesItsTitle() {if (running) {result.outcome = LocalRelocationResult::Outcome::kBusy;result.message = "Close the game first.";+ } else {+ // Once the title is stopped: the files changed since they were copied (none here).+ CHECK(relocation.move_files && relocation.move_files().empty());}return result;};@@ -354,7 +357,7 @@ void CopyRelocatesItsTitle() {{std::lock_guard<std::mutex> lock(mutex);CHECK(asked[0].game == fixture.Game() && asked[0].runtime_number == kNumber &&- asked[0].root == fixture.Dest().string() && !asked[0].move_files);+ asked[0].root == fixture.Dest().string());}running = false;WaitFor([&] { return fixture.Installed() && fixture.State() == ImportState::kCopied; }, "the relocated copy");@@ -847,6 +850,80 @@ void FreeSpaceRefused() {}, "the refused copy gone");}+// A link in place of one of the copy's folders is refused, never written through.+void LinkInTheCopyRefused() {+ Fixture fixture;+ fixture.Start(false);+ const auto added = fixture.store->Add("usb0", "playden/import/Rally", "Rally", "Bin/Rally.exe");+ CHECK(added.ok());+ auto build = BuildCopyPlan(fixture.source.string());+ CHECK(build.ok);+ build.plan.program = "Bin/Rally.exe";+ CHECK(SaveCopyPlan(build.plan, fixture.Dest().string()).empty());+ const auto elsewhere = fixture.root / "elsewhere";+ fs::create_directories(elsewhere);+ fs::create_directory_symlink(elsewhere, fixture.Dest() / "data");+ CHECK(fixture.store->QueueCopy(kId).ok());+ fixture.service->Install(fixture.Game(), build.plan.total);+ WaitFor([&] { const auto job = fixture.Job(); return job && job->state == InstallJobState::kFailed; }, "the refused folder");+ CHECK(fixture.Job()->failure == "Could not write the game files." && fs::is_empty(elsewhere));+}++// A restart without the drive a copy was queued to: its install is listed unavailable, and the+// reconcile leaves the entry copying (not copied) until the drive is back, when the copy carries on.+void ReconcileWaitsForTheDrive() {+ Fixture fixture;+ const auto games = fixture.root / "mnt/ext1/playden/games";+ fs::create_directories(games);+ fixture.extra_volumes = {{"m2", "M.2 SSD", games.string(), true}};+ std::atomic<bool> pause{true};+ fixture.options.after_file = [&](const std::string&) {+ if (pause.exchange(false)) fixture.service->Pause(GameId::Local(kId));+ };+ fixture.Start();+ fixture.Add();+ CHECK(fixture.Outcome(fixture.local->CopyIntoPlayden(kId, "m2", kNumber)).ok);+ WaitFor([&] { const auto job = fixture.Job(); return job && job->state == InstallJobState::kPaused; }, "paused");+ fixture.Stop();+ fixture.extra_volumes[0].available = false;+ fixture.Start();+ const auto snapshot = fixture.service->Snapshot();+ CHECK(snapshot.jobs.empty() && snapshot.installed.size() == 1 && !snapshot.installed[0].available);+ auto* service = fixture.service.get();+ CHECK(fixture.Outcome(fixture.local->Reconcile([service] { return service->Snapshot(); },+ [service](const GameId& id) { service->Cancel(id); })).ok);+ CHECK(fixture.State() == ImportState::kCopying);+ CHECK(fixture.Logged("import copy reconcile waits id=" + std::string(kId)));+ fixture.Stop();+ fixture.extra_volumes[0].available = true;+ fixture.Start();+ WaitFor([&] { return fixture.Job().has_value() || fixture.Installed(); }, "the copy job back"); // paused, or carrying on+ fixture.service->Resume(fixture.Game());+ WaitFor([&] { return fixture.Installed() && fixture.State() == ImportState::kCopied; }, "the copy finished");+ CHECK(Read(games / ("local-" + std::string(kId)) / "data/big.pak") == Read(fixture.source / "data/big.pak"));+}++// A copied game whose folder went missing from Playden's storage: Uninstall forgets it, and its+// entry leaves the library (nothing to delete).+void UninstallMissingCopy() {+ Fixture fixture;+ fixture.Start();+ fixture.Add();+ CHECK(fixture.Outcome(fixture.local->CopyIntoPlayden(kId)).ok);+ WaitFor([&] { return fixture.Installed() && fixture.State() == ImportState::kCopied; }, "copied");+ fixture.Stop();+ fs::remove_all(fixture.Dest());+ fixture.Start();+ const auto snapshot = fixture.service->Snapshot();+ CHECK(snapshot.installed.size() == 1 && !snapshot.installed[0].available);+ fixture.service->Uninstall(fixture.Game());+ WaitFor([&] { return !fixture.store->Find(kId).has_value(); }, "the entry gone");+ CHECK(fixture.store->Removed().size() == 1 && fixture.store->Removed()[0].id == kId);+ CHECK(fixture.service->Snapshot().installed.empty() && fixture.Logged("import copy uninstalled id=" + std::string(kId)));+ WaitFor([&] { return fixture.local->Snapshot()->games.empty(); }, "the game out of the library");+ CHECK(fs::exists(fixture.source / "Bin/Rally.exe"));+}+} // namespace// A drop-folder game copied to another drive: once the copy is committed its drop-folder files go@@ -942,6 +1019,78 @@ void DropFolderCopyFreesTheDropFolder() {CHECK(fixture.Installed() && fixture.State() == ImportState::kCopied);::chmod(parent.c_str(), 0755);}+ {+ // A copied file changed in the drop folder before the title followed the copy (the game played+ // from there meanwhile): copied again, then the whole drop folder goes.+ Fixture fixture;+ const auto dest = m2(fixture);+ std::string changed;+ fixture.options.after_file = [&](const std::string& path) {+ if (!changed.empty()) return;+ changed = path;+ std::ofstream(fixture.Drop() / path, std::ios::binary | std::ios::app) << "saved by the game";+ };+ fixture.Start();+ fixture.AddDrop();+ copy(fixture);+ CHECK(!changed.empty() && Has(Read(dest / changed), "saved by the game"));+ CHECK(fixture.Logged("import copy copies again id=" + std::string(kId) + " path=" + changed));+ CHECK(!fs::exists(fixture.Drop()) && fixture.store->Find(kId)->failure.empty());+ const auto plan_total = fixture.service->Snapshot().installed[0].install_bytes;+ CHECK(plan_total == 70000 + 3 * 1024 * 1024 + 17 + 4 + 21 + 7 + 17);+ CHECK(Has(Read(dest / ".playden-install.json"), "\"install_bytes\":" + std::to_string(plan_total)));+ }+ {+ // A copied file changed after the title followed the copy: the drop folder keeps it.+ Fixture fixture;+ const auto dest = m2(fixture);+ fixture.options.relocate = [&](const LocalRelocation& relocation) {+ LocalRelocationResult result;+ if (relocation.move_files) result.message = relocation.move_files();+ if (!result.message.empty()) result.outcome = LocalRelocationResult::Outcome::kFailed;+ std::ofstream(fixture.Drop() / "data/big.pak", std::ios::binary | std::ios::app) << "late";+ return result;+ };+ fixture.Start();+ fixture.AddDrop();+ const auto original = Read(fixture.Drop() / "data/big.pak");+ copy(fixture);+ CHECK(Read(dest / "data/big.pak") == original);+ const auto left = Files(fixture.Drop());+ CHECK(left.size() == 1 && left[0].first == "data/big.pak" && left[0].second == original + "late");+ CHECK(Has(fixture.store->Find(kId)->failure, "still in /data/playden-import/Rally"));+ CHECK(fixture.Installed() && fixture.State() == ImportState::kCopied);+ }+ {+ // Playden's own names at the top of the game's folder are left out, and stay in the drop+ // folder; deeper down they are the game's. A game file next to its ".part" name copies both.+ Fixture fixture;+ const auto dest = m2(fixture);+ Write(fixture.source / ".playden-install.json", "the game's own record");+ Write(fixture.source / ".playden-files", "the game's own list");+ Write(fixture.source / ".playden-copy/plan.json", "{}");+ Write(fixture.source / ".playden-download/journal", "journal");+ Write(fixture.source / "data/.playden-files", "nested");+ Write(fixture.source / "data/asset", "asset");+ Write(fixture.source / "data/asset.part", "asset part");+ const auto build = BuildCopyPlan(fixture.source.string());+ CHECK(build.ok);+ CHECK(std::set<std::string>(build.skipped.begin(), build.skipped.end()) ==+ std::set<std::string>({".playden-install.json", ".playden-files", ".playden-copy", ".playden-download"}));+ CHECK(!PlanHasFile(build.plan, ".playden-install.json") && !PlanHasFile(build.plan, ".playden-copy/plan.json") &&+ PlanHasFile(build.plan, "data/.playden-files"));+ fixture.Start();+ fixture.AddDrop();+ copy(fixture);+ CHECK(fixture.Logged("import copy leaves out id=" + std::string(kId) + " path=.playden-install.json"));+ CHECK(Read(dest / "data/asset") == "asset" && Read(dest / "data/asset.part") == "asset part");+ CHECK(Read(dest / "data/.playden-files") == "nested" && !fs::exists(dest / ".playden-copy"));+ CHECK(Has(Read(dest / ".playden-install.json"), "\"store\":\"local\""));+ CHECK(!fs::exists(dest / ".playden-download"));+ const auto left = Files(fixture.Drop());+ CHECK(left.size() == 4 && Read(fixture.Drop() / ".playden-install.json") == "the game's own record");+ CHECK(fs::exists(fixture.Drop() / ".playden-copy/plan.json") && !fs::exists(fixture.Drop() / "data/asset.part"));+ }{// A crash after the commit's record: the files are gone already, the next start commits the entry.Fixture fixture;@@ -981,6 +1130,9 @@ int main() {MoveRefusedWhileTheTitleRuns();MoveFinishesAfterRestart();DropFolderCopyFreesTheDropFolder();+ LinkInTheCopyRefused();+ ReconcileWaitsForTheDrive();+ UninstallMissingCopy();std::puts("local copy tests passed");return 0;}