diff --git a/src/slic3r/Utils/Http.cpp b/src/slic3r/Utils/Http.cpp index c09c22fe3f..20156614e7 100644 --- a/src/slic3r/Utils/Http.cpp +++ b/src/slic3r/Utils/Http.cpp @@ -521,7 +521,8 @@ void Http::priv::http_perform() ::curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_status); //BBS check success http status code - if (http_status >= 200 && http_status < 300) { + // A 304 answers a conditional request (If-None-Match): the caller's copy is still current. + if ((http_status >= 200 && http_status < 300) || http_status == 304) { if (completefn) { completefn(std::move(buffer), http_status); } if (ipresolvefn) { char* ct; diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp index 1f62ebbbd9..b6f254fb7a 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.cpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.cpp @@ -9,6 +9,8 @@ #include "libslic3r/AppConfig.hpp" #include +#include +#include #include #include #include @@ -507,6 +509,22 @@ bool aes256gcm_decrypt(const std::string& b64_payload, const std::vector lock(session_mutex); session = SessionInfo{}; } + { + std::lock_guard lock(subscriptions_cache_mutex); + subscriptions_cache = SubscriptionsCache{}; + } clear_user_secret(all_backends); } @@ -2221,7 +2243,8 @@ bool OrcaCloudServiceAgent::resolve_unauthorized(HttpResult& res, return rr == RefreshResult::Transient; } -int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* response_body, unsigned int* http_code) +int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* response_body, unsigned int* http_code, + const std::string& if_none_match, std::string* etag) { std::string url = api_base_url + path; BOOST_LOG_TRIVIAL(trace) << "OrcaCloudServiceAgent: GET " << url; @@ -2246,6 +2269,11 @@ int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* respon http.header("Authorization", "Bearer " + token); } + if (!if_none_match.empty()) + http.header("If-None-Match", if_none_match); + if (etag != nullptr) + http.on_header_callback([&result](std::string received) { result.etag = etag_from_headers(received); }); + http.on_complete([&](std::string body, unsigned resp_status) { result.success = true; result.status = resp_status; @@ -2273,6 +2301,8 @@ int OrcaCloudServiceAgent::http_get(const std::string& path, std::string* respon *response_body = res.body; if (http_code) *http_code = res.status; + if (etag) + *etag = res.etag; if (!suppress && (!res.success || res.status >= 400)) { invoke_http_error_callback(res.status, res.body); @@ -3248,10 +3278,28 @@ int OrcaCloudServiceAgent::get_subscribed_bundles(std::vector lock(subscriptions_cache_mutex); + if (!user_id.empty() && subscriptions_cache.user_id == user_id) + if_none_match = subscriptions_cache.etag; + } - if (result != 0 || http_code != 200) { + std::string etag; + int result = http_get(ORCA_SUBSCRIPTIONS_PATH, &response_body, &http_code, if_none_match, &etag); + + const bool not_modified = result == 0 && http_code == 304; + if (not_modified) { + std::lock_guard lock(subscriptions_cache_mutex); + if (if_none_match.empty() || subscriptions_cache.user_id != user_id || subscriptions_cache.etag != if_none_match) { + BOOST_LOG_TRIVIAL(error) << "get_subscribed_bundles failed: 304 without the list it refers to"; + return -1; + } + response_body = subscriptions_cache.body; + } else if (result != 0 || http_code != 200) { BOOST_LOG_TRIVIAL(error) << "get_subscribed_bundles failed: http_code=" << http_code << ", response=" << response_body; return result != 0 ? result : http_code; } @@ -3289,7 +3337,16 @@ int OrcaCloudServiceAgent::get_subscribed_bundles(std::vectorpush_back(std::make_pair(bundle_json["id"].get(), bundle_json["version"].get())); } - BOOST_LOG_TRIVIAL(info) << "get_subscribed_bundles: loaded " << bundles->size() << " bundles"; + // Kept only while the session is still the account that asked, so a sign-out during the + // request doesn't leave the list behind. + if (!not_modified) { + const bool keep = !etag.empty() && !user_id.empty() && get_user_id() == user_id; + std::lock_guard lock(subscriptions_cache_mutex); + subscriptions_cache = keep ? SubscriptionsCache{user_id, etag, response_body} : SubscriptionsCache{}; + } + + BOOST_LOG_TRIVIAL(info) << "get_subscribed_bundles: loaded " << bundles->size() << " bundles" + << (not_modified ? " (unchanged)" : ""); return 0; } catch (const std::exception& e) { diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp index cc7619459c..6518159c8c 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp @@ -397,6 +397,7 @@ private: bool success{false}; unsigned int status{0}; std::string body; + std::string etag; }; // Applies the "retry once on 401" policy for the data HTTP methods. @@ -408,7 +409,10 @@ private: const std::string& reason); // HTTP request helpers - int http_get(const std::string& path, std::string* response_body, unsigned int* http_code); + // A non-empty `if_none_match` makes the request conditional, so the server may answer 304 with no + // body. `etag`, when given, receives the answer's ETag, or an empty string if it has none. + int http_get(const std::string& path, std::string* response_body, unsigned int* http_code, + const std::string& if_none_match = {}, std::string* etag = nullptr); 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); // A non-empty `required_user_id` sends the request only while the session belongs to that account. @@ -465,6 +469,16 @@ private: SessionInfo session; mutable std::mutex session_mutex; + // The last subscription list the server sent, kept so a poll can revalidate it and reuse it on a + // 304. It belongs to the account that received it and is dropped at sign-out. + struct SubscriptionsCache { + std::string user_id; + std::string etag; + std::string body; + }; + SubscriptionsCache subscriptions_cache; + std::mutex subscriptions_cache_mutex; + // Refresh diagnostics (see docs/analysis/refresh_token_already_used.md). Epoch seconds so the // refresh-failure log can report token staleness without holding a lock or logging any token. std::atomic last_refresh_success_epoch{0}; // 0 = no success yet this process diff --git a/tests/slic3rutils/test_orca_cloud_agent.cpp b/tests/slic3rutils/test_orca_cloud_agent.cpp index 13bfb8b3c0..0a655c21d4 100644 --- a/tests/slic3rutils/test_orca_cloud_agent.cpp +++ b/tests/slic3rutils/test_orca_cloud_agent.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -97,13 +98,14 @@ 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. Reply answers - // at once with the status and body given to set_reply(). + // at once with the status, body and ETag given to set_reply(). enum class Mode { Ok, Unavailable, Silent, Session, Reply }; struct Request { std::string request_line; bool has_authorization{false}; + std::string if_none_match; }; LoopbackServer() : m_acceptor(m_io, tcp::endpoint(boost::asio::ip::make_address("127.0.0.1"), 0)) @@ -126,12 +128,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) + // `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); } bool wait_for_accepts(size_t count, std::chrono::milliseconds timeout) @@ -182,8 +186,11 @@ private: std::string line; std::getline(in, line); request.request_line = line.substr(0, line.find('\r')); - while (std::getline(in, line) && line != "\r") + while (std::getline(in, line) && line != "\r") { request.has_authorization |= boost::istarts_with(line, "authorization:"); + if (boost::istarts_with(line, "if-none-match:")) + request.if_none_match = boost::trim_copy(line.substr(14)); + } { std::lock_guard lock(m_mutex); m_requests.push_back(request); @@ -199,7 +206,8 @@ private: 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: " + + const std::string etag = m_reply_etag.empty() ? std::string() : "ETag: " + m_reply_etag + "\r\n"; + *response = "HTTP/1.1 " + m_reply_status + "\r\nContent-Type: application/json\r\n" + etag + "Content-Length: " + std::to_string(m_reply_body.size()) + "\r\nConnection: close\r\n\r\n" + m_reply_body; } else { *response = mode == Mode::Ok ? @@ -237,6 +245,7 @@ private: std::string m_session_body; std::string m_reply_status; std::string m_reply_body; + std::string m_reply_etag; }; // A JWT whose only claim is {"exp":4102444800} (2100-01-01); the agent reads nothing else from it. @@ -715,6 +724,105 @@ TEST_CASE("Unsubscribing a bundle fails when the server can't be reached", "[Orc namespace { +constexpr const char* SUBSCRIPTIONS_V1 = R"({"data":[{"id":"bundle-1","version":"1.0"}],"not_found":["gone"],"unauthorised":["private"]})"; +constexpr const char* SUBSCRIPTIONS_V2 = R"({"data":[{"id":"bundle-1","version":"2.0"}],"not_found":[],"unauthorised":[]})"; + +struct SubscriptionPoll +{ + int result{-1}; + std::vector> bundles; + std::vector not_found; + std::vector unauthorized; +}; + +SubscriptionPoll poll_subscriptions(OrcaCloudServiceAgent& agent) +{ + SubscriptionPoll poll; + poll.result = agent.get_subscribed_bundles(&poll.bundles, poll.not_found, poll.unauthorized); + return poll; +} + +} // namespace + +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); + server.set_reply("200 OK", SUBSCRIPTIONS_V1, R"(W/"v1")"); + const SubscriptionPoll first = poll_subscriptions(*agent); + REQUIRE(first.result == 0); + CHECK(first.bundles == std::vector>{{"bundle-1", "1.0"}}); + + server.set_reply("304 Not Modified", "", R"(W/"v1")"); + const SubscriptionPoll second = poll_subscriptions(*agent); + CHECK(second.result == 0); + CHECK(second.bundles == first.bundles); + CHECK(second.not_found == std::vector{"gone"}); + CHECK(second.unauthorized == std::vector{"private"}); + CHECK(log.http_errors.empty()); + + const auto requests = server.requests(); + REQUIRE(requests.size() == 2); + CHECK(requests[0].if_none_match.empty()); + CHECK(requests[1].if_none_match == R"(W/"v1")"); +} + +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); + server.set_reply("200 OK", SUBSCRIPTIONS_V1, R"(W/"v1")"); + REQUIRE(poll_subscriptions(*agent).result == 0); + + server.set_reply("200 OK", SUBSCRIPTIONS_V2, R"(W/"v2")"); + const SubscriptionPoll changed = poll_subscriptions(*agent); + CHECK(changed.result == 0); + CHECK(changed.bundles == std::vector>{{"bundle-1", "2.0"}}); + + server.set_reply("304 Not Modified", "", R"(W/"v2")"); + CHECK(poll_subscriptions(*agent).bundles == changed.bundles); + const auto requests = server.requests(); + REQUIRE(requests.size() == 3); + CHECK(requests[2].if_none_match == R"(W/"v2")"); +} + +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); + 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)); + } + 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)); + } + + server.set_reply("200 OK", SUBSCRIPTIONS_V2, R"(W/"v2")"); + CHECK(poll_subscriptions(*agent).result == 0); + const auto requests = server.requests(); + REQUIRE(requests.size() == 2); + CHECK(requests[1].if_none_match.empty()); +} + +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); + server.set_reply("304 Not Modified", "", R"(W/"v1")"); + + const SubscriptionPoll poll = poll_subscriptions(*agent); + CHECK(poll.result != 0); + CHECK(poll.bundles.empty()); +} + +namespace { + // A signed-in account's preset folder holding one deleted preset's .info file, and the queue it scans into. struct DeletedPresetFixture : HealthCheckFixture {