diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 8bddfabf81..ccc197bfba 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -3250,6 +3250,8 @@ bool PresetCollection::clone_presets(std::vector const &presets, preset.is_external = false; preset.is_visible = true; preset.is_project_embedded = false; + // A clone is the user's own preset, even when it was made from a bundle's. + preset.bundle_id.clear(); modifier(preset, m_type); if (find_preset(preset.name) && !force_rewritten) { failures.push_back(preset.name); @@ -3343,6 +3345,21 @@ std::vector PresetCollection::get_user_presets_for_printer(const [&printer_name](const std::string &name) { return name == printer_name; })) presets.push_back(&preset); } + // A preset that a kept preset inherits from is kept too, since a preset whose parent is gone fails to + // load. Each one kept can in turn keep its own parent, so this repeats until nothing changes. + for (bool kept_one = true; kept_one;) { + kept_one = false; + for (const Preset &preset : m_presets) { + if (preset.inherits().empty() || std::find(presets.begin(), presets.end(), &preset) != presets.end()) + continue; + auto parent = std::find_if(presets.begin(), presets.end(), + [&preset](const Preset *candidate) { return candidate->name == preset.inherits(); }); + if (parent != presets.end()) { + presets.erase(parent); + kept_one = true; + } + } + } return presets; } diff --git a/src/libslic3r/Preset.hpp b/src/libslic3r/Preset.hpp index 21f71b315f..58a57895b7 100644 --- a/src/libslic3r/Preset.hpp +++ b/src/libslic3r/Preset.hpp @@ -661,7 +661,8 @@ public: // User presets made for one printer alone, as clone_presets_for_printer() makes them: every entry of // their compatible_printers is that printer. They are deleted together with that printer. Presets - // that also list other printers, or are not limited by printer name, are shared and kept. + // that also list other printers, or are not limited by printer name, are shared and kept, and so is + // every preset a kept preset inherits from. std::vector get_user_presets_for_printer(const std::string &printer_name) const; std::map> get_filament_presets() const; diff --git a/src/slic3r/GUI/CreatePresetsDialog.cpp b/src/slic3r/GUI/CreatePresetsDialog.cpp index 4906169a25..b25d81a3b7 100644 --- a/src/slic3r/GUI/CreatePresetsDialog.cpp +++ b/src/slic3r/GUI/CreatePresetsDialog.cpp @@ -307,7 +307,7 @@ static bool delete_filament_preset_by_name(std::string delete_preset_name, std:: if (!need_delete_preset) BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(" can't find delete preset and name: %1%") % delete_preset_name; if (!need_delete_preset->setting_id.empty()) { BOOST_LOG_TRIVIAL(info) << "delete preset = " << need_delete_preset->name << ", setting_id = " << need_delete_preset->setting_id; - wxGetApp().delete_preset_from_cloud(need_delete_preset->setting_id, need_delete_preset->file); + wxGetApp().delete_preset_from_cloud(*need_delete_preset); } else { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(" can't preset setting id is empty and name: %1%") % delete_preset_name; } diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 022ad55ea2..55c187c060 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -9490,31 +9490,24 @@ void GUI_App::load_current_presets(bool active_preset_combox/*= false*/, bool ch // Sends the due cloud deletes of the signed-in account. Runs on the preset sync thread. void GUI_App::process_delete_presets() { - if (!m_agent) + const auto orca = get_orca_cloud_agent(m_agent); + if (!orca) 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 = " << entry.setting_id; - }); + send_cloud_deletes(m_cloud_delete_queue, *orca, [this](const CloudDeleteQueue::Entry& entry) { + m_create_preset_blocked = { false, false, false, false, false, false }; + BOOST_LOG_TRIVIAL(trace) << "sync_preset: sync operation: delete success! setting id = " << entry.setting_id; + }); } -void GUI_App::delete_preset_from_cloud(std::string setting_id, std::string preset_file_path) +void GUI_App::delete_preset_from_cloud(const Preset& preset) { - fs::path info_path = fs::path(preset_file_path); + // System, bundle and project presets, and user presets never uploaded, name no cloud profile of this account. + if (!preset.is_user() || preset.setting_id.empty()) + return; + fs::path info_path = fs::path(preset.file); info_path.replace_extension("info"); // No owner given: the delete belongs to the session's account, whose presets the UI shows. - m_cloud_delete_queue.add(m_cloud_delete_queue.generation(), setting_id, info_path.string(), {}); + m_cloud_delete_queue.add(m_cloud_delete_queue.generation(), preset.setting_id, info_path.string(), {}); } // Scan for orphaned .info files on startup diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index f4b2d29692..c31ea990a0 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -711,7 +711,8 @@ public: //BBS: add preset combox re-active logic void load_current_presets(bool active_preset_combox = false, bool check_printer_presets = true); void process_delete_presets(); - void delete_preset_from_cloud(std::string setting_id, std::string preset_file_path); + // Queues the cloud delete of a user preset synced to the signed-in account; any other preset is ignored. + void delete_preset_from_cloud(const Preset& preset); void scan_orphaned_info_files(); // Changes whenever the signed-in account whose presets are loaded changes. uint64_t user_preset_session() const { return m_cloud_delete_queue.generation(); } diff --git a/src/slic3r/GUI/SavePresetDialog.cpp b/src/slic3r/GUI/SavePresetDialog.cpp index ef671cfcb2..a42994db26 100644 --- a/src/slic3r/GUI/SavePresetDialog.cpp +++ b/src/slic3r/GUI/SavePresetDialog.cpp @@ -349,7 +349,7 @@ void SavePresetDialog::Item::accept() Preset ¤t_preset = *it; if (!current_preset.setting_id.empty()) { BOOST_LOG_TRIVIAL(info) << "delete preset = " << current_preset.name << ", setting_id = " << current_preset.setting_id; - wxGetApp().delete_preset_from_cloud(current_preset.setting_id, current_preset.file); + wxGetApp().delete_preset_from_cloud(current_preset); } m_presets->delete_preset(m_preset_name); } diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 5d2d101b2d..c476dd5877 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -7650,22 +7650,18 @@ bool Tab::select_preset( // A custom printer takes the filament and process presets made for it alone with it if (m_preset_bundle && m_presets->get_preset_base(current_preset) == ¤t_preset && printer_tab && !current_preset.is_system && !current_preset.is_from_bundle()) { delete_third_printer = true; - for (const Preset *preset : m_preset_bundle->filaments.get_user_presets_for_printer(current_preset.name)) { - if (preset->inherits() != "") - filament_presets.push_front(*preset); - else - filament_presets.push_back(*preset); - } - for (const Preset *preset : m_preset_bundle->prints.get_user_presets_for_printer(current_preset.name)) { - if (preset->inherits() != "") - process_presets.push_front(*preset); - else - process_presets.push_back(*preset); - } - } - if (current_preset.is_user() && !current_preset.setting_id.empty()) { - wxGetApp().delete_preset_from_cloud(current_preset.setting_id, current_preset.file); + auto collect = [¤t_preset](const PresetCollection &presets, std::deque &collected) { + for (const Preset *preset : presets.get_user_presets_for_printer(current_preset.name)) { + if (preset->inherits() != "") + collected.push_front(*preset); + else + collected.push_back(*preset); + } + }; + collect(m_preset_bundle->filaments, filament_presets); + collect(m_preset_bundle->prints, process_presets); } + wxGetApp().delete_preset_from_cloud(current_preset); BOOST_LOG_TRIVIAL(info) << "delete preset = " << current_preset.name << ", setting_id = " << current_preset.setting_id; BOOST_LOG_TRIVIAL(info) << boost::format("will delete current preset..."); m_presets->delete_current_preset(); @@ -7784,17 +7780,13 @@ bool Tab::select_preset( std::string old_process_name = preset_bundle->prints.get_edited_preset().name; for (const Preset &preset : filament_presets) { - if (preset.is_user() && !preset.setting_id.empty()) { - wxGetApp().delete_preset_from_cloud(preset.setting_id, preset.file); - } + wxGetApp().delete_preset_from_cloud(preset); BOOST_LOG_TRIVIAL(info) << "delete filament preset = " << preset.name << ", setting_id = " << preset.setting_id; preset_bundle->filaments.delete_preset(preset.name); } for (const Preset &preset : process_presets) { - if (preset.is_user() && !preset.setting_id.empty()) { - wxGetApp().delete_preset_from_cloud(preset.setting_id, preset.file); - } + wxGetApp().delete_preset_from_cloud(preset); BOOST_LOG_TRIVIAL(info) << "delete print preset = " << preset.name << ", setting_id = " << preset.setting_id; preset_bundle->prints.delete_preset(preset.name); } diff --git a/src/slic3r/Utils/CloudDeleteQueue.cpp b/src/slic3r/Utils/CloudDeleteQueue.cpp index dedf25765e..51c5eed5b2 100644 --- a/src/slic3r/Utils/CloudDeleteQueue.cpp +++ b/src/slic3r/Utils/CloudDeleteQueue.cpp @@ -9,18 +9,19 @@ #include #include #include +#include -#include #include #include #include #include #include -#include #include #include "libslic3r/InstanceLock.hpp" #include "libslic3r/Preset.hpp" +#include "OrcaCloudServiceAgent.hpp" +#include "bambu_networking.hpp" namespace Slic3r { @@ -36,29 +37,6 @@ CloudDeleteQueue::Clock::duration retry_wait(int failures) 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) @@ -150,8 +128,13 @@ size_t CloudDeleteQueue::size() const bool queue_orphaned_info_files(CloudDeleteQueue& queue, uint64_t generation, const std::string& user_dir) { namespace fs = boost::filesystem; + std::vector preset_dirs; for (const char* type : {PRESET_PRINT_NAME, PRESET_FILAMENT_NAME, PRESET_PRINTER_NAME}) { - const fs::path type_dir = fs::path(user_dir) / type; + preset_dirs.push_back(fs::path(user_dir) / type); + // Presets with no parent, custom printers and the presets made for them among them, are kept in base/. + preset_dirs.push_back(fs::path(user_dir) / type / "base"); + } + for (const fs::path& type_dir : preset_dirs) { if (!fs::exists(type_dir)) continue; @@ -164,21 +147,21 @@ bool queue_orphaned_info_files(CloudDeleteQueue& queue, uint64_t generation, con continue; fs::path preset_file = info_file; preset_file.replace_extension(".json"); + // Most .info files sit beside their preset; only the rest are read, and only those need the lock. + if (fs::exists(preset_file)) + continue; // 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; + Preset info(Preset::TYPE_INVALID, ""); { 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 (!fs::exists(preset_file)) + info.load_info(info_file.string()); } - if (setting_id.empty()) + if (info.setting_id.empty()) continue; - if (!queue.add(generation, setting_id, info_file.string(), owner)) { + if (!queue.add(generation, info.setting_id, info_file.string(), info.user_id)) { BOOST_LOG_TRIVIAL(info) << "queue_orphaned_info_files: account changed, scan of " << user_dir << " abandoned"; return false; } @@ -199,4 +182,24 @@ void remove_info_file(const std::string& info_path) BOOST_LOG_TRIVIAL(info) << "Deleted .info file after cloud confirmation: " << info_path; } +void send_cloud_deletes(CloudDeleteQueue& queue, + OrcaCloudServiceAgent& agent, + const std::function& on_gone) +{ + queue.send_due( + [] { return CloudDeleteQueue::Clock::now(); }, [&agent] { return agent.get_user_id(); }, + [&agent](const CloudDeleteQueue::Entry& entry) { + const bool gone = agent.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; + }, + [&on_gone](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); + if (on_gone) + on_gone(entry); + }); +} + } // namespace Slic3r diff --git a/src/slic3r/Utils/CloudDeleteQueue.hpp b/src/slic3r/Utils/CloudDeleteQueue.hpp index d3e0eebc4a..4587497f66 100644 --- a/src/slic3r/Utils/CloudDeleteQueue.hpp +++ b/src/slic3r/Utils/CloudDeleteQueue.hpp @@ -12,6 +12,8 @@ namespace Slic3r { +class OrcaCloudServiceAgent; + // 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. // @@ -102,4 +104,11 @@ bool queue_orphaned_info_files(CloudDeleteQueue& queue, uint64_t generation, con // 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); +// One pass of `queue` through `agent`: sends the signed-in account's due deletes, each only with its +// owner's token, and removes the .info file of every delete the cloud confirms before handing the entry +// to `on_gone`. +void send_cloud_deletes(CloudDeleteQueue& queue, + OrcaCloudServiceAgent& agent, + const std::function& on_gone = {}); + } // namespace Slic3r diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp index b6f254fb7a..8c9afbf224 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp @@ -1419,14 +1419,8 @@ int OrcaCloudServiceAgent::delete_setting_as(const std::string& user_id, const s // 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 (http_code == 404 && get_json_string_field(json::parse(response, nullptr, false), "status") == "failed") + return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_ERR_DEL_SETTING_FAILED; } @@ -2271,8 +2265,11 @@ int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* respon if (!if_none_match.empty()) http.header("If-None-Match", if_none_match); + // The callback runs once per header line with every header received so far, so only the + // last call's headers are kept and read. + std::string received_headers; if (etag != nullptr) - http.on_header_callback([&result](std::string received) { result.etag = etag_from_headers(received); }); + http.on_header_callback([&received_headers](std::string received) { received_headers = std::move(received); }); http.on_complete([&](std::string body, unsigned resp_status) { result.success = true; @@ -2287,6 +2284,8 @@ int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* respon }) .timeout_max(30) .perform_sync(); + if (etag != nullptr) + result.etag = etag_from_headers(received_headers); } catch (const std::exception& e) { BOOST_LOG_TRIVIAL(error) << "OrcaCloudServiceAgent: http_get exception - " << e.what(); @@ -3261,8 +3260,7 @@ bool OrcaCloudServiceAgent::unsubscribe_bundle(const std::string& bundle_id) std::string response; unsigned int http_code = 0; - int result = http_delete(path, &response, &http_code); - return result == BAMBU_NETWORK_SUCCESS && http_code < 400; + return http_delete(path, &response, &http_code) == BAMBU_NETWORK_SUCCESS; } std::string OrcaCloudServiceAgent::get_bundle_url(const std::string& bundle_id) const diff --git a/tests/libslic3r/test_preset_bundle_loading.cpp b/tests/libslic3r/test_preset_bundle_loading.cpp index bc540d05e8..62161b3219 100644 --- a/tests/libslic3r/test_preset_bundle_loading.cpp +++ b/tests/libslic3r/test_preset_bundle_loading.cpp @@ -1269,6 +1269,48 @@ TEST_CASE("A printer's own presets are the user presets made for it alone", "[Pr CHECK(names_for("Unknown Printer").empty()); } +TEST_CASE("A printer's own preset stays while a kept preset inherits from it", "[Preset]") +{ + PresetCollection filaments(Preset::TYPE_FILAMENT, Preset::filament_options(), + static_cast(FullPrintConfig::defaults())); + auto add = [&filaments](const std::string &name, const std::string &inherits, std::vector compatible_printers) { + add_inmemory_preset(filaments, name, inherits).config.option("compatible_printers", true)->values = + std::move(compatible_printers); + }; + // Root <- Middle <- Shared: Shared also lists another printer, so it is kept along with its parents. + add("Root", "", {"My Printer"}); + add("Middle", "Root", {"My Printer"}); + add("Shared", "Middle", {"My Printer", "Other Printer"}); + // Alone <- Child: both are made for the printer alone, so both go with it. + add("Alone", "", {"My Printer"}); + add("Child", "Alone", {"My Printer"}); + + std::vector names; + for (const Preset *preset : filaments.get_user_presets_for_printer("My Printer")) + names.push_back(preset->name); + CHECK(names == std::vector{"Alone", "Child"}); +} + +TEST_CASE("A preset cloned from a bundle's for a new printer is the user's own", "[Preset]") +{ + ScopedTemporaryDir temp_dir; + PresetCollection filaments(Preset::TYPE_FILAMENT, Preset::filament_options(), + static_cast(FullPrintConfig::defaults())); + PresetsConfigSubstitutions substitutions; + filaments.load_presets(temp_dir.path().string(), PRESET_FILAMENT_NAME, substitutions, ForwardCompatibilitySubstitutionRule::Disable); + boost::filesystem::create_directories(temp_dir.path() / PRESET_FILAMENT_NAME / "base"); + add_inmemory_preset(filaments, "Bundle PLA @Template").bundle_id = "bundle"; + + std::vector failures; + REQUIRE(filaments.clone_presets_for_printer({filaments.find_preset("Bundle PLA @Template")}, failures, "My Printer", + [](const std::string &) { return std::string("GFU01"); })); + + const std::vector own = filaments.get_user_presets_for_printer("My Printer"); + REQUIRE(own.size() == 1); + CHECK(own[0]->name == "Bundle PLA @My Printer"); + CHECK(own[0]->is_user()); +} + TEST_CASE("Renamed parent is normalized into a loaded preset's inherits", "[Preset][Rename]") { ScopedTemporaryDir temp_dir; diff --git a/tests/slic3rutils/test_cloud_delete_queue.cpp b/tests/slic3rutils/test_cloud_delete_queue.cpp index 80e437314b..168244554d 100644 --- a/tests/slic3rutils/test_cloud_delete_queue.cpp +++ b/tests/slic3rutils/test_cloud_delete_queue.cpp @@ -305,22 +305,27 @@ TEST_CASE("A scan queues the delete each orphaned .info file records", "[CloudDe // 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. + // A custom printer, which as a preset with no parent is kept in base/. + write_file(user_dir / "machine" / "base" / "My Printer.info", "sync_info = delete\nuser_id = A\nsetting_id = u4\n"); + // A preset that still exists, and .info files with no setting_id or the "null" one older versions wrote. 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"); + write_file(user_dir / "machine" / "Ender.info", "user_id = A\nsetting_id = null\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); + REQUIRE(batch.entries.size() == 3); 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"); + CHECK(batch.entries[2].setting_id == "u4"); + CHECK(batch.entries[2].info_path == (user_dir / "machine" / "base" / "My Printer.info").string()); } TEST_CASE("A scan that started before an account switch queues nothing", "[CloudDeleteQueue]") diff --git a/tests/slic3rutils/test_orca_cloud_agent.cpp b/tests/slic3rutils/test_orca_cloud_agent.cpp index 0a655c21d4..5f70d8c62a 100644 --- a/tests/slic3rutils/test_orca_cloud_agent.cpp +++ b/tests/slic3rutils/test_orca_cloud_agent.cpp @@ -128,14 +128,17 @@ public: m_session_body = std::move(body); } - // `status` is the status line after the HTTP version, e.g. "404 Not Found". An empty `etag` sends - // no ETag header. + // Switches to Reply mode. `status` is the status line after the HTTP version, e.g. "404 Not Found". + // An empty `etag` sends no ETag header. void set_reply(std::string status, std::string body, std::string etag = {}) { - std::lock_guard lock(m_mutex); - m_reply_status = std::move(status); - m_reply_body = std::move(body); - m_reply_etag = std::move(etag); + { + std::lock_guard lock(m_mutex); + m_reply_status = std::move(status); + m_reply_body = std::move(body); + m_reply_etag = std::move(etag); + } + m_mode = Mode::Reply; } bool wait_for_accepts(size_t count, std::chrono::milliseconds timeout) @@ -316,6 +319,12 @@ struct HealthCheckFixture // Defers callbacks the way the GUI's CallAfter does, instead of running them on the worker. void queue_callbacks() { agent->set_queue_on_main_fn([this](std::function task) { log.add_queued(std::move(task)); }); } + // Signs `user_id` in with an access token that doesn't expire, so no refresh is attempted. + void sign_in(const std::string& user_id) + { + REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", user_id}}, false)); + } + // Starts the next health check, retrying while a call is still folded into the previous one: // its callback fires before the worker thread finishes. bool start_check(size_t expected_accepts) @@ -619,7 +628,6 @@ TEST_CASE_METHOD(HealthCheckFixture, "Deleting a profile succeeds once the cloud {"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); @@ -641,7 +649,6 @@ TEST_CASE_METHOD(HealthCheckFixture, "Deleting a profile fails on any other answ {"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); @@ -656,14 +663,9 @@ TEST_CASE_METHOD(HealthCheckFixture, "Deleting an id that can't name a cloud pro CHECK(server.requests().empty()); } -TEST_CASE("A delete that can't reach the server fails and reports status 0, not 404", "[OrcaCloudServiceAgent]") +TEST_CASE_METHOD(HealthCheckFixture, "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}); @@ -671,8 +673,7 @@ TEST_CASE("A delete that can't reach the server fails and reports status 0, not 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); + sign_in("A"); server.set_reply("204 No Content", ""); CHECK(agent->delete_setting_as("B", PROFILE_ID) != BAMBU_NETWORK_SUCCESS); @@ -690,7 +691,6 @@ TEST_CASE_METHOD(HealthCheckFixture, "A delete is not retried after a 401 when t 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); @@ -706,17 +706,13 @@ TEST_CASE_METHOD(HealthCheckFixture, "Unsubscribing a bundle succeeds only on a {"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]") +TEST_CASE_METHOD(HealthCheckFixture, "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")); @@ -746,8 +742,7 @@ SubscriptionPoll poll_subscriptions(OrcaCloudServiceAgent& agent) TEST_CASE_METHOD(HealthCheckFixture, "A subscription poll answered 304 returns the list received last", "[OrcaCloudServiceAgent]") { - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); - server.set_mode(LoopbackServer::Mode::Reply); + sign_in("A"); server.set_reply("200 OK", SUBSCRIPTIONS_V1, R"(W/"v1")"); const SubscriptionPoll first = poll_subscriptions(*agent); REQUIRE(first.result == 0); @@ -769,8 +764,7 @@ TEST_CASE_METHOD(HealthCheckFixture, "A subscription poll answered 304 returns t TEST_CASE_METHOD(HealthCheckFixture, "A changed subscription list replaces the one received before", "[OrcaCloudServiceAgent]") { - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); - server.set_mode(LoopbackServer::Mode::Reply); + sign_in("A"); server.set_reply("200 OK", SUBSCRIPTIONS_V1, R"(W/"v1")"); REQUIRE(poll_subscriptions(*agent).result == 0); @@ -788,19 +782,18 @@ TEST_CASE_METHOD(HealthCheckFixture, "A changed subscription list replaces the o TEST_CASE_METHOD(HealthCheckFixture, "A subscription list is revalidated only for the account that received it", "[OrcaCloudServiceAgent]") { - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); - server.set_mode(LoopbackServer::Mode::Reply); + sign_in("A"); server.set_reply("200 OK", SUBSCRIPTIONS_V1, R"(W/"v1")"); REQUIRE(poll_subscriptions(*agent).result == 0); SECTION("another account signs in") { - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "B"}}, false)); + sign_in("B"); } SECTION("the account signs out and back in") { agent->user_logout(false); - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); + sign_in("A"); } server.set_reply("200 OK", SUBSCRIPTIONS_V2, R"(W/"v2")"); @@ -812,8 +805,7 @@ TEST_CASE_METHOD(HealthCheckFixture, "A subscription list is revalidated only fo TEST_CASE_METHOD(HealthCheckFixture, "A 304 for a subscription list never received fails", "[OrcaCloudServiceAgent]") { - REQUIRE(agent->set_user_session(nlohmann::json{{"access_token", FAR_FUTURE_JWT}, {"user_id", "A"}}, false)); - server.set_mode(LoopbackServer::Mode::Reply); + sign_in("A"); server.set_reply("304 Not Modified", "", R"(W/"v1")"); const SubscriptionPoll poll = poll_subscriptions(*agent); @@ -830,6 +822,7 @@ struct DeletedPresetFixture : HealthCheckFixture { fs::create_directories(info_path.parent_path()); fs::ofstream(info_path) << "sync_info = delete\nuser_id = A\nsetting_id = " << setting_id << "\n"; + sign_in("A"); queue.start_session("A"); } @@ -837,10 +830,7 @@ struct DeletedPresetFixture : HealthCheckFixture 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); }); + send_cloud_deletes(queue, *agent); } ScopedTemporaryDir presets{"orca-deleted-preset"}; @@ -866,7 +856,6 @@ TEST_CASE("A delete for an id that can't name a cloud profile is dropped with it 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();