diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 22e49fdc60..5df86e4f1e 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -746,6 +746,8 @@ set(SLIC3R_GUI_SOURCES Utils/PaintCLI.hpp Utils/CalibUtils.cpp Utils/CalibUtils.hpp + Utils/CloudDeleteQueue.cpp + Utils/CloudDeleteQueue.hpp Utils/ColorSpaceConvert.cpp Utils/ColorSpaceConvert.hpp Utils/CrealityPrint.cpp diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index bd110e6c6b..022ad55ea2 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -16,6 +16,7 @@ #include "WebUserLoginDialog.hpp" #include "WebViewDialog.hpp" #include "slic3r/Utils/BBLCloudServiceAgent.hpp" +#include "slic3r/Utils/CloudDeleteQueue.hpp" #include "slic3r/Utils/NetworkAgent.hpp" #include "GUI_Init.hpp" #include "GUI_ObjectList.hpp" @@ -6040,11 +6041,13 @@ void GUI_App::enable_user_preset_folder(bool enable) app_config->set("preset_folder", user_id); GUI::wxGetApp().preset_bundle->update_user_presets_directory(user_id); PluginManager::instance().set_cloud_user(user_id); + m_cloud_delete_queue.start_session(user_id); } else { BOOST_LOG_TRIVIAL(info) << "preset_folder: set to empty"; app_config->set("preset_folder", ""); GUI::wxGetApp().preset_bundle->update_user_presets_directory(DEFAULT_USER_FOLDER_NAME); PluginManager::instance().set_cloud_user(""); + m_cloud_delete_queue.start_session(""); } } @@ -7092,7 +7095,9 @@ bool GUI_App::reload_settings() load_pending_vendors(); preset_bundle->load_user_presets(*app_config, user_presets, ForwardCompatibilitySubstitutionRule::Enable); - preset_bundle->save_user_presets(*app_config, get_delete_cache_presets()); + // save_user_presets() never fills this list; cloud deletes go through m_cloud_delete_queue. + std::map unused_delete_list; + preset_bundle->save_user_presets(*app_config, unused_delete_list); // Re-apply any edited config that was wiped during vendor loading or sync. auto restore_snapshot = [](PresetCollection& col, const PresetSnapshot& snap, const char* label) { @@ -9482,137 +9487,46 @@ void GUI_App::load_current_presets(bool active_preset_combox/*= false*/, bool ch } } -static std::mutex mutex_delete_cache_presets; - -std::map & GUI_App::get_delete_cache_presets() -{ - return need_delete_presets; -} - -std::map GUI_App::get_delete_cache_presets_lock() -{ - std::scoped_lock l(mutex_delete_cache_presets); - return need_delete_presets; -} - +// Sends the due cloud deletes of the signed-in account. Runs on the preset sync thread. void GUI_App::process_delete_presets() { - std::map delete_cache_presets = get_delete_cache_presets_lock(); - for (auto it = delete_cache_presets.begin(); it != delete_cache_presets.end();) { - if (it->first.empty()) continue; - std::string del_setting_id = it->first; - int result = m_agent->delete_setting(del_setting_id); - if (result == 0) { - preset_deleted_from_cloud(del_setting_id); - it = delete_cache_presets.erase(it); + if (!m_agent) + return; + m_cloud_delete_queue.send_due( + [] { return CloudDeleteQueue::Clock::now(); }, [this] { return m_agent->get_user_id(); }, + [this](const CloudDeleteQueue::Entry& entry) { + auto orca = get_orca_cloud_agent(m_agent); + const bool gone = orca && orca->delete_setting_as(entry.owner, entry.setting_id) == BAMBU_NETWORK_SUCCESS; + if (!gone) + BOOST_LOG_TRIVIAL(info) << "delete setting = " << entry.setting_id << " failed, will retry"; + return gone; + }, + [this](const CloudDeleteQueue::Entry& entry) { + // The cloud has no such profile any more, so the .info that kept the delete pending can go. + remove_info_file(entry.info_path); m_create_preset_blocked = { false, false, false, false, false, false }; - BOOST_LOG_TRIVIAL(trace) << "sync_preset: sync operation: delete success! setting id = " << del_setting_id; - } - else { - BOOST_LOG_TRIVIAL(info) << "delete setting = " <get("preset_folder"); if (user_sub_folder.empty()) user_sub_folder = DEFAULT_USER_FOLDER_NAME; - const std::string dir_user_presets = data_dir() + "/" + PRESET_USER_DIR + "/" + user_sub_folder; - - // Scan for orphaned .info files in each preset type directory - std::vector preset_types = {PRESET_PRINT_NAME, PRESET_FILAMENT_NAME, PRESET_PRINTER_NAME}; - - for (const std::string& type : preset_types) { - fs::path type_dir = fs::path(dir_user_presets) / type; - if (!fs::exists(type_dir)) - continue; - - // Iterate through all .info files. Use the error_code-based iterator so a transient - // directory-read failure (e.g. macOS readdir returning ENOTSUP) is logged and skipped - // instead of throwing an uncaught exception that would terminate the app from the - // background sync thread this runs on. - boost::system::error_code ec; - for (boost::filesystem::directory_iterator it(type_dir, ec), end; !ec && it != end; it.increment(ec)) { - const auto& entry = *it; - if (entry.path().extension() != ".info") - continue; - - fs::path info_file = entry.path(); - fs::path preset_file = info_file; - preset_file.replace_extension(".json"); - - // If .json doesn't exist, .info is orphaned. Read under the lock, so a - // remove_files() in another instance is seen whole or not at all; the - // delete queue's own mutex is taken after the lock is released. - std::string setting_id; - { - InstanceLock instance_lock(user_presets_lock_path()); - if (!fs::exists(preset_file)) - setting_id = extract_setting_id_from_info(info_file.string()); - } - if (!setting_id.empty()) { - // Add to need_delete_presets - delete_preset_from_cloud(setting_id, info_file.string()); - BOOST_LOG_TRIVIAL(info) << "Found orphaned .info file on startup: " << info_file.string(); - } - } - if (ec) - BOOST_LOG_TRIVIAL(warning) << "scan_orphaned_info_files: failed to scan " << type_dir.string() << ": " << ec.message(); - } + queue_orphaned_info_files(m_cloud_delete_queue, generation, data_dir() + "/" + PRESET_USER_DIR + "/" + user_sub_folder); } wxString GUI_App::filter_string(wxString str) diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index 0fd96ea557..f4b2d29692 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -23,6 +23,7 @@ #include "libslic3r/PresetBundle.hpp" #include "libslic3r_version.h" #include "slic3r/GUI/UserNotification.hpp" +#include "slic3r/Utils/CloudDeleteQueue.hpp" #include "slic3r/Utils/CloudProvider.hpp" #include "libslic3r/Point.hpp" @@ -330,7 +331,7 @@ private: Slic3r::UserManager* m_user_manager { nullptr }; Slic3r::TaskManager* m_task_manager { nullptr }; NetworkAgent* m_agent { nullptr }; - std::map need_delete_presets; // store setting ids of preset + CloudDeleteQueue m_cloud_delete_queue; // cloud deletes of synced presets, sent by the preset sync thread std::vector m_create_preset_blocked { false, false, false, false, false, false }; // excceed limit std::vector m_pending_conflict_setting_ids; // setting_id from the most recent 409 conflict bool m_networking_compatible { false }; @@ -709,13 +710,11 @@ public: bool checked_tab(Tab* tab); //BBS: add preset combox re-active logic void load_current_presets(bool active_preset_combox = false, bool check_printer_presets = true); - std::map &get_delete_cache_presets(); - std::map get_delete_cache_presets_lock(); void process_delete_presets(); void delete_preset_from_cloud(std::string setting_id, std::string preset_file_path); - void preset_deleted_from_cloud(std::string setting_id); void scan_orphaned_info_files(); - static std::string extract_setting_id_from_info(const std::string& info_file_path); + // Changes whenever the signed-in account whose presets are loaded changes. + uint64_t user_preset_session() const { return m_cloud_delete_queue.generation(); } wxString filter_string(wxString str); wxString current_language_code() const { return m_active_language_code.empty() && m_wxLocale ? m_wxLocale->GetCanonicalName() : m_active_language_code; } diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index f759812c89..c661958f15 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -7667,7 +7667,7 @@ bool Tab::select_preset( } } } - if (!current_preset.setting_id.empty()) { + if (current_preset.is_user() && !current_preset.setting_id.empty()) { wxGetApp().delete_preset_from_cloud(current_preset.setting_id, current_preset.file); } BOOST_LOG_TRIVIAL(info) << "delete preset = " << current_preset.name << ", setting_id = " << current_preset.setting_id; @@ -7775,13 +7775,20 @@ bool Tab::select_preset( } if (delete_third_printer) { - wxGetApp().CallAfter([filament_presets, process_presets]() { + // The presets were collected from the account loaded now. If another account's presets load + // before this runs, its same-named presets must not be deleted, nor these queued under it. + const uint64_t preset_session = wxGetApp().user_preset_session(); + wxGetApp().CallAfter([filament_presets, process_presets, preset_session]() { + if (wxGetApp().user_preset_session() != preset_session) { + BOOST_LOG_TRIVIAL(info) << "account changed before the presets of the deleted printer were removed; skipping"; + return; + } PresetBundle *preset_bundle = wxGetApp().preset_bundle; std::string old_filament_name = preset_bundle->filaments.get_edited_preset().name; std::string old_process_name = preset_bundle->prints.get_edited_preset().name; for (const Preset &preset : filament_presets) { - if (!preset.setting_id.empty()) { + if (preset.is_user() && !preset.setting_id.empty()) { wxGetApp().delete_preset_from_cloud(preset.setting_id, preset.file); } BOOST_LOG_TRIVIAL(info) << "delete filament preset = " << preset.name << ", setting_id = " << preset.setting_id; @@ -7789,7 +7796,7 @@ bool Tab::select_preset( } for (const Preset &preset : process_presets) { - if (!preset.setting_id.empty()) { + if (preset.is_user() && !preset.setting_id.empty()) { wxGetApp().delete_preset_from_cloud(preset.setting_id, preset.file); } BOOST_LOG_TRIVIAL(info) << "delete print preset = " << preset.name << ", setting_id = " << preset.setting_id; diff --git a/src/slic3r/Utils/CloudDeleteQueue.cpp b/src/slic3r/Utils/CloudDeleteQueue.cpp new file mode 100644 index 0000000000..b00ae40d70 --- /dev/null +++ b/src/slic3r/Utils/CloudDeleteQueue.cpp @@ -0,0 +1,199 @@ +#include "CloudDeleteQueue.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "libslic3r/InstanceLock.hpp" +#include "libslic3r/Preset.hpp" + +namespace Slic3r { + +namespace { + +CloudDeleteQueue::Clock::duration retry_wait(int failures) +{ + using namespace std::chrono_literals; + constexpr auto first = 1min; + constexpr auto longest = 60min; + // Capped before shifting, so a long run of failures can't overflow the shift. + const int doublings = std::min(failures - 1, 6); + return std::min(first * (1 << doublings), longest); +} + +// Value of one "key = value" line of a .info file, or "" when the key is missing. +std::string read_info_value(const std::string& info_file_path, const std::string& key) +{ + boost::nowide::ifstream file(info_file_path); + if (!file.is_open()) + return ""; + + std::string line; + while (std::getline(file, line)) { + const size_t pos = line.find('='); + if (pos == std::string::npos) + continue; + std::string name = line.substr(0, pos); + boost::algorithm::trim(name); + if (name != key) + continue; + std::string value = line.substr(pos + 1); + boost::algorithm::trim(value); + return value; + } + return ""; +} + +} // namespace + +void CloudDeleteQueue::start_session(const std::string& user_id) +{ + std::lock_guard lock(m_mutex); + if (user_id == m_user_id) + return; + m_user_id = user_id; + ++m_generation; + m_pending.clear(); +} + +uint64_t CloudDeleteQueue::generation() const +{ + std::lock_guard lock(m_mutex); + return m_generation; +} + +bool CloudDeleteQueue::is_current(uint64_t generation) const +{ + std::lock_guard lock(m_mutex); + return generation == m_generation; +} + +bool CloudDeleteQueue::add(uint64_t generation, const std::string& setting_id, const std::string& info_path, const std::string& owner) +{ + if (setting_id.empty()) + return false; + std::lock_guard lock(m_mutex); + if (generation != m_generation) + return false; + m_pending.try_emplace(setting_id, Pending{Entry{setting_id, info_path, owner.empty() ? m_user_id : owner}}); + return true; +} + +CloudDeleteQueue::Batch CloudDeleteQueue::due(Clock::time_point now) const +{ + std::lock_guard lock(m_mutex); + Batch batch{m_generation, {}}; + if (m_user_id.empty()) + return batch; + for (const auto& [setting_id, pending] : m_pending) + if (pending.entry.owner == m_user_id && pending.not_before <= now) + batch.entries.push_back(pending.entry); + return batch; +} + +std::optional CloudDeleteQueue::finish(uint64_t generation, const std::string& setting_id, bool gone, Clock::time_point now) +{ + std::lock_guard lock(m_mutex); + if (generation != m_generation) + return std::nullopt; + auto it = m_pending.find(setting_id); + if (it == m_pending.end()) + return std::nullopt; + if (gone) { + std::string info_path = std::move(it->second.entry.info_path); + m_pending.erase(it); + return info_path; + } + Pending& pending = it->second; + pending.not_before = now + retry_wait(++pending.failures); + return std::nullopt; +} + +void CloudDeleteQueue::send_due(const std::function& now, + const std::function& current_user, + const std::function& send, + const std::function& on_gone) +{ + const Batch batch = due(now()); + for (const Entry& entry : batch.entries) { + if (!is_current(batch.generation) || current_user() != entry.owner) + return; + const bool gone = send(entry); + if (current_user() != entry.owner) + return; + if (finish(batch.generation, entry.setting_id, gone, now())) + on_gone(entry); + } +} + +size_t CloudDeleteQueue::size() const +{ + std::lock_guard lock(m_mutex); + return m_pending.size(); +} + +bool queue_orphaned_info_files(CloudDeleteQueue& queue, uint64_t generation, const std::string& user_dir) +{ + namespace fs = boost::filesystem; + for (const char* type : {PRESET_PRINT_NAME, PRESET_FILAMENT_NAME, PRESET_PRINTER_NAME}) { + const fs::path type_dir = fs::path(user_dir) / type; + if (!fs::exists(type_dir)) + continue; + + // The error_code iterator logs and skips a transient directory-read failure (e.g. macOS readdir + // returning ENOTSUP) instead of throwing on the background sync thread this runs on. + boost::system::error_code ec; + for (fs::directory_iterator it(type_dir, ec), end; !ec && it != end; it.increment(ec)) { + const fs::path info_file = it->path(); + if (info_file.extension() != ".info") + continue; + fs::path preset_file = info_file; + preset_file.replace_extension(".json"); + + // Read under the lock, so a remove_files() in another instance is seen whole or not at all; + // the queue's own mutex is taken after the lock is released. + std::string setting_id; + std::string owner; + { + InstanceLock instance_lock(user_presets_lock_path()); + if (!fs::exists(preset_file)) { + setting_id = read_info_value(info_file.string(), "setting_id"); + owner = read_info_value(info_file.string(), "user_id"); + } + } + if (setting_id.empty()) + continue; + if (!queue.add(generation, setting_id, info_file.string(), owner)) { + BOOST_LOG_TRIVIAL(info) << "queue_orphaned_info_files: account changed, scan of " << user_dir << " abandoned"; + return false; + } + BOOST_LOG_TRIVIAL(info) << "Found orphaned .info file on startup: " << info_file.string(); + } + if (ec) + BOOST_LOG_TRIVIAL(warning) << "queue_orphaned_info_files: failed to scan " << type_dir.string() << ": " << ec.message(); + } + return true; +} + +void remove_info_file(const std::string& info_path) +{ + if (info_path.empty() || !boost::filesystem::exists(boost::filesystem::path(info_path))) + return; + InstanceLock instance_lock(user_presets_lock_path()); + boost::nowide::remove(info_path.c_str()); + BOOST_LOG_TRIVIAL(info) << "Deleted .info file after cloud confirmation: " << info_path; +} + +} // namespace Slic3r diff --git a/src/slic3r/Utils/CloudDeleteQueue.hpp b/src/slic3r/Utils/CloudDeleteQueue.hpp new file mode 100644 index 0000000000..d3e0eebc4a --- /dev/null +++ b/src/slic3r/Utils/CloudDeleteQueue.hpp @@ -0,0 +1,105 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +// Cloud preset deletes waiting to be sent. Deleting a synced preset in the UI and the scan for orphaned +// .info files add them; the preset sync thread sends them. +// +// Every entry belongs to an account, and the queue belongs to one session: the time one account stays +// signed in with its presets loaded. Starting another account's session drops every entry and changes the +// generation, so an entry is never sent with another account's token, an add that began in an earlier +// session is refused, and a response that arrives after the switch is ignored. Nothing is lost by the +// drop: each pending delete keeps its .info file, and the scan queues it again when its account next +// signs in. +// +// A failed delete stays queued and waits before its next attempt, one minute after the first failure and +// twice as long after each further one, up to an hour. +class CloudDeleteQueue +{ +public: + using Clock = std::chrono::steady_clock; + + struct Entry + { + std::string setting_id; + std::string info_path; // the deleted preset's .info file, removed once the cloud has no such profile + std::string owner; // user id of the account the delete belongs to + }; + + // What one sync pass sends: the due entries of the session's account, and the session they belong to. + struct Batch + { + uint64_t generation{0}; + std::vector entries; + }; + + // Starts the session of `user_id`, empty when signed out. Another account drops every entry and + // changes the generation; the account already signed in keeps both. + void start_session(const std::string& user_id); + + uint64_t generation() const; + bool is_current(uint64_t generation) const; + + // Queues a delete for `owner` unless the session changed since `generation` was read. An empty owner + // means the session's own account, the one whose presets are loaded. The check and the add are one + // step under the queue's lock. A setting_id already queued keeps its entry and its wait. Returns false + // when the delete was refused: an empty setting_id, or a session that has moved on. + bool add(uint64_t generation, const std::string& setting_id, const std::string& info_path, const std::string& owner); + + // The entries of the session's account whose wait is over. Entries of other accounts stay queued unsent. + Batch due(Clock::time_point now) const; + + // Records the result of sending `setting_id` in session `generation`. `gone` means the cloud holds no + // such profile for this account any more: the entry leaves the queue and its .info path is returned for + // removal. Otherwise the entry waits longer, counted from `now`. A response from an earlier session + // changes nothing and returns nothing. + std::optional finish(uint64_t generation, const std::string& setting_id, bool gone, Clock::time_point now); + + // One sync pass: sends the due deletes one at a time through `send`, which returns true when the cloud + // no longer has the profile, and hands each confirmed entry to `on_gone` once it has left the queue. + // `current_user` names the account whose token `send` uses. That token can change to another account + // just before the queue starts the new account's session, so before each request the pass checks that + // the session is unchanged and the token belongs to the entry's owner, and after it that the token + // still does; it stops at the first change. `now` times each result, so a long pass doesn't eat into + // the waits of the failures it records. + void send_due(const std::function& now, + const std::function& current_user, + const std::function& send, + const std::function& on_gone); + + size_t size() const; + +private: + struct Pending + { + Entry entry; + int failures{0}; + Clock::time_point not_before{}; + }; + + mutable std::mutex m_mutex; + std::string m_user_id; + uint64_t m_generation{0}; + std::map m_pending; // by setting_id +}; + +// Queues the delete recorded by each orphaned .info file under `user_dir`, the signed-in account's preset +// folder: a .info whose preset .json is gone marks a delete the cloud hasn't confirmed. The owner is the +// .info's user_id, or the session's account when it has none. Returns false when the session changed +// since `generation`, which ends the scan. +bool queue_orphaned_info_files(CloudDeleteQueue& queue, uint64_t generation, const std::string& user_dir); + +// Removes a confirmed delete's .info file, under the lock other instances take to edit user presets. +void remove_info_file(const std::string& info_path); + +} // namespace Slic3r diff --git a/src/slic3r/Utils/ICloudServiceAgent.hpp b/src/slic3r/Utils/ICloudServiceAgent.hpp index 1bcb4d370a..e51ea3e609 100644 --- a/src/slic3r/Utils/ICloudServiceAgent.hpp +++ b/src/slic3r/Utils/ICloudServiceAgent.hpp @@ -262,6 +262,8 @@ public: /** * Delete a remote preset. + * Returns 0 once the cloud holds no preset with this id for the signed-in account, whether this call + * deleted it or there was nothing to delete. Any other value means the delete should be tried again later. */ virtual int delete_setting(std::string setting_id) = 0; diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp index 69686d470e..1f62ebbbd9 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp @@ -1379,24 +1379,37 @@ int OrcaCloudServiceAgent::get_setting_list2(std::string bundle_version, CheckFn return success ? BAMBU_NETWORK_SUCCESS : BAMBU_NETWORK_ERR_GET_SETTING_LIST_FAILED; } -int OrcaCloudServiceAgent::delete_setting(std::string setting_id) +int OrcaCloudServiceAgent::delete_setting(std::string setting_id) { return delete_setting_as({}, setting_id); } + +int OrcaCloudServiceAgent::delete_setting_as(const std::string& user_id, const std::string& setting_id) { + // Cloud profiles are named by UUIDs. Any other id, such as a system preset's setting_id, names + // nothing in the cloud, so there is nothing to delete and no request to send. + if (!is_uuid(setting_id)) { + BOOST_LOG_TRIVIAL(info) << "OrcaCloudServiceAgent: delete_setting skipped, not a cloud profile id: " << setting_id; + return BAMBU_NETWORK_SUCCESS; + } + std::string path = std::string(ORCA_SYNC_DELETE_PATH) + "?resource=" + ORCA_SYNC_PROFILE_TABLE + "&id=" + setting_id; std::string response; unsigned int http_code = 0; - int result = http_delete(path, &response, &http_code); + http_delete(path, &response, &http_code, user_id); - // Treat 204 as success: the setting is already gone from cloud, which is our goal. - if (http_code == 204) { + // 200 deleted the profile and 204 says there was nothing to delete. A 404 is final only when the + // gateway itself answered it: {"status":"failed"} means this account owns no profile with this id. + // Anything else, a network failure included, is worth another attempt. + if (http_code == 200 || http_code == 204) return BAMBU_NETWORK_SUCCESS; + if (http_code == 404) { + const json body = json::parse(response, nullptr, false); + if (body.is_object()) { + const auto status = body.find("status"); + if (status != body.end() && status->is_string() && status->get() == "failed") + return BAMBU_NETWORK_SUCCESS; + } } - - if (result != BAMBU_NETWORK_SUCCESS || http_code >= 400) { - return BAMBU_NETWORK_ERR_DEL_SETTING_FAILED; - } - - return BAMBU_NETWORK_SUCCESS; + return BAMBU_NETWORK_ERR_DEL_SETTING_FAILED; } // ============================================================================ @@ -2395,21 +2408,31 @@ int OrcaCloudServiceAgent::http_put(const std::string& path, const std::string& return (res.success && !suppress) ? BAMBU_NETWORK_SUCCESS : BAMBU_NETWORK_ERR_CONNECT_FAILED; } -int OrcaCloudServiceAgent::http_delete(const std::string& path, std::string* response_body, unsigned int* http_code) +int OrcaCloudServiceAgent::http_delete(const std::string& path, std::string* response_body, unsigned int* http_code, const std::string& required_user_id) { std::string url = api_base_url + path; BOOST_LOG_TRIVIAL(trace) << "OrcaCloudServiceAgent: DELETE " << url; ensure_token_fresh("http_delete_" + path); + bool wrong_account = false; auto perform = [&]() { HttpResult result; try { + // The token and the account it belongs to are read together, so the check can't go stale + // before the token is used. + std::string token; + { + std::lock_guard lock(session_mutex); + wrong_account = !required_user_id.empty() && session.user_id != required_user_id; + token = session.access_token; + } + if (wrong_account) + return result; + auto http = Http::del(url); http.tls_verify(true); - std::string token = get_access_token(); - auto headers = data_headers(); for (const auto& pair : headers) { http.header(pair.first, pair.second); @@ -2425,8 +2448,9 @@ int OrcaCloudServiceAgent::http_delete(const std::string& path, std::string* res result.body = resp_body; }) .on_error([&](std::string resp_body, std::string error, unsigned resp_status) { + // A network failure keeps status 0, so callers can't mistake it for the server's 404. result.success = false; - result.status = resp_status == 0 ? 404 : resp_status; + result.status = resp_status; result.body = resp_body; BOOST_LOG_TRIVIAL(error) << "OrcaCloudServiceAgent: HTTP error - " << error; }) @@ -2447,6 +2471,11 @@ int OrcaCloudServiceAgent::http_delete(const std::string& path, std::string* res if (http_code) *http_code = res.status; + if (wrong_account) { + BOOST_LOG_TRIVIAL(info) << "OrcaCloudServiceAgent: DELETE " << path << " not sent, the session no longer belongs to the requesting account"; + return BAMBU_NETWORK_ERR_CONNECT_FAILED; + } + if (!suppress && (!res.success || res.status >= 400)) { invoke_http_error_callback(res.status, res.body); } @@ -3203,11 +3232,7 @@ bool OrcaCloudServiceAgent::unsubscribe_bundle(const std::string& bundle_id) unsigned int http_code = 0; int result = http_delete(path, &response, &http_code); - if (http_code >= 400) { - return false; - } - - return true; + return result == BAMBU_NETWORK_SUCCESS && http_code < 400; } std::string OrcaCloudServiceAgent::get_bundle_url(const std::string& bundle_id) const diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp index 524f24ced7..cc7619459c 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp @@ -253,6 +253,12 @@ public: int get_setting_list(std::string bundle_version, ProgressFn pro_fn = nullptr, WasCancelledFn cancel_fn = nullptr) override; int get_setting_list2(std::string bundle_version, CheckFn chk_fn, ProgressFn pro_fn = nullptr, WasCancelledFn cancel_fn = nullptr) override; int delete_setting(std::string setting_id) override; + // delete_setting() sent only with `user_id`'s token. A token refresh can load another account's + // session (another instance may have signed in as someone else), so the account is checked whenever + // the token is read, including for the retry after a 401. When the session belongs to another + // account nothing is sent, and the delete counts as failed, to be tried again. An empty user_id sends + // with the current session, as delete_setting() does. + int delete_setting_as(const std::string& user_id, const std::string& setting_id); // ======================================================================== // ICloudServiceAgent Interface Implementation - Cloud User Services @@ -405,7 +411,8 @@ private: int http_get(const std::string& path, std::string* response_body, unsigned int* http_code); int http_post(const std::string& path, const std::string& body, std::string* response_body, unsigned int* http_code); int http_put(const std::string& path, const std::string& body, std::string* response_body, unsigned int* http_code); - int http_delete(const std::string& path, std::string* response_body, unsigned int* http_code); + // A non-empty `required_user_id` sends the request only while the session belongs to that account. + int http_delete(const std::string& path, std::string* response_body, unsigned int* http_code, const std::string& required_user_id = {}); std::map data_headers(); RefreshResult attempt_refresh_after_unauthorized(const std::string& reason); diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 265314712f..a05426e05f 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -3,6 +3,7 @@ add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests_main.cpp test_bambu_filament_ids.cpp test_bed_exclusion_fields.cpp + test_cloud_delete_queue.cpp test_config_value_formatter.cpp test_creality_cfs_match.cpp test_creality_print.cpp diff --git a/tests/slic3rutils/test_cloud_delete_queue.cpp b/tests/slic3rutils/test_cloud_delete_queue.cpp new file mode 100644 index 0000000000..80e437314b --- /dev/null +++ b/tests/slic3rutils/test_cloud_delete_queue.cpp @@ -0,0 +1,339 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include "slic3r/Utils/CloudDeleteQueue.hpp" +#include "test_utils.hpp" + +using Slic3r::CloudDeleteQueue; +using namespace std::chrono_literals; + +namespace { + +const CloudDeleteQueue::Clock::time_point T0 = CloudDeleteQueue::Clock::time_point{} + 1000h; + +// Puts the queue in user A's session with one delete of A's queued. +void start_with_a_delete(CloudDeleteQueue& queue) +{ + queue.start_session("A"); + REQUIRE(queue.add(queue.generation(), "u1", "/a/filament/PETG.info", "A")); +} + +} // namespace + +TEST_CASE("A delete is sent only while its account is signed in", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + REQUIRE(queue.add(queue.generation(), "u2", "/a/filament/PLA.info", "B")); + + const CloudDeleteQueue::Batch batch = queue.due(T0); + REQUIRE(batch.entries.size() == 1); + CHECK(batch.entries[0].setting_id == "u1"); + CHECK(queue.size() == 2); +} + +TEST_CASE("Nothing is sent while signed out", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + queue.start_session(""); + REQUIRE(queue.add(queue.generation(), "u1", "/default/filament/PETG.info", "")); + CHECK(queue.due(T0).entries.empty()); +} + +TEST_CASE("Switching account drops pending deletes and starts a new generation", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + const uint64_t generation = queue.generation(); + + queue.start_session("B"); + + CHECK(queue.size() == 0); + CHECK(queue.generation() != generation); + CHECK(queue.due(T0).entries.empty()); +} + +TEST_CASE("Starting the signed-in account's session again keeps its pending deletes", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + const uint64_t generation = queue.generation(); + + queue.start_session("A"); + + CHECK(queue.size() == 1); + CHECK(queue.generation() == generation); +} + +TEST_CASE("An add that started before an account switch is refused", "[CloudDeleteQueue]") +{ + // A scan for A's orphaned .info files reads the generation, then the user switches to B before it adds. + CloudDeleteQueue queue; + queue.start_session("A"); + const uint64_t scan_generation = queue.generation(); + + queue.start_session("B"); + + CHECK_FALSE(queue.add(scan_generation, "u1", "/a/filament/PETG.info", "A")); + CHECK(queue.size() == 0); +} + +TEST_CASE("A response that arrives after an account switch is ignored", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + const CloudDeleteQueue::Batch batch = queue.due(T0); + + // Switched to B and back to A while the request was in flight; A's scan queued the delete again. + queue.start_session("B"); + queue.start_session("A"); + REQUIRE(queue.add(queue.generation(), "u1", "/a/filament/PETG.info", "A")); + + CHECK_FALSE(queue.is_current(batch.generation)); + CHECK_FALSE(queue.finish(batch.generation, "u1", true, T0).has_value()); + CHECK(queue.size() == 1); +} + +TEST_CASE("A delete the cloud confirms leaves the queue and hands back its info file", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + const CloudDeleteQueue::Batch batch = queue.due(T0); + + const std::optional info_path = queue.finish(batch.generation, "u1", true, T0); + + REQUIRE(info_path.has_value()); + CHECK(*info_path == "/a/filament/PETG.info"); + CHECK(queue.size() == 0); +} + +TEST_CASE("A failed delete waits one minute, then twice as long after each failure, up to an hour", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + const uint64_t generation = queue.generation(); + + auto now = T0; + for (const auto expected_wait : {1min, 2min, 4min, 8min, 16min, 32min, 60min, 60min}) { + CHECK_FALSE(queue.finish(generation, "u1", false, now).has_value()); + CHECK(queue.due(now + expected_wait - 1s).entries.empty()); + CHECK(queue.due(now + expected_wait).entries.size() == 1); + now += expected_wait; + } + CHECK(queue.size() == 1); +} + +TEST_CASE("Queueing a pending delete again keeps its wait", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + queue.finish(queue.generation(), "u1", false, T0); + + REQUIRE(queue.add(queue.generation(), "u1", "/a/filament/PETG.info", "A")); + + CHECK(queue.size() == 1); + CHECK(queue.due(T0 + 30s).entries.empty()); +} + +TEST_CASE("An empty setting id is never queued", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + queue.start_session("A"); + CHECK_FALSE(queue.add(queue.generation(), "", "/a/filament/PETG.info", "A")); + CHECK(queue.size() == 0); +} + +TEST_CASE("A pass sends the signed-in account's due deletes and hands back the confirmed ones", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + REQUIRE(queue.add(queue.generation(), "u2", "/a/filament/PLA.info", "A")); + REQUIRE(queue.add(queue.generation(), "u3", "/b/filament/ABS.info", "B")); + + std::vector sent; + std::vector removed; + queue.send_due( + [] { return T0; }, [] { return std::string("A"); }, + [&](const CloudDeleteQueue::Entry& entry) { + sent.push_back(entry.setting_id); + return entry.setting_id == "u1"; + }, + [&](const CloudDeleteQueue::Entry& entry) { removed.push_back(entry.info_path); }); + + CHECK(sent == std::vector{"u1", "u2"}); + CHECK(removed == std::vector{"/a/filament/PETG.info"}); + // u2 waits for its retry and u3 for B's session. + CHECK(queue.size() == 2); + CHECK(queue.due(T0).entries.empty()); +} + +TEST_CASE("A pass stops when the account changes during a request", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + REQUIRE(queue.add(queue.generation(), "u2", "/a/filament/PLA.info", "A")); + + std::vector sent; + bool confirmed = false; + queue.send_due( + [] { return T0; }, [] { return std::string("A"); }, + [&](const CloudDeleteQueue::Entry& entry) { + sent.push_back(entry.setting_id); + queue.start_session("B"); + return true; + }, + [&](const CloudDeleteQueue::Entry&) { confirmed = true; }); + + CHECK(sent == std::vector{"u1"}); + CHECK_FALSE(confirmed); +} + +TEST_CASE("A pass ignores an answer that came back after the token changed account", "[CloudDeleteQueue]") +{ + // The agent signed in as B before the queue started B's session. + CloudDeleteQueue queue; + start_with_a_delete(queue); + + std::string token_user = "A"; + bool confirmed = false; + queue.send_due( + [] { return T0; }, [&] { return token_user; }, + [&](const CloudDeleteQueue::Entry&) { + token_user = "B"; + return true; + }, + [&](const CloudDeleteQueue::Entry&) { confirmed = true; }); + + CHECK_FALSE(confirmed); + // Neither confirmed nor counted as a failure: the delete is still due for A. + CHECK(queue.due(T0).entries.size() == 1); +} + +TEST_CASE("A pass sends nothing while the token belongs to another account", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + + int requests = 0; + queue.send_due( + [] { return T0; }, [] { return std::string("B"); }, + [&](const CloudDeleteQueue::Entry&) { + ++requests; + return true; + }, + [](const CloudDeleteQueue::Entry&) {}); + + CHECK(requests == 0); + CHECK(queue.size() == 1); +} + +TEST_CASE("A pass rechecks the token's account before every request", "[CloudDeleteQueue]") +{ + // The agent signs in as B between two of A's requests, before the queue starts B's session. + CloudDeleteQueue queue; + start_with_a_delete(queue); + REQUIRE(queue.add(queue.generation(), "u2", "/a/filament/PLA.info", "A")); + + std::string token_user = "A"; + std::vector sent; + queue.send_due( + [] { return T0; }, [&] { return token_user; }, + [&](const CloudDeleteQueue::Entry& entry) { + sent.push_back(entry.setting_id); + return true; + }, + [&](const CloudDeleteQueue::Entry&) { token_user = "B"; }); + + CHECK(sent == std::vector{"u1"}); + CHECK(queue.size() == 1); +} + +TEST_CASE("A failure's wait counts from when its request finished", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + start_with_a_delete(queue); + + // The request takes ten minutes to fail. + auto clock = T0; + queue.send_due( + [&] { return clock; }, [] { return std::string("A"); }, + [&](const CloudDeleteQueue::Entry&) { + clock += 10min; + return false; + }, + [](const CloudDeleteQueue::Entry&) {}); + + CHECK(queue.due(T0 + 10min + 59s).entries.empty()); + CHECK(queue.due(T0 + 11min).entries.size() == 1); +} + +TEST_CASE("A delete without an owner belongs to the session's account", "[CloudDeleteQueue]") +{ + CloudDeleteQueue queue; + queue.start_session("A"); + REQUIRE(queue.add(queue.generation(), "u1", "/a/filament/PETG.info", "")); + + const CloudDeleteQueue::Batch batch = queue.due(T0); + REQUIRE(batch.entries.size() == 1); + CHECK(batch.entries[0].owner == "A"); +} + +namespace { + +void write_file(const boost::filesystem::path& path, const std::string& text) +{ + boost::filesystem::create_directories(path.parent_path()); + boost::filesystem::ofstream(path) << text; +} + +} // namespace + +TEST_CASE("A scan queues the delete each orphaned .info file records", "[CloudDeleteQueue]") +{ + ScopedTemporaryDir dir("orca-delete-scan"); + const auto user_dir = dir.path() / "user" / "A"; + // Deleted presets: their .json is gone and the .info stays until the cloud confirms. + write_file(user_dir / "filament" / "PETG.info", "sync_info = delete\nuser_id = A\nsetting_id = u1\n"); + write_file(user_dir / "process" / "Draft.info", "sync_info = delete\nsetting_id = u2\n"); + // A preset that still exists, and a .info with no setting_id. + write_file(user_dir / "filament" / "PLA.info", "user_id = A\nsetting_id = u3\n"); + write_file(user_dir / "filament" / "PLA.json", "{}"); + write_file(user_dir / "machine" / "Voron.info", "user_id = A\n"); + + CloudDeleteQueue queue; + queue.start_session("A"); + REQUIRE(queue_orphaned_info_files(queue, queue.generation(), user_dir.string())); + + const CloudDeleteQueue::Batch batch = queue.due(T0); + REQUIRE(batch.entries.size() == 2); + CHECK(batch.entries[0].setting_id == "u1"); + CHECK(batch.entries[0].info_path == (user_dir / "filament" / "PETG.info").string()); + // Without a user_id, the .info belongs to the account whose folder holds it. + CHECK(batch.entries[1].setting_id == "u2"); + CHECK(batch.entries[1].owner == "A"); +} + +TEST_CASE("A scan that started before an account switch queues nothing", "[CloudDeleteQueue]") +{ + ScopedTemporaryDir dir("orca-delete-scan"); + const auto user_dir = dir.path() / "user" / "A"; + write_file(user_dir / "filament" / "PETG.info", "user_id = A\nsetting_id = u1\n"); + + CloudDeleteQueue queue; + queue.start_session("A"); + const uint64_t scan_generation = queue.generation(); + queue.start_session("B"); + + CHECK_FALSE(queue_orphaned_info_files(queue, scan_generation, user_dir.string())); + CHECK(queue.size() == 0); +} diff --git a/tests/slic3rutils/test_orca_cloud_agent.cpp b/tests/slic3rutils/test_orca_cloud_agent.cpp index 709879a2b8..13bfb8b3c0 100644 --- a/tests/slic3rutils/test_orca_cloud_agent.cpp +++ b/tests/slic3rutils/test_orca_cloud_agent.cpp @@ -30,6 +30,8 @@ #include #include +#include +#include "slic3r/Utils/CloudDeleteQueue.hpp" #include "slic3r/Utils/ICloudServiceAgent.hpp" #include "slic3r/Utils/OrcaCloudServiceAgent.hpp" #include "slic3r/Utils/bambu_networking.hpp" @@ -94,8 +96,9 @@ class LoopbackServer { public: // Session answers every request with the body given to set_session_body(), as the token endpoint - // does, after 200 ms so the client is still waiting when the test makes its next call. - enum class Mode { Ok, Unavailable, Silent, Session }; + // does, after 200 ms so the client is still waiting when the test makes its next call. Reply answers + // at once with the status and body given to set_reply(). + enum class Mode { Ok, Unavailable, Silent, Session, Reply }; struct Request { @@ -123,6 +126,14 @@ public: m_session_body = std::move(body); } + // `status` is the status line after the HTTP version, e.g. "404 Not Found". + void set_reply(std::string status, std::string body) + { + std::lock_guard lock(m_mutex); + m_reply_status = std::move(status); + m_reply_body = std::move(body); + } + bool wait_for_accepts(size_t count, std::chrono::milliseconds timeout) { std::unique_lock lock(m_mutex); @@ -186,6 +197,10 @@ private: std::lock_guard lock(m_mutex); *response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + std::to_string(m_session_body.size()) + "\r\nConnection: close\r\n\r\n" + m_session_body; + } else if (mode == Mode::Reply) { + std::lock_guard lock(m_mutex); + *response = "HTTP/1.1 " + m_reply_status + "\r\nContent-Type: application/json\r\nContent-Length: " + + std::to_string(m_reply_body.size()) + "\r\nConnection: close\r\n\r\n" + m_reply_body; } else { *response = mode == Mode::Ok ? "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}" : @@ -220,6 +235,8 @@ private: std::vector m_requests; std::vector> m_connections; std::string m_session_body; + std::string m_reply_status; + std::string m_reply_body; }; // A JWT whose only claim is {"exp":4102444800} (2100-01-01); the agent reads nothing else from it. @@ -567,3 +584,198 @@ TEST_CASE_METHOD(HealthCheckFixture, "A token request made while start() refresh ++token_posts; CHECK(token_posts == 1); } + +namespace { + +// An Orca cloud profile id; the cloud names profiles by UUID. +constexpr const char* PROFILE_ID = "3f9c1d2e-8b7a-4c55-9e10-6a2b4c8d1f07"; + +// A loopback URL nothing listens on, so a request to it fails before any HTTP exchange. +std::string closed_port_url() +{ + boost::asio::io_context io; + tcp::acceptor acceptor(io, tcp::endpoint(boost::asio::ip::make_address("127.0.0.1"), 0)); + const unsigned short port = acceptor.local_endpoint().port(); + acceptor.close(); + return "http://127.0.0.1:" + std::to_string(port); +} + +} // namespace + +TEST_CASE_METHOD(HealthCheckFixture, "Deleting a profile succeeds once the cloud has no such profile", "[OrcaCloudServiceAgent]") +{ + // Deleted now, nothing to delete, or the gateway's own answer that this account owns no such profile. + const auto [status, body] = GENERATE(table({ + {"200 OK", R"({"status":"ok","deleted":["3f9c1d2e-8b7a-4c55-9e10-6a2b4c8d1f07"]})"}, + {"204 No Content", ""}, + {"404 Not Found", R"({"status":"failed","failed":["3f9c1d2e-8b7a-4c55-9e10-6a2b4c8d1f07"]})"}, + })); + server.set_mode(LoopbackServer::Mode::Reply); + server.set_reply(status, body); + + CHECK(agent->delete_setting(PROFILE_ID) == BAMBU_NETWORK_SUCCESS); + const auto requests = server.requests(); + REQUIRE(requests.size() == 1); + CHECK(boost::starts_with(requests[0].request_line, std::string("DELETE /api/v1/sync/delete?resource=profiles&id=") + PROFILE_ID)); +} + +TEST_CASE_METHOD(HealthCheckFixture, "Deleting a profile fails on any other answer, so it is tried again", "[OrcaCloudServiceAgent]") +{ + // A 404 the gateway didn't write, for example from a proxy, says nothing about the profile. + const auto [status, body] = GENERATE(table({ + {"404 Not Found", "Not Found"}, + {"400 Bad Request", R"({"error":"invalid_request"})"}, + {"500 Internal Server Error", ""}, + {"207 Multi-Status", R"({"status":"partial_failure"})"}, + // Malformed bodies and a status of the wrong type are retried, not fatal. + {"404 Not Found", R"({"status":null})"}, + {"404 Not Found", R"({"status":404})"}, + {"404 Not Found", R"({"status":)"}, + })); + server.set_mode(LoopbackServer::Mode::Reply); + server.set_reply(status, body); + + CHECK(agent->delete_setting(PROFILE_ID) != BAMBU_NETWORK_SUCCESS); +} + +TEST_CASE_METHOD(HealthCheckFixture, "Deleting an id that can't name a cloud profile succeeds without a request", "[OrcaCloudServiceAgent]") +{ + // A system preset's 16-character id, an older short one, and an empty id. + const std::string id = GENERATE(as{}, "RcBNzytWgwRrwXXz", "OGFSA04", ""); + + CHECK(agent->delete_setting(id) == BAMBU_NETWORK_SUCCESS); + CHECK(server.requests().empty()); +} + +TEST_CASE("A delete that can't reach the server fails and reports status 0, not 404", "[OrcaCloudServiceAgent]") +{ + ScopedEnvVar no_proxy{"no_proxy", "127.0.0.1"}; + ScopedTemporaryDir dir{"orca-delete"}; + CallbackLog log; + auto agent = make_file_backed_agent(dir.path()); + agent->set_api_base_url(closed_port_url()); + agent->set_on_http_error_fn([&log](CloudEvent, unsigned http_code, std::string) { log.add_http_error(http_code); }); + + CHECK(agent->delete_setting(PROFILE_ID) != BAMBU_NETWORK_SUCCESS); + CHECK(log.http_errors == std::vector{0}); +} + +TEST_CASE_METHOD(HealthCheckFixture, "A delete goes out only while the session belongs to its account", "[OrcaCloudServiceAgent]") +{ + REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); + server.set_mode(LoopbackServer::Mode::Reply); + server.set_reply("204 No Content", ""); + + CHECK(agent->delete_setting_as("B", PROFILE_ID) != BAMBU_NETWORK_SUCCESS); + CHECK(server.requests().empty()); + + CHECK(agent->delete_setting_as("A", PROFILE_ID) == BAMBU_NETWORK_SUCCESS); + CHECK(server.requests().size() == 1); +} + +TEST_CASE_METHOD(HealthCheckFixture, "A delete is not retried after a 401 when the refreshed session is another account's", "[OrcaCloudServiceAgent]") +{ + // A's session, whose stored refresh now yields B's session, as after another instance signed in as B. + REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"refresh_token", "refresh-a"}, {"user_id", "A"}}, false)); + LoopbackServer auth_server; + auth_server.set_session_body(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"refresh_token", "refresh-b"}, {"user_id", "B"}}.dump()); + auth_server.set_mode(LoopbackServer::Mode::Session); + agent->set_auth_base_url(auth_server.url()); + server.set_mode(LoopbackServer::Mode::Reply); + server.set_reply("401 Unauthorized", R"({"error":"unauthorized"})"); + + CHECK(agent->delete_setting_as("A", PROFILE_ID) != BAMBU_NETWORK_SUCCESS); + CHECK(server.requests().size() == 1); + CHECK(agent->get_user_id() == "B"); +} + +TEST_CASE_METHOD(HealthCheckFixture, "Unsubscribing a bundle succeeds only on a 2xx answer", "[OrcaCloudServiceAgent]") +{ + const auto [status, expected] = GENERATE(table({ + {"200 OK", true}, + {"204 No Content", true}, + {"404 Not Found", false}, + {"500 Internal Server Error", false}, + })); + server.set_mode(LoopbackServer::Mode::Reply); + server.set_reply(status, ""); + + CHECK(agent->unsubscribe_bundle("bundle-1") == expected); +} + +TEST_CASE("Unsubscribing a bundle fails when the server can't be reached", "[OrcaCloudServiceAgent]") +{ + ScopedEnvVar no_proxy{"no_proxy", "127.0.0.1"}; + ScopedTemporaryDir dir{"orca-unsubscribe"}; + auto agent = make_file_backed_agent(dir.path()); + agent->set_api_base_url(closed_port_url()); + + CHECK_FALSE(agent->unsubscribe_bundle("bundle-1")); +} + +namespace { + +// A signed-in account's preset folder holding one deleted preset's .info file, and the queue it scans into. +struct DeletedPresetFixture : HealthCheckFixture +{ + explicit DeletedPresetFixture(const std::string& setting_id) + { + fs::create_directories(info_path.parent_path()); + fs::ofstream(info_path) << "sync_info = delete\nuser_id = A\nsetting_id = " << setting_id << "\n"; + queue.start_session("A"); + } + + // One sync start: the orphaned-.info scan, then a pass through the agent. + void sync() + { + REQUIRE(queue_orphaned_info_files(queue, queue.generation(), user_dir.string())); + queue.send_due( + [] { return CloudDeleteQueue::Clock::now(); }, [] { return std::string("A"); }, + [this](const CloudDeleteQueue::Entry& entry) { return agent->delete_setting(entry.setting_id) == BAMBU_NETWORK_SUCCESS; }, + [](const CloudDeleteQueue::Entry& entry) { remove_info_file(entry.info_path); }); + } + + ScopedTemporaryDir presets{"orca-deleted-preset"}; + fs::path user_dir = presets.path() / "user" / "A"; + fs::path info_path = user_dir / "filament" / "PETG Fast.info"; + CloudDeleteQueue queue; +}; + +} // namespace + +TEST_CASE("A delete for an id that can't name a cloud profile is dropped with its .info", "[OrcaCloudServiceAgent]") +{ + // A system preset's id, queued by a printer delete in an earlier version. + DeletedPresetFixture fixture("RcBNzytWgwRrwXXz"); + + fixture.sync(); + + CHECK(fixture.server.requests().empty()); + CHECK_FALSE(fs::exists(fixture.info_path)); + CHECK(fixture.queue.size() == 0); +} + +TEST_CASE("A delete the gateway answers with a verified 404 is not sent again", "[OrcaCloudServiceAgent]") +{ + DeletedPresetFixture fixture(PROFILE_ID); + fixture.server.set_mode(LoopbackServer::Mode::Reply); + fixture.server.set_reply("404 Not Found", R"({"status":"failed","failed":["3f9c1d2e-8b7a-4c55-9e10-6a2b4c8d1f07"]})"); + + fixture.sync(); + fixture.sync(); + + CHECK(fixture.server.requests().size() == 1); + CHECK_FALSE(fs::exists(fixture.info_path)); + CHECK(fixture.queue.size() == 0); +} + +TEST_CASE("A delete that fails to reach the gateway keeps its .info for a later attempt", "[OrcaCloudServiceAgent]") +{ + DeletedPresetFixture fixture(PROFILE_ID); + fixture.agent->set_api_base_url(closed_port_url()); + + fixture.sync(); + + CHECK(fs::exists(fixture.info_path)); + CHECK(fixture.queue.size() == 1); +}