From 177db40bf7f28938a84e423c215496909c27b993 Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:39:46 +0900 Subject: [PATCH 1/5] feat: add request compression with gzip enableRequestCompression() sends request bodies of 1 KB to 1 MB compressed with gzip, once the server's SDK behavior settings answer says that it reads compressed bodies. Compression needs a build with the new CMake option COUNTLY_USE_ZLIB (off by default), which links zlib; in other builds the call logs a warning and requests stay plain. The built-in libcurl client now gives libcurl the body size, so a body with zero bytes is sent whole. --- .github/package-check/app.cpp | 2 + .github/workflows/packaging.yml | 17 + .github/workflows/static_analysis.yml | 4 +- .github/workflows/tests.yml | 10 +- CHANGELOG.md | 3 + CMakeLists.txt | 21 +- api/countly-sdk-cpp.api | 4 + include/countly.hpp | 15 + include/countly/countly_configuration.hpp | 6 + include/countly/request_module.hpp | 16 + packaging/README.md | 11 +- .../conan/countly-sdk-cpp/all/conanfile.py | 5 + .../ports/countly-sdk-cpp/portfile.cmake | 1 + .../vcpkg/ports/countly-sdk-cpp/vcpkg.json | 6 + scripts/generate_sbom.py | 12 + src/configuration_module.cpp | 8 + src/countly.cpp | 14 + src/request_module.cpp | 202 ++++++- tests/request_compression.cpp | 538 ++++++++++++++++++ 19 files changed, 863 insertions(+), 32 deletions(-) create mode 100644 tests/request_compression.cpp diff --git a/.github/package-check/app.cpp b/.github/package-check/app.cpp index d56ff0dc..4009d7b7 100644 --- a/.github/package-check/app.cpp +++ b/.github/package-check/app.cpp @@ -16,6 +16,8 @@ int main() { #ifdef EXPECT_COUNTLY_SQLITE countly.setDatabasePath("install_check.db"); #endif + // works in every build: without zlib it logs a warning and requests stay plain + countly.enableRequestCompression(); countly.setDeviceID("install-check-device"); countly.start("install-check-app-key", "https://example.invalid", 443, false); diff --git a/.github/workflows/packaging.yml b/.github/workflows/packaging.yml index fb99e4b9..cb21eeb5 100644 --- a/.github/workflows/packaging.yml +++ b/.github/workflows/packaging.yml @@ -179,6 +179,20 @@ jobs: "$WORK/app-sqlite-no-path/app" fi + - name: Install the port with the compression feature + run: '"$VCPKG_ROOT/vcpkg" install "countly-sdk-cpp[compression]" --recurse --overlay-ports="$WORK/ports" --triplet ${{ matrix.triplet }}' + + - name: Build and run an app with the compression feature + if: matrix.run-app + run: | + cmake -S .github/package-check -B "$WORK/app-compression" -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} -DCMAKE_BUILD_TYPE=Release + cmake --build "$WORK/app-compression" --config Release + if [ "$RUNNER_OS" = "Windows" ]; then + "$WORK/app-compression/Release/app.exe" + else + "$WORK/app-compression/app" + fi + # ────────────────────────────────────────────── # Conan: the recipe builds from an archive of this # commit and its test_package runs, without and with @@ -240,6 +254,9 @@ jobs: - name: Create the package with SQLite run: conan create "$WORK/recipe" --version "$COUNTLY_VERSION" --build=missing -o "countly-sdk-cpp/*:with_sqlite=True" + - name: Create the package with request compression + run: conan create "$WORK/recipe" --version "$COUNTLY_VERSION" --build=missing -o "countly-sdk-cpp/*:with_zlib=True" + - name: Create the package as shared libraries run: conan create "$WORK/recipe" --version "$COUNTLY_VERSION" --build=missing -o "*:shared=True" diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index 3cbafcc5..874e755a 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -26,7 +26,7 @@ jobs: - name: Install dependencies run: | sudo apt-get -qq update - sudo apt-get -qq install -y --no-install-recommends clang-18 clang-tidy-18 libcurl4-openssl-dev libssl-dev + sudo apt-get -qq install -y --no-install-recommends clang-18 clang-tidy-18 libcurl4-openssl-dev libssl-dev zlib1g-dev # On pull requests the base branch is analyzed too, so that only findings it lacks can fail the job. - name: Analyze the SDK @@ -34,7 +34,7 @@ jobs: # Runs clang-tidy over the sources of the checkout in $1 and writes the findings as SARIF to $2.sarif. analyze() { cd "$1" - cmake -DCOUNTLY_USE_SQLITE=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 -B build . + cmake -DCOUNTLY_USE_SQLITE=ON -DCOUNTLY_USE_ZLIB=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 -B build . # run-clang-tidy analyzes nothing, and reports nothing, when its file pattern matches no source. if ! grep -qF "\"file\": \"$PWD/src/" build/compile_commands.json; then echo "::error title=clang-tidy::The compilation database has no source under $PWD/src" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 75af8578..930b530a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -96,6 +96,12 @@ jobs: - name: system-sqlite flags: -DCOUNTLY_USE_SQLITE=ON -DCOUNTLY_USE_SYSTEM_SQLITE=ON apt: libsqlite3-dev + - name: zlib + flags: -DCOUNTLY_USE_SQLITE=ON -DCOUNTLY_USE_ZLIB=ON + apt: zlib1g-dev + - name: zlib-sanitizer-asan + flags: -DCOUNTLY_USE_SQLITE=ON -DCOUNTLY_USE_ZLIB=ON -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address" -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address" + apt: zlib1g-dev - name: cpp17 flags: -DCOUNTLY_USE_SQLITE=ON -DCMAKE_CXX_STANDARD=17 - name: cpp20 @@ -329,12 +335,12 @@ jobs: - name: Install dependencies run: | sudo apt-get $APT_OPTS update - sudo apt-get $APT_OPTS install -y --no-install-recommends libcurl4-openssl-dev libssl-dev gcovr + sudo apt-get $APT_OPTS install -y --no-install-recommends libcurl4-openssl-dev libssl-dev zlib1g-dev gcovr # Atomic counters: the SDK's request thread runs beside the tests, and racing plain counters yield negative branch counts that gcovr rejects. - name: Build the tests with coverage run: | - cmake -DCOUNTLY_BUILD_TESTS=1 -DCOUNTLY_USE_SQLITE=ON -DCMAKE_BUILD_TYPE=Debug \ + cmake -DCOUNTLY_BUILD_TESTS=1 -DCOUNTLY_USE_SQLITE=ON -DCOUNTLY_USE_ZLIB=ON -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_C_FLAGS="--coverage -fprofile-update=atomic" -DCMAKE_CXX_FLAGS="--coverage -fprofile-update=atomic" \ -DCMAKE_EXE_LINKER_FLAGS=--coverage -DCMAKE_SHARED_LINKER_FLAGS=--coverage -B build . cmake --build build -j 4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e6c248e..88d1c5d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,9 @@ - Added `setCrashFilterCallback` for changing or dropping crash reports before they are queued, and `setCustomCrashSegmentation` for segmentation added to every crash report. - Added `crash().clearBreadcrumbs()`, `views().stopAllViews()`, and segmentation for `closeViewWithName` and `closeViewWithID`. - Added `disableLocation()`. A location given with `setLocation` before `start()` is now used from `start()` on. +- Added `enableRequestCompression()` for sending request bodies of 1 KB to 1 MB compressed with gzip. The SDK compresses only after the server's SDK Behavior Settings answer says that it reads compressed bodies, so other servers keep getting plain requests. +- Added the CMake option `COUNTLY_USE_ZLIB` (vcpkg feature `compression`, Conan option `with_zlib`), which links zlib for `enableRequestCompression()`. It is off by default; in a build without it the call logs a warning and requests stay plain. +- With request compression, a client set with `setHTTPClient` gets `?content_encoding=gzip` at the end of the path and the gzip data, which contains zero bytes, as `data`: it must send all `data.size()` bytes. - Mitigated an issue where reaching the event queue threshold logged a warning that events were dropped, although they were sent. - Mitigated an issue where a view that was open during a device ID change without merge was ended under the new device ID. diff --git a/CMakeLists.txt b/CMakeLists.txt index 14fdfbe7..3360d0a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,6 +20,7 @@ option(COUNTLY_USE_CUSTOM_SHA256 "Use a custom SHA 256 library" OFF) option(COUNTLY_USE_SQLITE "Use SQLite" OFF) option(COUNTLY_USE_SYSTEM_SQLITE "Link the system SQLite instead of compiling the vendored amalgamation" OFF) option(COUNTLY_USE_SYSTEM_JSON "Compile against the system nlohmann_json instead of the vendored copy" OFF) +option(COUNTLY_USE_ZLIB "Link zlib, which enableRequestCompression() needs to compress request bodies" OFF) option(COUNTLY_BUILD_TESTS "Build test programs" OFF) option(COUNTLY_BUILD_SAMPLE "Build Sample programs" OFF) @@ -30,6 +31,7 @@ message("Use a custom SHA 256 library:" ${COUNTLY_USE_CUSTOM_SHA256}) message("Use SQLite:" ${COUNTLY_USE_SQLITE}) message("Use system SQLite:" ${COUNTLY_USE_SYSTEM_SQLITE}) message("Use system nlohmann_json:" ${COUNTLY_USE_SYSTEM_JSON}) +message("Use zlib:" ${COUNTLY_USE_ZLIB}) message("Build test programs:" ${COUNTLY_BUILD_TESTS}) message("Build Sample programs:" ${COUNTLY_BUILD_SAMPLE}) @@ -123,6 +125,14 @@ elseif(NOT WIN32) target_link_libraries(countly CURL::libcurl) endif() +if(COUNTLY_USE_ZLIB) + message("Linking zlib for request compression") + find_package(ZLIB REQUIRED) + # No public header changes with this definition, so only the library sees it + target_compile_definitions(countly PRIVATE COUNTLY_USE_ZLIB) + target_link_libraries(countly ZLIB::ZLIB) +endif() + if(COUNTLY_USE_SQLITE) # The public headers change with this definition, so code that includes them must see it too target_compile_definitions(countly PUBLIC COUNTLY_USE_SQLITE) @@ -175,7 +185,8 @@ if(COUNTLY_BUILD_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/tests/crash_reporting.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tests/location.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tests/server_url_app_key.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tests/request_scenarios.cpp) + ${CMAKE_CURRENT_SOURCE_DIR}/tests/request_scenarios.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tests/request_compression.cpp) target_compile_options(countly-tests PRIVATE $<$>:-g>) # the request scenarios read and write their records under api/requests/ @@ -195,6 +206,11 @@ if(COUNTLY_BUILD_TESTS) message("Compiling definitions for custom http") target_compile_definitions(countly-tests PRIVATE COUNTLY_USE_CUSTOM_HTTP) endif() + if(COUNTLY_USE_ZLIB) + # the compression tests decode what the SDK sent + target_compile_definitions(countly-tests PRIVATE COUNTLY_USE_ZLIB) + target_link_libraries(countly-tests ZLIB::ZLIB) + endif() target_include_directories(countly-tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor/doctest/doctest) target_link_libraries(countly-tests countly) set_target_properties(countly-tests PROPERTIES @@ -250,6 +266,9 @@ endif() if(COUNTLY_USE_SQLITE AND COUNTLY_USE_SYSTEM_SQLITE) string(APPEND COUNTLY_CONFIG_DEPENDENCIES "\nfind_dependency(SQLite3)") endif() +if(COUNTLY_USE_ZLIB) + string(APPEND COUNTLY_CONFIG_DEPENDENCIES "\nfind_dependency(ZLIB)") +endif() include(CMakePackageConfigHelpers) configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/countlyConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/countlyConfig.cmake INSTALL_DESTINATION lib/cmake/countly) diff --git a/api/countly-sdk-cpp.api b/api/countly-sdk-cpp.api index bebb85bd..ffdd1334 100644 --- a/api/countly-sdk-cpp.api +++ b/api/countly-sdk-cpp.api @@ -114,6 +114,7 @@ cly::Countly::disableSDKBehaviorSettingsUpdates method void () public cly::Countly::enableImmediateRequestOnStop method void () public cly::Countly::enableManualSessionControl method void () public cly::Countly::enableRemoteConfig method void () public +cly::Countly::enableRequestCompression method void () public cly::Countly::endSession method bool () public cly::Countly::enrollABOnRCDownload method void () public cly::Countly::fillEventsIntoJson method void (nlohmann::json &, std::string &) public @@ -214,6 +215,7 @@ cly::CountlyConfiguration::maxStackTraceLinesPerThread field unsigned int public cly::CountlyConfiguration::maxValueSize field unsigned int public cly::CountlyConfiguration::metrics field nlohmann::json public cly::CountlyConfiguration::port field unsigned int public +cly::CountlyConfiguration::requestCompressionEnabled field bool public cly::CountlyConfiguration::requestDropAgeHours field unsigned int public cly::CountlyConfiguration::requestQueueThreshold field unsigned int public cly::CountlyConfiguration::salt field std::string public @@ -340,12 +342,14 @@ cly::RequestModule::RQSize method long long () public cly::RequestModule::RequestModule constructor void (std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr) public cly::RequestModule::addRequestToQueue method void (const std::map &) public cly::RequestModule::clearRequestQueue method void () public +cly::RequestModule::currentServer method std::string () public cly::RequestModule::initGlobalNetworking method void () static public cly::RequestModule::processQueue method void (std::shared_ptr, bool) public cly::RequestModule::removeOtherAppKeysFromQueue method long long (const std::string &) public cly::RequestModule::replaceAppKeysInQueue method void (const std::string &) public cly::RequestModule::sendHTTP method HTTPResponse (std::string, std::string) public cly::RequestModule::sendImmediate method HTTPResponse (const std::string &, const std::string &) public +cly::RequestModule::setCompressedBodiesAccepted method void (bool, const std::string &) public cly::RequestModule::setConfigurationProvider method void (std::weak_ptr) public cly::RequestModule::setOnMergeDelivered method void (std::function) public cly::RequestModule::setServerUrl method void (const std::string &, unsigned int, const std::string &) public diff --git a/include/countly.hpp b/include/countly.hpp index 47281f34..69e06611 100644 --- a/include/countly.hpp +++ b/include/countly.hpp @@ -567,6 +567,21 @@ class Countly : public cly::CountlyDelegates { */ void disableHealthCheck(); + /** + * Sends request bodies of 1 KB to 1 MB compressed with gzip, which makes them several times smaller. Off by + * default. The SDK compresses only after the server's SDK behavior settings answer said that it reads compressed + * bodies, so a server that doesn't know the feature keeps getting plain requests, and with + * disableSDKBehaviorSettingsUpdates() the SDK never compresses. When the server, or something in front of it, + * answers a compressed request without accepting it, that request goes plain on its next try and compression stops + * until a later SDK behavior settings answer says again that the server reads compressed bodies. + * + * It needs an SDK built with the CMake option COUNTLY_USE_ZLIB; in other builds it logs a warning and requests stay + * plain. A client set with setHTTPClient gets a compressed request with "?content_encoding=gzip" at the end of its + * path and the gzip data, which contains zero bytes, as 'data': it must send all data.size() bytes. + * Call it before start(). + */ + void enableRequestCompression(); + /** * Disable SDK behavior settings updates that SDK performs periodically from the server. */ diff --git a/include/countly/countly_configuration.hpp b/include/countly/countly_configuration.hpp index ebe5b8ad..72c66eec 100644 --- a/include/countly/countly_configuration.hpp +++ b/include/countly/countly_configuration.hpp @@ -180,6 +180,12 @@ struct CountlyConfiguration { */ bool healthCheckEnabled = true; + /** + * Whether request bodies are sent gzip-compressed, once the server's SDK behavior settings answer said that it + * reads compressed bodies. Only builds with COUNTLY_USE_ZLIB compress. + */ + bool requestCompressionEnabled = false; + std::string sdkBehaviorSettings; CountlyConfiguration(const std::string appKey, std::string serverUrl) { diff --git a/include/countly/request_module.hpp b/include/countly/request_module.hpp index e1e716b1..dd865fa4 100644 --- a/include/countly/request_module.hpp +++ b/include/countly/request_module.hpp @@ -55,6 +55,22 @@ class RequestModule { */ void setServerUrl(const std::string &url, unsigned int port, const std::string &path = std::string()); + /** + * The server the requests go to now, as ":". A behavior settings fetch notes it before the + * request and passes it to setCompressedBodiesAccepted() with the answer. + */ + std::string currentServer(); + + /** + * Tells what an SDK behavior settings answer said about gzip-compressed request bodies. Every answer replaces the + * one before, and an accepting answer also ends a stop caused by a refused compressed request. The answer of a + * server other than the current one is ignored, as is every answer without enableRequestCompression(). + * + * @param accepted: whether the answer carried "gzip": true + * @param server: the server that answered, as currentServer() gave it before the request + */ + void setCompressedBodiesAccepted(bool accepted, const std::string &server); + /** * Gives every queued request the app key. The caller holds the mutex it passes to processQueue(). */ diff --git a/packaging/README.md b/packaging/README.md index f4de0249..5c4a5ae0 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -6,8 +6,9 @@ submitted by copying them over: - `vcpkg/ports/countly-sdk-cpp` goes to `ports/countly-sdk-cpp` in [microsoft/vcpkg](https://github.com/microsoft/vcpkg). - `conan/countly-sdk-cpp` goes to `recipes/countly-sdk-cpp` in [conan-io/conan-center-index](https://github.com/conan-io/conan-center-index). -Both build against the package manager's own nlohmann/json, OpenSSL, libcurl and (with the `sqlite` feature or the -`with_sqlite` option) SQLite, and install the CMake package used as: +Both build against the package manager's own nlohmann/json, OpenSSL, libcurl, (with the `sqlite` feature or the +`with_sqlite` option) SQLite and (with the `compression` feature or the `with_zlib` option) zlib, and install the CMake +package used as: ```cmake find_package(countly CONFIG REQUIRED) @@ -40,6 +41,6 @@ local archive of the tree instead. `.github/workflows/packaging.yml` does that for every commit that touches the build or these files: it packs the commit with `git archive` (which, like GitHub's release archives, leaves the submodules out), builds the port and the recipe -from that archive on Linux, Windows and macOS, and builds an app against each, without and with SQLite. The port is -also built for arm64 Android, and the recipe also as shared libraries. It also checks that the versions in both match -`COUNTLY_SDK_VERSION`. +from that archive on Linux, Windows and macOS, and builds an app against each, without and with SQLite and with +request compression. The port is also built for arm64 Android, and the recipe also as shared libraries. It also checks +that the versions in both match `COUNTLY_SDK_VERSION`. diff --git a/packaging/conan/countly-sdk-cpp/all/conanfile.py b/packaging/conan/countly-sdk-cpp/all/conanfile.py index 9323efd4..b9c1711c 100644 --- a/packaging/conan/countly-sdk-cpp/all/conanfile.py +++ b/packaging/conan/countly-sdk-cpp/all/conanfile.py @@ -22,11 +22,13 @@ class CountlySdkCppConan(ConanFile): "shared": [True, False], "fPIC": [True, False], "with_sqlite": [True, False], + "with_zlib": [True, False], } default_options = { "shared": False, "fPIC": True, "with_sqlite": False, + "with_zlib": False, } implements = ["auto_shared_fpic"] @@ -43,6 +45,8 @@ def requirements(self): self.requires("libcurl/[>=7.78 <9]") if self.options.with_sqlite: self.requires("sqlite3/3.54.0") + if self.options.with_zlib: + self.requires("zlib/[>=1.2.11 <2]") def validate(self): check_min_cppstd(self, 14) @@ -58,6 +62,7 @@ def generate(self): tc.cache_variables["COUNTLY_USE_SYSTEM_JSON"] = True tc.cache_variables["COUNTLY_USE_SQLITE"] = bool(self.options.with_sqlite) tc.cache_variables["COUNTLY_USE_SYSTEM_SQLITE"] = bool(self.options.with_sqlite) + tc.cache_variables["COUNTLY_USE_ZLIB"] = bool(self.options.with_zlib) tc.cache_variables["COUNTLY_BUILD_TESTS"] = False tc.cache_variables["COUNTLY_BUILD_SAMPLE"] = False tc.generate() diff --git a/packaging/vcpkg/ports/countly-sdk-cpp/portfile.cmake b/packaging/vcpkg/ports/countly-sdk-cpp/portfile.cmake index 35911edf..80985d2b 100644 --- a/packaging/vcpkg/ports/countly-sdk-cpp/portfile.cmake +++ b/packaging/vcpkg/ports/countly-sdk-cpp/portfile.cmake @@ -8,6 +8,7 @@ vcpkg_from_github( vcpkg_check_features(OUT_FEATURE_OPTIONS FEATURE_OPTIONS FEATURES + compression COUNTLY_USE_ZLIB sqlite COUNTLY_USE_SQLITE sqlite COUNTLY_USE_SYSTEM_SQLITE ) diff --git a/packaging/vcpkg/ports/countly-sdk-cpp/vcpkg.json b/packaging/vcpkg/ports/countly-sdk-cpp/vcpkg.json index 47c35eaa..6d80f4b4 100644 --- a/packaging/vcpkg/ports/countly-sdk-cpp/vcpkg.json +++ b/packaging/vcpkg/ports/countly-sdk-cpp/vcpkg.json @@ -22,6 +22,12 @@ } ], "features": { + "compression": { + "description": "Compress request bodies with gzip", + "dependencies": [ + "zlib" + ] + }, "sqlite": { "description": "Store events and requests in SQLite", "dependencies": [ diff --git a/scripts/generate_sbom.py b/scripts/generate_sbom.py index b4df9cea..9e71b4b5 100644 --- a/scripts/generate_sbom.py +++ b/scripts/generate_sbom.py @@ -136,6 +136,18 @@ def build_sbom() -> dict: prop("countly:condition", "linked on non-Windows platforms unless the consumer supplies a custom HTTP function; version is determined by the consumer's environment"), ], }, + { + "bom-ref": "zlib", + "type": "library", + "name": "zlib", + "purl": "pkg:generic/zlib", + "scope": "optional", + "properties": [ + prop("countly:origin", "system library, resolved at consumer build time (find_package(ZLIB))"), + prop("countly:cmake-option", "COUNTLY_USE_ZLIB=ON"), + prop("countly:condition", "linked only when COUNTLY_USE_ZLIB=ON, for gzip-compressed request bodies; version is determined by the consumer's environment"), + ], + }, { "bom-ref": "winhttp", "type": "library", diff --git a/src/configuration_module.cpp b/src/configuration_module.cpp index 979d4102..5b69c7a2 100644 --- a/src/configuration_module.cpp +++ b/src/configuration_module.cpp @@ -10,6 +10,8 @@ namespace cly { static constexpr const char *KEY_TIMESTAMP = "t"; // not used yet static constexpr const char *KEY_CONFIG = "c"; // used static constexpr const char *KEY_VERSION = "v"; // not used yet +// Sent as "gzip=1" with the fetch, and answered next to "c" by a server that reads gzip-compressed request bodies +static constexpr const char *KEY_GZIP = "gzip"; static constexpr const char *KEY_TRACKING = "tracking"; static constexpr const char *KEY_NETWORKING = "networking"; @@ -188,9 +190,15 @@ class ConfigurationModule::ConfigurationModuleImpl { { std::lock_guard mutexLock(*_mutex); data = {{"method", "sc"}, {"app_key", _configuration->appKey}, {"device_id", _configuration->deviceId}}; + if (_configuration->requestCompressionEnabled) { + data[KEY_GZIP] = "1"; + } } + const std::string server = _requestModule->currentServer(); HTTPResponse response = _requestModule->sendImmediate("/o/sdk", _requestBuilder->buildRequest(data)); if (response.success && isValidAnswer(response.data)) { + const nlohmann::json::const_iterator gzip = response.data.find(KEY_GZIP); + _requestModule->setCompressedBodiesAccepted(gzip != response.data.end() && gzip->is_boolean() && gzip->get(), server); nlohmann::json changedSettings; { std::lock_guard lock(sbsMutex); diff --git a/src/countly.cpp b/src/countly.cpp index 2fe47cea..764e8073 100644 --- a/src/countly.cpp +++ b/src/countly.cpp @@ -3051,6 +3051,20 @@ void Countly::disableHealthCheck() { configuration->healthCheckEnabled = false; } +void Countly::enableRequestCompression() { + if (is_sdk_initialized) { + log(LogLevel::WARNING, "[Countly] enableRequestCompression, This method can't be called after SDK initialization. Returning."); + return; + } + +#ifdef COUNTLY_USE_ZLIB + std::lock_guard lk(*mutex); + configuration->requestCompressionEnabled = true; +#else + log(LogLevel::WARNING, "[Countly] enableRequestCompression, This build of the SDK has no zlib (CMake option COUNTLY_USE_ZLIB), so request bodies stay uncompressed."); +#endif +} + void Countly::sendHealthCheck() { if (!configuration->healthCheckEnabled) { log(LogLevel::DEBUG, "[Countly] sendHealthCheck, the health check is disabled, nothing is sent"); diff --git a/src/request_module.cpp b/src/request_module.cpp index e7ea0ba3..3393f79b 100644 --- a/src/request_module.cpp +++ b/src/request_module.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #ifndef COUNTLY_USE_CUSTOM_SHA256 #include "openssl/sha.h" @@ -26,6 +27,10 @@ #endif #endif +#ifdef COUNTLY_USE_ZLIB +#include +#endif + #if !defined(_WIN32) && !defined(COUNTLY_USE_CUSTOM_HTTP) #define COUNTLY_HAS_CURL 1 #else @@ -47,6 +52,11 @@ class RequestModule::RequestModuleImpl { std::chrono::steady_clock::time_point next_attempt_after_failure; std::chrono::steady_clock::time_point backoff_ends; std::function on_merge_delivered; + // Whether the latest SDK behavior settings answer of the current server said that it reads compressed bodies. + // Guarded by server_mutex. + bool server_reads_compressed = false; + // Set while compression is stopped because a compressed request was answered without being accepted. + std::atomic compression_stopped{false}; std::shared_ptr _configuration; std::shared_ptr _logger; std::shared_ptr _requestBuilder; @@ -75,6 +85,10 @@ class RequestModule::RequestModuleImpl { } std::lock_guard lk(server_mutex); + if (url != _configuration->serverUrl || port != _configuration->port || path != _configuration->serverPath) { + // another server gets plain requests until its own SDK behavior settings answer + server_reads_compressed = false; + } _configuration->serverUrl = url; _configuration->port = port; _configuration->serverPath = path; @@ -82,6 +96,41 @@ class RequestModule::RequestModuleImpl { ~RequestModuleImpl() { _logger.reset(); } + /** + * The server the requests go to, as ":". The caller holds server_mutex. + */ + std::string serverIdentity() const { return _configuration->serverUrl + ':' + std::to_string(_configuration->port) + _configuration->serverPath; } + + /** + * Adds the checksum, compresses the body when it may go compressed, and sends the request. + * + * @param queued: true for a request of the request queue, which counts as accepted only when it was delivered; + * an immediate request counts as accepted with any 2xx answer that is JSON + */ + HTTPResponse send(std::string path, std::string data, bool queued); + + /** + * Replaces the body with its gzip data and puts the compression marker on the path, when request compression is on, + * the current server said that it reads compressed bodies, compression isn't stopped, the path has no query, the + * body is 1 KB to 1 MB long and its gzip data is smaller. + * + * @return whether the request goes compressed + */ + bool compress(std::string &path, std::string &data); + + /** + * Stops compression when the answer to a compressed request shows that the request was answered but not accepted. + * With a client set with setHTTPClient every failure counts as answered: such a client may leave status_code 0 also + * when the server answered, and one that cuts the gzip data at a zero byte would otherwise fail the same request + * forever. + */ + void checkCompressedAnswer(const HTTPResponse &response, bool queued); + + /** + * Sends the body as it is to the path, with the HTTP client the app set or the built-in one. + */ + HTTPResponse transmit(const std::string &path, const std::string &data); + std::string calculateChecksum(const std::string &salt, const std::string &data) { std::string salted_data = data + salt; #ifdef COUNTLY_USE_CUSTOM_SHA256 @@ -152,6 +201,36 @@ bool isOlderThan(const std::string &request, unsigned int dropAgeHours) { */ bool isDelivered(const HTTPResponse &response) { return response.success && response.data.is_object() && response.data.contains("result"); } +const size_t COMPRESSION_MIN_BYTES = 1024; +const size_t COMPRESSION_MAX_BYTES = 1048576; +const char *const COMPRESSION_MARKER = "?content_encoding=gzip"; + +#ifdef COUNTLY_USE_ZLIB +/** + * Writes the gzip data (RFC 1952) of 'plain' into 'compressed'. Returns false when zlib fails. + */ +bool gzipBody(const std::string &plain, std::string &compressed) { + z_stream stream = z_stream(); + // 15 window bits plus 16 make zlib write the gzip header and trailer instead of the zlib ones + if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) { + return false; + } + compressed.resize(deflateBound(&stream, static_cast(plain.size()))); + stream.next_in = reinterpret_cast(const_cast(plain.data())); + stream.avail_in = static_cast(plain.size()); + stream.next_out = reinterpret_cast(&compressed[0]); + stream.avail_out = static_cast(compressed.size()); + const int result = deflate(&stream, Z_FINISH); + const uLong written = stream.total_out; + deflateEnd(&stream); + if (result != Z_STREAM_END) { + return false; + } + compressed.resize(written); + return true; +} +#endif + /** * Process-wide libcurl initialisation. * @@ -405,7 +484,7 @@ void RequestModule::processQueue(std::shared_ptr mutex, bool closing bool mergeDelivered = false; const std::chrono::steady_clock::time_point sent = std::chrono::steady_clock::now(); - HTTPResponse response = sendHTTP("/i", data->getData() + "&rr=" + std::to_string(behind)); + HTTPResponse response = impl->send("/i", data->getData() + "&rr=" + std::to_string(behind), true); const std::chrono::steady_clock::duration responseTime = std::chrono::steady_clock::now() - sent; { @@ -471,44 +550,121 @@ void RequestModule::processQueue(std::shared_ptr mutex, bool closing impl->is_queue_being_processed = false; } -HTTPResponse RequestModule::sendImmediate(const std::string &path, const std::string &data) { return sendHTTP(path, data + "&rr=" + std::to_string(std::max(0LL, RQSize()))); } +HTTPResponse RequestModule::sendImmediate(const std::string &path, const std::string &data) { return impl->send(path, data + "&rr=" + std::to_string(std::max(0LL, RQSize())), false); } -HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { - const bool use_post = true; - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, data: [" + data + "]"); - if (!impl->_configuration->salt.empty()) { - std::string checksum = impl->calculateChecksum(impl->_configuration->salt, data); +HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { return impl->send(std::move(path), std::move(data), false); } + +std::string RequestModule::currentServer() { + std::lock_guard lk(impl->server_mutex); + return impl->serverIdentity(); +} + +void RequestModule::setCompressedBodiesAccepted(bool accepted, const std::string &server) { + if (!impl->_configuration->requestCompressionEnabled) { + return; + } + { + std::lock_guard lk(impl->server_mutex); + if (server != impl->serverIdentity()) { + impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] setCompressedBodiesAccepted, The answer is from a server the SDK no longer sends to, so it is ignored."); + return; + } + impl->server_reads_compressed = accepted; + } + if (accepted && impl->compression_stopped.exchange(false)) { + impl->_logger->log(LogLevel::INFO, "[Countly] [RequestModule] setCompressedBodiesAccepted, The server says again that it reads compressed request bodies, so requests are compressed again."); + } + impl->_logger->log(LogLevel::DEBUG, std::string("[Countly] [RequestModule] setCompressedBodiesAccepted, The server ") + (accepted ? "reads" : "does not say that it reads") + " compressed request bodies."); +} + +HTTPResponse RequestModule::RequestModuleImpl::send(std::string path, std::string data, bool queued) { + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, data: [" + data + "]"); + if (!_configuration->salt.empty()) { + std::string checksum = calculateChecksum(_configuration->salt, data); if (!data.empty()) { data += '&'; } data += "checksum256=" + checksum; - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, with checksum, data: [" + data + "]"); + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, with checksum, data: [" + data + "]"); + } + + const bool compressed = compress(path, data); + HTTPResponse response = transmit(path, data); + if (compressed) { + checkCompressedAnswer(response, queued); + } + return response; +} + +bool RequestModule::RequestModuleImpl::compress(std::string &path, std::string &data) { +#ifdef COUNTLY_USE_ZLIB + if (!_configuration->requestCompressionEnabled || compression_stopped.load() || data.size() < COMPRESSION_MIN_BYTES || data.size() > COMPRESSION_MAX_BYTES || path.find('?') != std::string::npos) { + return false; + } + { + std::lock_guard lk(server_mutex); + if (!server_reads_compressed) { + return false; + } } + std::string compressed; + if (!gzipBody(data, compressed)) { + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, Compressing the request body failed, so it is sent uncompressed."); + return false; + } + if (compressed.size() >= data.size()) { + return false; + } + + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, The request body is sent gzip-compressed, [" + std::to_string(data.size()) + "] -> [" + std::to_string(compressed.size()) + "] bytes."); + data.swap(compressed); + path += COMPRESSION_MARKER; + return true; +#else + (void)path; + (void)data; + return false; +#endif +} + +void RequestModule::RequestModuleImpl::checkCompressedAnswer(const HTTPResponse &response, bool queued) { + const bool accepted = queued ? isDelivered(response) : (response.success && !response.data.is_null() && !response.data.is_discarded()); + const bool answered = response.status_code > 0 || _configuration->http_client_function != nullptr; + if (accepted || !answered) { + return; + } + if (!compression_stopped.exchange(true)) { + _logger->log(LogLevel::INFO, "[Countly] [RequestModule] sendHTTP, A compressed request was not accepted, so requests are sent uncompressed until an SDK behavior settings answer says again that the server reads compressed request bodies."); + } +} + +HTTPResponse RequestModule::RequestModuleImpl::transmit(const std::string &path, const std::string &data) { + const bool use_post = true; HTTPResponse response; response.success = false; #ifdef COUNTLY_USE_CUSTOM_HTTP - if (!impl->_configuration->http_client_function) { - impl->_logger->log(LogLevel::FATAL, "[Countly] [RequestModule] sendHTTP, Missing HTTP client function"); + if (!_configuration->http_client_function) { + _logger->log(LogLevel::FATAL, "[Countly] [RequestModule] sendHTTP, Missing HTTP client function"); return response; } - return impl->_configuration->http_client_function(use_post, path, data); + return _configuration->http_client_function(use_post, path, data); #else - if (impl->_configuration->http_client_function) { - return impl->_configuration->http_client_function(use_post, path, data); + if (_configuration->http_client_function) { + return _configuration->http_client_function(use_post, path, data); } std::string server_url; std::string server_path; unsigned int port; { - std::lock_guard lk(impl->server_mutex); - server_url = impl->_configuration->serverUrl; - server_path = impl->_configuration->serverPath; - port = impl->_configuration->port; + std::lock_guard lk(server_mutex); + server_url = _configuration->serverUrl; + server_path = _configuration->serverPath; + port = _configuration->port; } const std::string request_path = server_path + path; #ifdef _WIN32 @@ -589,7 +745,7 @@ HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { if (response.success && !body.empty()) { const nlohmann::json &parseResult = nlohmann::json::parse(body, nullptr, false); if (parseResult.is_discarded()) { - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, Returned response from the server was not a valid JSON."); + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, Returned response from the server was not a valid JSON."); } else { response.data = parseResult; } @@ -616,9 +772,11 @@ HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { std::ostringstream full_url_stream; full_url_stream << server_url << ':' << std::dec << port << request_path; - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); + // The size is given because gzip data contains zero bytes, where a body read as a C string would end + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.data()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(data.size())); - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, request: [" + full_url_stream.str() + "]"); + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, request: [" + full_url_stream.str() + "]"); std::string full_url = full_url_stream.str(); curl_easy_setopt(curl, CURLOPT_URL, full_url.c_str()); @@ -642,7 +800,7 @@ HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { if (!body.empty()) { const nlohmann::json &parseResult = nlohmann::json::parse(body, nullptr, false); if (parseResult.is_discarded()) { - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, Returned response from the server was not a valid JSON."); + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, Returned response from the server was not a valid JSON."); } else { response.data = parseResult; } @@ -651,7 +809,7 @@ HTTPResponse RequestModule::sendHTTP(std::string path, std::string data) { curl_easy_cleanup(curl); } #endif - impl->_logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, response: [" + response.data.dump() + "]"); + _logger->log(LogLevel::DEBUG, "[Countly] [RequestModule] sendHTTP, response: [" + response.data.dump() + "]"); return response; #endif } diff --git a/tests/request_compression.cpp b/tests/request_compression.cpp new file mode 100644 index 00000000..8bfc1b0d --- /dev/null +++ b/tests/request_compression.cpp @@ -0,0 +1,538 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "countly.hpp" +#include "countly/request_builder.hpp" +#include "countly/request_module.hpp" +#include "countly/storage_module_memory.hpp" +#include "doctest.h" +#include "nlohmann/json.hpp" +#include "test_utils.hpp" + +#ifdef COUNTLY_USE_ZLIB +#include +#endif + +using namespace cly; +using namespace test_utils; +using json = nlohmann::json; + +namespace { +#ifdef COUNTLY_USE_ZLIB +const char *const COMPRESSED_PATH = "/i?content_encoding=gzip"; +#endif + +struct SentRequest { + std::string path; + std::string body; +}; + +/** + * A server as the fake HTTP client plays it: it answers the behavior settings fetches with 'settings', keeps the body + * of every request as it arrived, and answers compressed requests with 'compressedAnswer' when that has a status code. + */ +struct CompressionServer { + std::mutex mutex; + json settings; + HTTPResponse compressedAnswer; + std::vector settingsFetches; + std::vector requests; + + void reset(const json &settingsAnswer) { + std::lock_guard lock(mutex); + settings = settingsAnswer; + compressedAnswer = HTTPResponse{true, json(), 0, ""}; + settingsFetches.clear(); + requests.clear(); + } + + void answerSettingsWith(const json &settingsAnswer) { + std::lock_guard lock(mutex); + settings = settingsAnswer; + } + + void answerCompressedWith(const HTTPResponse &answer) { + std::lock_guard lock(mutex); + compressedAnswer = answer; + } + + size_t fetchCount() { + std::lock_guard lock(mutex); + return settingsFetches.size(); + } + + std::string fetch(size_t index) { + std::lock_guard lock(mutex); + return settingsFetches.at(index); + } + + std::vector sent() { + std::lock_guard lock(mutex); + return requests; + } + + void forgetRequests() { + std::lock_guard lock(mutex); + requests.clear(); + } +}; + +CompressionServer server; + +const json SETTINGS_WITH_GZIP = {{"v", 2}, {"t", 1}, {"c", json::object()}, {"gzip", true}}; +const json SETTINGS_WITHOUT_GZIP = {{"v", 2}, {"t", 1}, {"c", json::object()}}; + +HTTPResponse compressionClient(bool use_post, const std::string &path, const std::string &data) { + (void)use_post; + std::lock_guard lock(server.mutex); + if (path == "/o/sdk" && data.find("method=sc") != std::string::npos) { + server.settingsFetches.push_back(data); + return HTTPResponse{true, server.settings, 200, server.settings.dump()}; + } + server.requests.push_back(SentRequest{path, data}); + if (path.find("content_encoding=gzip") != std::string::npos && server.compressedAnswer.status_code != 0) { + return server.compressedAnswer; + } + return HTTPResponse{true, json({{"result", "Success"}}), 200, "{\"result\":\"Success\"}"}; +} + +bool waitFor(std::function condition) { + const std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (std::chrono::steady_clock::now() < deadline) { + if (condition()) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + return condition(); +} + +#ifdef COUNTLY_USE_CUSTOM_SHA256 +std::string fakeSha256(const std::string &data) { + (void)data; + return std::string(64, '0'); +} +#endif + +bool isGzip(const std::string &body) { return body.size() > 2 && static_cast(body[0]) == 0x1f && static_cast(body[1]) == 0x8b; } + +Countly &prepareCompression(const json &settingsAnswer) { + clearSDK(); + clearCapturedLogs(); + server.reset(settingsAnswer); + Countly &countly = Countly::getInstance(); + countly.setLogger(captureLog); + countly.setHTTPClient(compressionClient); + countly.disableHealthCheck(); + countly.enableManualSessionControl(); + countly.enableImmediateRequestOnStop(); + countly.setUpdateInterval(600000); + countly.setFailedRequestCooldown(1); + countly.setDeviceID(COUNTLY_TEST_DEVICE_ID); + countly.SetPath(TEST_DATABASE_NAME); +#ifdef COUNTLY_USE_CUSTOM_SHA256 + countly.setSha256(fakeSha256); +#endif + return countly; +} + +/** + * Starts the SDK and waits until the answer of the behavior settings fetch at start was handled. + */ +void startAndWaitForSettings(Countly &countly) { + countly.start(COUNTLY_TEST_APP_KEY, COUNTLY_TEST_HOST, COUNTLY_TEST_PORT); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); +} + +/** + * Records enough events for a request body over 1 KB and sends them; returns the request as the server got it. + */ +SentRequest sendLargeRequest(Countly &countly) { + server.forgetRequests(); + for (int index = 0; index < 30; index++) { + countly.RecordEvent("compression_probe_event_" + std::to_string(index), 1); + } + countly.flushEvents(); + countly.processRQDebug(); + const std::vector sent = server.sent(); + REQUIRE(sent.size() == 1); + return sent[0]; +} + +#ifdef COUNTLY_USE_ZLIB +std::string gunzip(const std::string &compressed) { + z_stream stream = z_stream(); + REQUIRE(inflateInit2(&stream, 15 + 16) == Z_OK); + std::string plain(4 * 1024 * 1024, '\0'); + stream.next_in = reinterpret_cast(const_cast(compressed.data())); + stream.avail_in = static_cast(compressed.size()); + stream.next_out = reinterpret_cast(&plain[0]); + stream.avail_out = static_cast(plain.size()); + const int result = inflate(&stream, Z_FINISH); + const uLong written = stream.total_out; + inflateEnd(&stream); + REQUIRE(result == Z_STREAM_END); + plain.resize(written); + return plain; +} + +/** + * A request module of its own, with compression on and an HTTP client that keeps what it is given. + */ +struct ModuleFixture { + std::shared_ptr configuration = std::make_shared(COUNTLY_TEST_APP_KEY, COUNTLY_TEST_HOST); + std::shared_ptr logger = std::make_shared(); + std::shared_ptr requestBuilder = std::make_shared(configuration, logger); + std::shared_ptr storageModule = std::make_shared(configuration, logger); + std::vector sent; + HTTPResponse answer{true, json({{"result", "Success"}}), 200, "{\"result\":\"Success\"}"}; + std::shared_ptr requestModule; + + ModuleFixture() { + configuration->requestCompressionEnabled = true; +#ifdef COUNTLY_USE_CUSTOM_SHA256 + configuration->sha256_function = fakeSha256; +#endif + configuration->http_client_function = [this](bool, const std::string &path, const std::string &data) { + sent.push_back(SentRequest{path, data}); + return answer; + }; + storageModule->init(); + requestModule = std::make_shared(configuration, logger, requestBuilder, storageModule); + requestModule->setCompressedBodiesAccepted(true, requestModule->currentServer()); + } + + SentRequest send(const std::string &body, const std::string &path = "/i") { + sent.clear(); + requestModule->sendHTTP(path, body); + REQUIRE(sent.size() == 1); + return sent[0]; + } +}; + +std::string formBody(size_t size) { return "events=" + std::string(size - 7, 'a'); } +#endif +} // namespace + +TEST_CASE("Request compression is off by default") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + startAndWaitForSettings(countly); + + CHECK(server.fetch(0).find("gzip=") == std::string::npos); + const SentRequest request = sendLargeRequest(countly); + CHECK(request.body.size() >= 1024); + CHECK(request.path == "/i"); + CHECK(request.body.find("app_key=") != std::string::npos); +} + +#ifdef COUNTLY_USE_ZLIB +TEST_CASE("With request compression on, the behavior settings fetch asks whether the server reads compressed bodies") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + startAndWaitForSettings(countly); + + const std::string fetch = server.fetch(0); + CHECK((fetch.find("&gzip=1&") != std::string::npos || fetch.compare(0, 7, "gzip=1&") == 0)); +} + +TEST_CASE("A large request goes compressed after the server said that it reads compressed bodies") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + + SUBCASE("the body is the gzip data of the plain body, and the path carries the marker") { + startAndWaitForSettings(countly); + const SentRequest request = sendLargeRequest(countly); + CHECK(request.path == COMPRESSED_PATH); + REQUIRE(isGzip(request.body)); + const std::string plain = gunzip(request.body); + CHECK(request.body.size() < plain.size()); + CHECK(plain.find("app_key=" COUNTLY_TEST_APP_KEY) != std::string::npos); + CHECK(plain.find("compression_probe_event_29") != std::string::npos); + CHECK(plain.find("&rr=0") != std::string::npos); + CHECK(countly.checkRQSize() == 0); + } + + SUBCASE("the checksum is part of the plain body that is compressed") { + countly.setSalt("test-salt"); + startAndWaitForSettings(countly); + const SentRequest request = sendLargeRequest(countly); + CHECK(request.path == COMPRESSED_PATH); + REQUIRE(isGzip(request.body)); + const std::string plain = gunzip(request.body); + const std::string::size_type checksum = plain.find("&checksum256="); + REQUIRE(checksum != std::string::npos); + CHECK(plain.size() - checksum == 13 + 64); + } + + SUBCASE("a request under 1 KB stays plain") { + startAndWaitForSettings(countly); + server.forgetRequests(); + countly.RecordEvent("small", 1); + countly.flushEvents(); + countly.processRQDebug(); + const std::vector sent = server.sent(); + REQUIRE(sent.size() == 1); + CHECK(sent[0].body.size() < 1024); + CHECK(sent[0].path == "/i"); + CHECK(!isGzip(sent[0].body)); + } +} + +TEST_CASE("Requests stay plain while the behavior settings answer does not carry gzip true") { + json settings = SETTINGS_WITHOUT_GZIP; + SUBCASE("no gzip key") {} + SUBCASE("gzip false") { settings["gzip"] = false; } + SUBCASE("gzip as the text true") { settings["gzip"] = "true"; } + SUBCASE("gzip as the number 1") { settings["gzip"] = 1; } + SUBCASE("gzip inside the settings object") { settings["c"]["gzip"] = true; } + + Countly &countly = prepareCompression(settings); + countly.enableRequestCompression(); + startAndWaitForSettings(countly); + + const SentRequest request = sendLargeRequest(countly); + CHECK(request.path == "/i"); + CHECK(!isGzip(request.body)); +} + +TEST_CASE("A compressed request that the server refuses goes plain on its next try, and compression stops") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + startAndWaitForSettings(countly); + + server.answerCompressedWith(HTTPResponse{false, json({{"result", "Invalid gzip body"}}), 400, "{\"result\":\"Invalid gzip body\"}"}); + const SentRequest refused = sendLargeRequest(countly); + REQUIRE(refused.path == COMPRESSED_PATH); + CHECK(countly.checkRQSize() == 1); + + server.forgetRequests(); + std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + countly.processRQDebug(); + std::vector sent = server.sent(); + REQUIRE(sent.size() == 1); + CHECK(sent[0].path == "/i"); + CHECK(sent[0].body == gunzip(refused.body)); + CHECK(countly.checkRQSize() == 0); + + const SentRequest later = sendLargeRequest(countly); + CHECK(later.path == "/i"); + CHECK(!isGzip(later.body)); + + SUBCASE("the next behavior settings answer with gzip true starts compression again") { + server.answerCompressedWith(HTTPResponse{true, json(), 0, ""}); + clearCapturedLogs(); + countly.setDeviceID("second-user", false); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + countly.processRQDebug(); + + const SentRequest again = sendLargeRequest(countly); + CHECK(again.path == COMPRESSED_PATH); + CHECK(isGzip(again.body)); + } + + SUBCASE("a behavior settings answer without gzip keeps requests plain") { + server.answerSettingsWith(SETTINGS_WITHOUT_GZIP); + clearCapturedLogs(); + countly.setDeviceID("second-user", false); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + countly.processRQDebug(); + + const SentRequest still = sendLargeRequest(countly); + CHECK(still.path == "/i"); + } +} + +TEST_CASE("A later behavior settings answer without gzip stops compression") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + startAndWaitForSettings(countly); + REQUIRE(sendLargeRequest(countly).path == COMPRESSED_PATH); + + server.answerSettingsWith(SETTINGS_WITHOUT_GZIP); + clearCapturedLogs(); + countly.setDeviceID("second-user", false); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + countly.processRQDebug(); + + CHECK(sendLargeRequest(countly).path == "/i"); +} + +TEST_CASE("After a server URL change requests stay plain until the new server says that it reads compressed bodies") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + startAndWaitForSettings(countly); + REQUIRE(sendLargeRequest(countly).path == COMPRESSED_PATH); + + SUBCASE("a new server without gzip gets plain requests") { + server.answerSettingsWith(SETTINGS_WITHOUT_GZIP); + clearCapturedLogs(); + countly.changeServerUrl("http://other.countly.notarealdomain"); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + CHECK(sendLargeRequest(countly).path == "/i"); + } + + SUBCASE("a new server with gzip gets compressed requests") { + clearCapturedLogs(); + countly.changeServerUrl("http://other.countly.notarealdomain"); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + CHECK(sendLargeRequest(countly).path == COMPRESSED_PATH); + } +} + +TEST_CASE("Provided behavior settings cannot turn request compression on") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + countly.setSDKBehaviorSettings("{\"v\":2,\"t\":1,\"c\":{},\"gzip\":true}"); + countly.disableSDKBehaviorSettingsUpdates(); + countly.start(COUNTLY_TEST_APP_KEY, COUNTLY_TEST_HOST, COUNTLY_TEST_PORT); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + + CHECK(server.fetchCount() == 0); + CHECK(sendLargeRequest(countly).path == "/i"); +} + +TEST_CASE("enableRequestCompression after start has no effect") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + startAndWaitForSettings(countly); + + countly.enableRequestCompression(); + CHECK(capturedLogContains("enableRequestCompression, This method can't be called after SDK initialization")); + + clearCapturedLogs(); + countly.setDeviceID("second-user", false); + REQUIRE(waitFor([] { return capturedLogContains("_fetchConfigFromServerHTTP, SDK config"); })); + countly.processRQDebug(); + CHECK(server.fetch(1).find("gzip=") == std::string::npos); + CHECK(sendLargeRequest(countly).path == "/i"); +} + +TEST_CASE("The size limits of a compressed body") { + ModuleFixture fixture; + + SUBCASE("1,023 bytes stay plain") { + const SentRequest request = fixture.send(formBody(1023)); + CHECK(request.path == "/i"); + CHECK(request.body.size() == 1023); + } + + SUBCASE("1,024 bytes go compressed") { + const SentRequest request = fixture.send(formBody(1024)); + CHECK(request.path == COMPRESSED_PATH); + CHECK(gunzip(request.body) == formBody(1024)); + } + + SUBCASE("1 MB goes compressed") { + const SentRequest request = fixture.send(formBody(1048576)); + CHECK(request.path == COMPRESSED_PATH); + CHECK(gunzip(request.body) == formBody(1048576)); + } + + SUBCASE("one byte over 1 MB stays plain") { + const SentRequest request = fixture.send(formBody(1048577)); + CHECK(request.path == "/i"); + CHECK(request.body.size() == 1048577); + } + + SUBCASE("the size counts with the checksum") { + fixture.configuration->salt = "test-salt"; + const std::string body = formBody(1024 - 13 - 64); + const SentRequest request = fixture.send(body); + CHECK(request.path == COMPRESSED_PATH); + const std::string plain = gunzip(request.body); + CHECK(plain.size() == 1024); + CHECK(plain.compare(0, body.size() + 13, body + "&checksum256=") == 0); + } + + SUBCASE("a body that gzip does not make smaller stays plain") { + std::mt19937 generator(7); + std::string body = "events="; + while (body.size() < 4096) { + body += static_cast(generator() & 0xff); + } + const SentRequest request = fixture.send(body); + CHECK(request.path == "/i"); + CHECK(request.body == body); + } + + SUBCASE("a path that has a query stays plain") { + const SentRequest request = fixture.send(formBody(4096), "/i?preview=1"); + CHECK(request.path == "/i?preview=1"); + CHECK(request.body == formBody(4096)); + } +} + +TEST_CASE("The answer of the server decides for one server only") { + ModuleFixture fixture; + const std::string first = fixture.requestModule->currentServer(); + REQUIRE(fixture.send(formBody(4096)).path == COMPRESSED_PATH); + + fixture.requestModule->setServerUrl("https://other.countly.notarealdomain", 0); + CHECK(fixture.send(formBody(4096)).path == "/i"); + + SUBCASE("the late answer of the server the SDK left changes nothing") { + fixture.requestModule->setCompressedBodiesAccepted(true, first); + CHECK(fixture.send(formBody(4096)).path == "/i"); + } + + SUBCASE("the answer of the new server turns compression on for it") { + fixture.requestModule->setCompressedBodiesAccepted(true, fixture.requestModule->currentServer()); + CHECK(fixture.send(formBody(4096)).path == COMPRESSED_PATH); + } + + SUBCASE("going back to the first server needs a new answer from it") { + fixture.requestModule->setServerUrl(COUNTLY_TEST_HOST, 443); + REQUIRE(fixture.requestModule->currentServer() == first); + CHECK(fixture.send(formBody(4096)).path == "/i"); + } +} + +TEST_CASE("An immediate compressed request that is not accepted stops compression") { + ModuleFixture fixture; + + SUBCASE("an answer outside 2xx") { fixture.answer = HTTPResponse{false, json({{"result", "Invalid gzip body"}}), 400, "{\"result\":\"Invalid gzip body\"}"}; } + SUBCASE("a 2xx answer that is not JSON") { fixture.answer = HTTPResponse{true, json(), 200, ""}; } + SUBCASE("a failure of an HTTP client that reports no status code") { fixture.answer = HTTPResponse{false, json(), 0, ""}; } + + REQUIRE(fixture.send(formBody(4096)).path == COMPRESSED_PATH); + CHECK(fixture.send(formBody(4096)).path == "/i"); + + fixture.requestModule->setCompressedBodiesAccepted(true, fixture.requestModule->currentServer()); + CHECK(fixture.send(formBody(4096)).path == COMPRESSED_PATH); +} + +TEST_CASE("An accepted immediate compressed request keeps compression on") { + ModuleFixture fixture; + fixture.answer = HTTPResponse{true, json({{"color", "blue"}}), 200, "{\"color\":\"blue\"}"}; + + REQUIRE(fixture.send(formBody(4096)).path == COMPRESSED_PATH); + CHECK(fixture.send(formBody(4096)).path == COMPRESSED_PATH); +} + +TEST_CASE("A request module without request compression turned on never compresses") { + ModuleFixture fixture; + fixture.configuration->requestCompressionEnabled = false; + fixture.requestModule->setCompressedBodiesAccepted(true, fixture.requestModule->currentServer()); + + CHECK(fixture.send(formBody(4096)).path == "/i"); +} +#else +TEST_CASE("In a build without zlib, enableRequestCompression warns and requests stay plain") { + Countly &countly = prepareCompression(SETTINGS_WITH_GZIP); + countly.enableRequestCompression(); + CHECK(capturedLogContains("enableRequestCompression, This build of the SDK has no zlib")); + startAndWaitForSettings(countly); + + CHECK(server.fetch(0).find("gzip=") == std::string::npos); + const SentRequest request = sendLargeRequest(countly); + CHECK(request.path == "/i"); + CHECK(!isGzip(request.body)); +} +#endif From f9691b214379d27236e2831e01e853270ac5060f Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:00:19 +0900 Subject: [PATCH 2/5] test: take the sent requests of the compression fixture from a function cppcheck read the list as always empty, because the HTTP client callback fills it. --- tests/request_compression.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/request_compression.cpp b/tests/request_compression.cpp index 8bfc1b0d..5ed94796 100644 --- a/tests/request_compression.cpp +++ b/tests/request_compression.cpp @@ -210,11 +210,21 @@ struct ModuleFixture { requestModule->setCompressedBodiesAccepted(true, requestModule->currentServer()); } + /** + * Hands over the requests the HTTP client got since the last call. + */ + std::vector takeSent() { + std::vector taken; + taken.swap(sent); + return taken; + } + SentRequest send(const std::string &body, const std::string &path = "/i") { - sent.clear(); + takeSent(); requestModule->sendHTTP(path, body); - REQUIRE(sent.size() == 1); - return sent[0]; + const std::vector requests = takeSent(); + REQUIRE(requests.size() == 1); + return requests[0]; } }; From 08b955f4639de4fb64c4b973cfaf59bf9d4a1431 Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:22:44 +0900 Subject: [PATCH 3/5] test: send compressed requests through the built-in HTTP client A local server answers the behavior settings request with gzip true. The test checks that the whole gzip body arrives, that a request without an answer keeps compression on, and that a 400 answer gives a plain retry with the same body. --- tests/request.cpp | 176 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 170 insertions(+), 6 deletions(-) diff --git a/tests/request.cpp b/tests/request.cpp index 085c0131..23fa7158 100644 --- a/tests/request.cpp +++ b/tests/request.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +34,9 @@ #include #endif #endif +#ifdef COUNTLY_USE_ZLIB +#include +#endif using namespace cly; using namespace std; @@ -449,8 +453,8 @@ long receiveFrom(Socket socket, char *buffer, size_t size) { return static_cast< * * An answering server replies to every complete request with 200 and {"result":"Success"} * and records its request line and body; with a body rate, it reads each body at that many bytes per second, like a - * slow connection. A silent server accepts connections and never replies; it records - * how long each connection stayed open until the client closed it. + * slow connection. replyWith() and answerSettingsWith() change its answers. A silent server accepts connections and + * never replies; it records how long each connection stayed open until the client closed it. */ class LocalHTTPServer { public: @@ -529,6 +533,25 @@ class LocalHTTPServer { */ size_t bodyBytesInProgress() const { return _body_bytes_in_progress.load(); } + /** + * What an answering server does with a complete request that is not an SDK behavior settings fetch: SUCCESS answers + * 200 and {"result":"Success"}, REFUSE answers 400, and NO_ANSWER closes the connection without an answer. + */ + enum class Reply : std::uint8_t { SUCCESS, REFUSE, NO_ANSWER }; + + /** + * Sets the reply to the requests that arrive from now on. + */ + void replyWith(Reply reply) { _reply.store(reply); } + + /** + * Answers every SDK behavior settings fetch, a "method=sc" request to /o/sdk, with 200 and this JSON text from now on. + */ + void answerSettingsWith(const std::string &settings) { + std::lock_guard lock(_mutex); + _settings_answer = settings; + } + private: struct HeldConnection { Socket descriptor; @@ -626,13 +649,32 @@ class LocalHTTPServer { return; } + const std::string request_line = request.substr(0, request.find("\r\n")); + const std::string body = request.substr(header_end + 4); + std::string settings_answer; { std::lock_guard lock(_mutex); - _request_lines.push_back(request.substr(0, request.find("\r\n"))); - _request_bodies.push_back(request.substr(header_end + 4)); + _request_lines.push_back(request_line); + _request_bodies.push_back(body); + settings_answer = _settings_answer; } - const std::string response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 20\r\nConnection: close\r\n\r\n{\"result\":\"Success\"}"; + const Reply reply = _reply.load(); + if (!settings_answer.empty() && request_line.find("/o/sdk ") != std::string::npos && body.find("method=sc") != std::string::npos) { + respond(client, "200 OK", settings_answer); + } else if (reply == Reply::REFUSE) { + respond(client, "400 Bad Request", "{\"result\":\"Invalid gzip body\"}"); + } else if (reply == Reply::SUCCESS) { + respond(client, "200 OK", "{\"result\":\"Success\"}"); + } + closeSocket(client); + } + + /** + * Sends an HTTP answer with the status and the JSON text as its body. + */ + static void respond(Socket client, const std::string &status, const std::string &json) { + const std::string response = "HTTP/1.1 " + status + "\r\nContent-Type: application/json\r\nContent-Length: " + std::to_string(json.size()) + "\r\nConnection: close\r\n\r\n" + json; #ifdef SO_NOSIGPIPE int no_sigpipe = 1; ::setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe)); @@ -642,7 +684,6 @@ class LocalHTTPServer { #else ::send(client, response.data(), static_cast(response.size()), 0); #endif - closeSocket(client); } const bool _answering; @@ -652,10 +693,13 @@ class LocalHTTPServer { int _port = 0; std::thread _thread; std::atomic _stopping{false}; + std::atomic _reply{Reply::SUCCESS}; mutable std::mutex _mutex; std::vector _request_lines; std::vector _request_bodies; std::vector _closed_durations; + // Guarded by _mutex, empty while the server answers behavior settings fetches as other requests + std::string _settings_answer; }; } // namespace @@ -1005,4 +1049,124 @@ TEST_CASE("Built-in HTTP client on a slow connection") { } } +#ifdef COUNTLY_USE_ZLIB +/** + * The plain body of gzip data. 'whole' says whether the data was one complete gzip stream. + */ +static std::string gunzipBody(const std::string &compressed, bool &whole) { + z_stream stream = z_stream(); + whole = false; + if (inflateInit2(&stream, 15 + 16) != Z_OK) { + return std::string(); + } + std::string plain(4 * 1024 * 1024, '\0'); + stream.next_in = reinterpret_cast(const_cast(compressed.data())); + stream.avail_in = static_cast(compressed.size()); + stream.next_out = reinterpret_cast(&plain[0]); + stream.avail_out = static_cast(plain.size()); + const int result = inflate(&stream, Z_FINISH); + const uLong written = stream.total_out; + const uInt unread = stream.avail_in; + inflateEnd(&stream); + whole = result == Z_STREAM_END && unread == 0; + plain.resize(written); + return plain; +} + +TEST_CASE("Built-in HTTP client with request compression") { + const std::string database_path = "test-countly-http.db"; + remove(database_path.c_str()); + LocalHTTPServer server(true); + server.answerSettingsWith("{\"v\":2,\"t\":1,\"c\":{},\"gzip\":true}"); + test_utils::clearCapturedLogs(); + std::shared_ptr countly = std::make_shared(); + countly->setLogger(test_utils::captureLog); + countly->setDeviceID(COUNTLY_TEST_DEVICE_ID); + countly->SetPath(database_path); + countly->disableHealthCheck(); + countly->enableManualSessionControl(); + countly->enableImmediateRequestOnStop(); + countly->setUpdateInterval(60000); + countly->setFailedRequestCooldown(1); + countly->setSalt("test-salt"); + countly->enableRequestCompression(); + countly->start(COUNTLY_TEST_APP_KEY, "http://127.0.0.1", server.port(), false); + + const std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!test_utils::capturedLogContains("_fetchConfigFromServerHTTP, SDK config") && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + REQUIRE(test_utils::capturedLogContains("_fetchConfigFromServerHTTP, SDK config")); + REQUIRE(receivedRequestWith(server, "gzip=1")); + + // Records 30 events and sends them as one request of about 2 KB + const auto sendEvents = [&countly](const std::string &prefix) { + for (int index = 0; index < 30; index++) { + countly->RecordEvent(prefix + std::to_string(index), 1); + } + countly->flushEvents(); + countly->processRQDebug(); + }; + const std::string compressed_line = "POST /i?content_encoding=gzip HTTP/1.1"; + bool whole = false; + + // The whole gzip data arrives, with its zero bytes, and holds the plain body with its checksum + size_t seen = server.requestLines().size(); + sendEvents("compressed_"); + std::vector lines = server.requestLines(); + std::vector bodies = server.requestBodies(); + REQUIRE(lines.size() == seen + 1); + CHECK(lines[seen] == compressed_line); + const std::string plain = gunzipBody(bodies[seen], whole); + REQUIRE(whole); + CHECK(bodies[seen].size() < plain.size()); + CHECK(plain.find("compressed_29") != std::string::npos); + CHECK(plain.find("&checksum256=") != std::string::npos); + CHECK(countly->checkRQSize() == 0); + + // A request that gets no answer keeps compression on: its retry after the cool-down goes compressed again + server.replyWith(LocalHTTPServer::Reply::NO_ANSWER); + seen = server.requestLines().size(); + sendEvents("unanswered_"); + lines = server.requestLines(); + REQUIRE(lines.size() == seen + 1); + CHECK(lines[seen] == compressed_line); + CHECK(countly->checkRQSize() == 1); + CHECK_FALSE(test_utils::capturedLogContains("requests are sent uncompressed until")); + server.replyWith(LocalHTTPServer::Reply::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + seen = server.requestLines().size(); + countly->processRQDebug(); + lines = server.requestLines(); + REQUIRE(lines.size() == seen + 1); + CHECK(lines[seen] == compressed_line); + CHECK(countly->checkRQSize() == 0); + + // A 400 answer stops compression: the retry after the cool-down goes plain, with the same body + server.replyWith(LocalHTTPServer::Reply::REFUSE); + seen = server.requestLines().size(); + sendEvents("refused_"); + lines = server.requestLines(); + bodies = server.requestBodies(); + REQUIRE(lines.size() == seen + 1); + CHECK(lines[seen] == compressed_line); + const std::string refused_plain = gunzipBody(bodies[seen], whole); + REQUIRE(whole); + server.replyWith(LocalHTTPServer::Reply::SUCCESS); + std::this_thread::sleep_for(std::chrono::milliseconds(1100)); + seen = server.requestLines().size(); + countly->processRQDebug(); + lines = server.requestLines(); + bodies = server.requestBodies(); + REQUIRE(lines.size() == seen + 1); + CHECK(lines[seen] == "POST /i HTTP/1.1"); + CHECK(bodies[seen] == refused_plain); + CHECK(countly->checkRQSize() == 0); + + countly.reset(); + server.stop(); + remove(database_path.c_str()); +} +#endif + #endif From de1bce4d4431483686c85e0e1cdeac67881ea553 Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:22:44 +0900 Subject: [PATCH 4/5] docs: say that a failed request of a custom HTTP client stops compression The header now names the rule for clients set with setHTTPClient, and the log line also fits a request that got no answer. --- include/countly.hpp | 4 +++- src/request_module.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/countly.hpp b/include/countly.hpp index d6d3e6ec..c64208b4 100644 --- a/include/countly.hpp +++ b/include/countly.hpp @@ -633,7 +633,9 @@ class Countly : public cly::CountlyDelegates { * * It needs an SDK built with the CMake option COUNTLY_USE_ZLIB; in other builds it logs a warning and requests stay * plain. A client set with setHTTPClient gets a compressed request with "?content_encoding=gzip" at the end of its - * path and the gzip data, which contains zero bytes, as 'data': it must send all data.size() bytes. + * path and the gzip data, which contains zero bytes, as 'data': it must send all data.size() bytes. Such a client + * may report no status code, so every failed compressed request it sends, also one that got no answer, stops + * compression until the next SDK behavior settings answer. * Call it before start(). */ void enableRequestCompression(); diff --git a/src/request_module.cpp b/src/request_module.cpp index eb9dc344..4102e0d9 100644 --- a/src/request_module.cpp +++ b/src/request_module.cpp @@ -759,7 +759,7 @@ void RequestModule::RequestModuleImpl::checkCompressedAnswer(const HTTPResponse return; } if (!compression_stopped.exchange(true)) { - _logger->log(LogLevel::INFO, "[Countly] [RequestModule] sendHTTP, A compressed request was not accepted, so requests are sent uncompressed until an SDK behavior settings answer says again that the server reads compressed request bodies."); + _logger->log(LogLevel::INFO, "[Countly] [RequestModule] sendHTTP, A compressed request failed or was not accepted, so requests are sent uncompressed until an SDK behavior settings answer says again that the server reads compressed request bodies."); } } From f548d5477a3035196e84176b4539aba528cc6a52 Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:50:52 +0900 Subject: [PATCH 5/5] chore: mark the compression check for cppcheck's analysis without zlib --- src/request_module.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/request_module.cpp b/src/request_module.cpp index 4102e0d9..9ae3a2ee 100644 --- a/src/request_module.cpp +++ b/src/request_module.cpp @@ -714,6 +714,7 @@ HTTPResponse RequestModule::RequestModuleImpl::send(std::string path, std::strin const bool compressed = compress(path, data); HTTPResponse response = transmit(path, data); + // cppcheck-suppress knownConditionTrueFalse ; compress() is always false only in builds without COUNTLY_USE_ZLIB if (compressed) { checkCompressedAnswer(response, queued); }