utils/curl_utils.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "curl_utils.hpp" | ||
| 2 | #include <format> | ||
| 3 | #include <string> | ||
| 4 | |||
| 5 | /** | ||
| 6 | * Constructs a CurlUtils instance with dependency injection. | ||
| 7 | * | ||
| 8 | * Initializes CURL and headers pointers to nullptr, stores the provided | ||
| 9 | * UserInterface pointer for logging and status messages, and creates a | ||
| 10 | * ProgressSpinner instance for visual feedback during network operations. | ||
| 11 | * The actual CURL easy handle initialization is deferred to the initialize() | ||
| 12 | * method, typically called after object construction. | ||
| 13 | * | ||
| 14 | * @param ui Pointer to the UserInterface for displaying messages and progress | ||
| 15 | */ | ||
| 16 | ✗ | CurlUtils::CurlUtils(std::shared_ptr<UserInterface> ui) : ui(ui) { | |
| 17 | ✗ | this->curl = nullptr; | |
| 18 | ✗ | this->headers = nullptr; | |
| 19 | ✗ | this->spinner = std::make_unique<ProgressSpinner>(ui, false); | |
| 20 | ✗ | } | |
| 21 | |||
| 22 | /** | ||
| 23 | * Destroys the CurlUtils instance and releases its CURL resources. | ||
| 24 | * | ||
| 25 | * Calls cleanup(), which resets the curl and headers unique_ptrs and runs their | ||
| 26 | * deleters. Because the unique_ptrs also release their resources when they are | ||
| 27 | * destroyed, this call is not strictly required. It is kept so that the handle | ||
| 28 | * is released in the same way as at the end of each request. | ||
| 29 | * | ||
| 30 | * @note cleanup() also prints a completion message. This output appears when the | ||
| 31 | * object is destroyed, even if no request was made. | ||
| 32 | */ | ||
| 33 | ✗ | CurlUtils::~CurlUtils() { | |
| 34 | ✗ | this->cleanup(); | |
| 35 | ✗ | } | |
| 36 | |||
| 37 | /** | ||
| 38 | * Creates a new CURL easy handle and stores it in the curl unique_ptr. | ||
| 39 | * | ||
| 40 | * Calls curl_easy_init() and assigns the result with reset(), which releases any | ||
| 41 | * previously held handle through its custom deleter (curl_easy_cleanup). If | ||
| 42 | * initialization fails, the error is reported through the UI or to stdout, and | ||
| 43 | * the process exits (non-interactive mode) or the UI session ends with | ||
| 44 | * EXIT_FAILURE. On success, a confirmation message is printed. | ||
| 45 | * | ||
| 46 | * @note Because reset() releases an existing handle, calling this method | ||
| 47 | * discards any state set on the previous handle. | ||
| 48 | */ | ||
| 49 | ✗ | void CurlUtils::initialize() { | |
| 50 | ✗ | this->curl.reset(curl_easy_init()); | |
| 51 | ✗ | std::string message{}; | |
| 52 | ✗ | if (!this->curl) { | |
| 53 | ✗ | message = "Failed to initialize CURL.\n"; | |
| 54 | ✗ | if (this->ui->backend_running() == false) { | |
| 55 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 56 | } else { | ||
| 57 | ✗ | this->ui->print_error(message); | |
| 58 | } | ||
| 59 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 60 | } else { | ||
| 61 | ✗ | message = "CURL is initialized.\n"; | |
| 62 | ✗ | if (this->ui->backend_running() == false) { | |
| 63 | ✗ | UserInterface::print_success_noninteractive(message); | |
| 64 | } else { | ||
| 65 | ✗ | this->ui->print_success(message); | |
| 66 | } | ||
| 67 | } | ||
| 68 | ✗ | } | |
| 69 | |||
| 70 | /** | ||
| 71 | * Releases the CURL handle and the header list held by this object. | ||
| 72 | * | ||
| 73 | * Calls reset() on the curl and headers unique_ptrs, which runs their custom | ||
| 74 | * deleters (curl_easy_cleanup and curl_slist_free_all). Each resource is only | ||
| 75 | * released if it is currently held, so calling this method more than once is safe. | ||
| 76 | * | ||
| 77 | * In DEBUG builds, the pointer values are logged before they are released when | ||
| 78 | * no UI is running. A success message is printed at the end, either through the | ||
| 79 | * UI or to stdout. | ||
| 80 | * | ||
| 81 | * @note Do not call curl_easy_cleanup or curl_slist_free_all manually for these | ||
| 82 | * resources. Doing so together with the deleters causes a double free. | ||
| 83 | */ | ||
| 84 | ✗ | void CurlUtils::cleanup() { | |
| 85 | ✗ | if (this->curl) { | |
| 86 | #ifdef DEBUG | ||
| 87 | ✗ | if (this->ui->backend_running() == false) { | |
| 88 | ✗ | UserInterface::print_message_noninteractive( | |
| 89 | ✗ | std::format("\t[DEBUG] curl pointer before cleanup: {}\n", static_cast<void*>(this->curl.get()))); | |
| 90 | } | ||
| 91 | #endif | ||
| 92 | ✗ | this->curl.reset(); | |
| 93 | } | ||
| 94 | ✗ | if (this->headers) { | |
| 95 | #ifdef DEBUG | ||
| 96 | ✗ | if (this->ui->backend_running() == false) { | |
| 97 | ✗ | UserInterface::print_message_noninteractive(std::format( | |
| 98 | ✗ | "\t[DEBUG] curl headers pointer before cleanup: {}\n", static_cast<void*>(this->headers.get()))); | |
| 99 | } | ||
| 100 | #endif | ||
| 101 | ✗ | this->headers.reset(); | |
| 102 | } | ||
| 103 | ✗ | std::string message = "CURL cleanup is complete.\n"; | |
| 104 | ✗ | if (this->ui->backend_running() == false) { | |
| 105 | ✗ | UserInterface::print_success_noninteractive(message); | |
| 106 | } else { | ||
| 107 | ✗ | this->ui->print_success(message); | |
| 108 | } | ||
| 109 | ✗ | } | |
| 110 | |||
| 111 | /** | ||
| 112 | * Appends a single header line to a curl_slist that is being built. | ||
| 113 | * | ||
| 114 | * Calls curl_slist_append() and, on success, updates the caller's list pointer | ||
| 115 | * to the new head. If the append fails, the pointer is left unchanged, so the | ||
| 116 | * previously built list remains valid and is not lost. | ||
| 117 | * | ||
| 118 | * @param headers Reference to the curl_slist pointer being built. May be nullptr | ||
| 119 | * to start a new list. | ||
| 120 | * @param line The header line to append, in the form "Name: value". | ||
| 121 | * | ||
| 122 | * @note On failure the header is silently dropped. Callers that must guarantee | ||
| 123 | * every header is sent should check the list afterwards. | ||
| 124 | */ | ||
| 125 | ✗ | void CurlUtils::add_header(curl_slist*& headers, const std::string& line) { | |
| 126 | ✗ | curl_slist* updated = curl_slist_append(headers, line.c_str()); | |
| 127 | ✗ | if (updated != nullptr) { | |
| 128 | ✗ | headers = updated; | |
| 129 | } | ||
| 130 | ✗ | } | |
| 131 | |||
| 132 | /** | ||
| 133 | * CURL write callback for accumulating response data. | ||
| 134 | * | ||
| 135 | * Called by CURL whenever data is received. Appends the chunk to the | ||
| 136 | * userp string buffer. | ||
| 137 | * | ||
| 138 | * @param contents Pointer to the received data chunk. | ||
| 139 | * @param size Size of each element (always 1 for this use case). | ||
| 140 | * @param nmemb Number of elements received. | ||
| 141 | * @param userp Pointer to the std::string buffer to append data to. | ||
| 142 | * | ||
| 143 | * @return Total bytes processed (size * nmemb). | ||
| 144 | */ | ||
| 145 | ✗ | size_t CurlUtils::curl_write_callback(char* contents, size_t size, size_t nmemb, std::string* userp) { | |
| 146 | ✗ | userp->append(contents, size * nmemb); | |
| 147 | ✗ | return size * nmemb; | |
| 148 | } | ||
| 149 | |||
| 150 | /** | ||
| 151 | * CURL write callback for streaming response data. | ||
| 152 | * | ||
| 153 | * Called by CURL whenever a chunk of the response body is received. The chunk | ||
| 154 | * is copied into a std::string and passed to CurlUtils::process_chunk() on the | ||
| 155 | * CurlUtils instance stored in userp. Output for errors and debug messages goes | ||
| 156 | * through the UserInterface when it is running, and to stdout or stderr | ||
| 157 | * otherwise. | ||
| 158 | * | ||
| 159 | * @param contents Pointer to the received data chunk. Not null-terminated. | ||
| 160 | * @param size Size of each element (always 1 for this use case). | ||
| 161 | * @param nmemb Number of elements received. | ||
| 162 | * @param userp Pointer to the CurlUtils instance that owns the transfer. | ||
| 163 | * | ||
| 164 | * @return Total bytes processed (size * nmemb). Returns 0 if process_chunk() | ||
| 165 | * throws, which makes CURL abort the transfer with CURLE_WRITE_ERROR. | ||
| 166 | * | ||
| 167 | * @note This method reads curl_obj->ui directly, so it is unsafe when no | ||
| 168 | * UserInterface is set. Consider using ui_running() before each access. | ||
| 169 | */ | ||
| 170 | ✗ | size_t CurlUtils::curl_streaming_write_callback(char* contents, size_t size, size_t nmemb, void* userp) { | |
| 171 | ✗ | size_t realsize = size * nmemb; | |
| 172 | |||
| 173 | ✗ | CurlUtils* curl_obj = static_cast<CurlUtils*>(userp); | |
| 174 | |||
| 175 | #ifdef DEBUG | ||
| 176 | ✗ | if (curl_obj->ui->backend_running() == false) { | |
| 177 | ✗ | UserInterface::print_message_noninteractive( | |
| 178 | ✗ | std::format("\t[DEBUG] 🔗 curl_streaming_write_callback called, size: {}\n", realsize)); | |
| 179 | } | ||
| 180 | #endif | ||
| 181 | |||
| 182 | try { | ||
| 183 | ✗ | std::string chunk(contents, realsize); | |
| 184 | ✗ | curl_obj->process_chunk(chunk); | |
| 185 | ✗ | } catch (const std::exception& e) { | |
| 186 | ✗ | std::string message = std::format("Exception in curl_streaming_write_callback: {}", e.what()); | |
| 187 | ✗ | if (curl_obj->ui->backend_running() == false) { | |
| 188 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 189 | } else { | ||
| 190 | ✗ | curl_obj->ui->print_error(message); | |
| 191 | } | ||
| 192 | // Returning 0 aborts the transfer | ||
| 193 | ✗ | return 0; | |
| 194 | ✗ | } | |
| 195 | |||
| 196 | ✗ | return realsize; | |
| 197 | } | ||
| 198 | |||
| 199 | /** | ||
| 200 | * Buffers streamed response data and dispatches complete JSON lines. | ||
| 201 | * | ||
| 202 | * Appends the incoming chunk to stream_buffer and extracts every complete line | ||
| 203 | * (terminated by '\n'). A trailing '\r' is removed, so \r\n line endings work. | ||
| 204 | * Only lines that start with '{' are treated as JSON and passed to | ||
| 205 | * stream_callback. Other lines are skipped. Any incomplete trailing data stays | ||
| 206 | * in stream_buffer until the next chunk arrives. If no stream_callback is set, | ||
| 207 | * the line is dropped. | ||
| 208 | * | ||
| 209 | * Debug output goes to stdout only when no UserInterface is running. | ||
| 210 | * | ||
| 211 | * @param chunk The raw data received from the current CURL write callback. It | ||
| 212 | * may contain zero, one, or several complete lines, or a partial line. | ||
| 213 | * | ||
| 214 | * @note Each complete line is passed to stream_callback as a copy, so the | ||
| 215 | * callback may keep it. Lines that are not JSON objects are discarded. | ||
| 216 | */ | ||
| 217 | ✗ | void CurlUtils::process_chunk(const std::string& chunk) { | |
| 218 | #ifdef DEBUG | ||
| 219 | ✗ | if (this->ui->backend_running() == false) { | |
| 220 | ✗ | UserInterface::print_message_noninteractive( | |
| 221 | ✗ | std::format("\t[DEBUG] 🔥 process_chunk called with {}\n", chunk.size())); | |
| 222 | } | ||
| 223 | #endif | ||
| 224 | |||
| 225 | ✗ | this->stream_buffer += chunk; | |
| 226 | |||
| 227 | // Extract complete lines (ending with \n). | ||
| 228 | ✗ | size_t pos = 0; | |
| 229 | ✗ | while ((pos = this->stream_buffer.find('\n')) != std::string::npos) { | |
| 230 | ✗ | std::string line = this->stream_buffer.substr(0, pos); | |
| 231 | ✗ | this->stream_buffer.erase(0, pos + 1); | |
| 232 | |||
| 233 | // Trim trailing \r (HTTP line endings are \r\n). | ||
| 234 | ✗ | if (!line.empty() && line.back() == '\r') { | |
| 235 | ✗ | line.pop_back(); | |
| 236 | } | ||
| 237 | |||
| 238 | #ifdef DEBUG | ||
| 239 | ✗ | if (this->ui->backend_running() == false) { | |
| 240 | ✗ | UserInterface::print_message_noninteractive(std::format( | |
| 241 | ✗ | "\t[DEBUG] 🔥 Extracted line: {} {}\n", line.substr(0, 80), (line.size() > 80 ? "..." : ""))); | |
| 242 | } | ||
| 243 | #endif | ||
| 244 | |||
| 245 | ✗ | if (line.empty() || line[0] != '{') { | |
| 246 | #ifdef DEBUG | ||
| 247 | ✗ | if (this->ui->backend_running() == false) { | |
| 248 | ✗ | UserInterface::print_message_noninteractive(std::format("\t[DEBUG] 🔥 Skipping non-JSON line.\n")); | |
| 249 | } | ||
| 250 | #endif | ||
| 251 | ✗ | continue; | |
| 252 | } | ||
| 253 | |||
| 254 | // Pass only valid JSON lines to the callback. | ||
| 255 | ✗ | if (stream_callback) { | |
| 256 | #ifdef DEBUG | ||
| 257 | ✗ | if (this->ui->backend_running() == false) { | |
| 258 | ✗ | UserInterface::print_message_noninteractive(std::format("\t[DEBUG] 🔥 Calling stream_callback.\n")); | |
| 259 | } | ||
| 260 | #endif | ||
| 261 | ✗ | stream_callback(line); | |
| 262 | } else { | ||
| 263 | #ifdef DEBUG | ||
| 264 | ✗ | if (this->ui->backend_running() == false) { | |
| 265 | ✗ | UserInterface::print_message_noninteractive("⚠️ stream_callback is NULL!\n"); | |
| 266 | } | ||
| 267 | #endif | ||
| 268 | } | ||
| 269 | ✗ | } | |
| 270 | // Remaining incomplete data stays in stream_buffer for next chunk. | ||
| 271 | ✗ | } | |
| 272 | |||
| 273 | /** | ||
| 274 | * @brief Checks service availability by querying an HTTP endpoint and returning the HTTP status code. | ||
| 275 | * | ||
| 276 | * Makes a silent HEAD request to the specified URL with optional custom headers, | ||
| 277 | * discards the response body, and returns the HTTP status code. | ||
| 278 | * On curl failure, returns -1. | ||
| 279 | * | ||
| 280 | * @param url Target endpoint URL (e.g., "http://localhost:6333/collections"). | ||
| 281 | * @param extra_headers Map of custom headers to include (e.g., {"api-key": "secret", "Authorization": "Bearer | ||
| 282 | * token"}). If empty, request is sent without additional headers. | ||
| 283 | * @param timeout_seconds Connection and transfer timeout in seconds (default: 5). | ||
| 284 | * @return HTTP status code on success (e.g., 200, 401, 404); -1 on curl failure. | ||
| 285 | * @note Initializes and cleans up curl handle internally; manages spinner lifecycle. | ||
| 286 | * @see initialize(), cleanup() | ||
| 287 | */ | ||
| 288 | ✗ | long CurlUtils::check_service_status(const std::string& url, const std::map<std::string, std::string>& extra_headers, | |
| 289 | long timeout_seconds) { | ||
| 290 | ✗ | this->initialize(); | |
| 291 | ✗ | this->spinner->start(); | |
| 292 | |||
| 293 | ✗ | long http_code = 0; | |
| 294 | |||
| 295 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_URL, url.c_str()); | |
| 296 | |||
| 297 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_CUSTOMREQUEST, "GET"); | |
| 298 | |||
| 299 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_WRITEFUNCTION, | |
| 300 | [](void*, size_t size, size_t nmemb, void*) { return size * nmemb; }); | ||
| 301 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_TIMEOUT, timeout_seconds); | |
| 302 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_CONNECTTIMEOUT, timeout_seconds); | |
| 303 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_FOLLOWLOCATION, 1L); | |
| 304 | |||
| 305 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_NOPROGRESS, 0L); | |
| 306 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); | |
| 307 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_XFERINFODATA, this->spinner.get()); | |
| 308 | |||
| 309 | ✗ | curl_slist* new_headers = nullptr; | |
| 310 | ✗ | this->add_header(new_headers, "Content-Type: application/json"); | |
| 311 | |||
| 312 | ✗ | for (const auto& [key, value] : extra_headers) { | |
| 313 | ✗ | this->add_header(new_headers, key + ": " + value); | |
| 314 | } | ||
| 315 | ✗ | this->headers.reset(new_headers); | |
| 316 | |||
| 317 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_HTTPHEADER, this->headers.get()); | |
| 318 | |||
| 319 | ✗ | CURLcode res = curl_easy_perform(this->curl.get()); | |
| 320 | ✗ | this->spinner->stop(); | |
| 321 | |||
| 322 | ✗ | curl_easy_getinfo(this->curl.get(), CURLINFO_RESPONSE_CODE, &http_code); | |
| 323 | |||
| 324 | ✗ | this->cleanup(); | |
| 325 | |||
| 326 | ✗ | if (res != CURLE_OK) { | |
| 327 | ✗ | std::string message = std::format("Curl error: {}\n", curl_easy_strerror(res)); | |
| 328 | ✗ | if (this->ui->backend_running() == false) { | |
| 329 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 330 | } else { | ||
| 331 | ✗ | this->ui->print_error(message); | |
| 332 | } | ||
| 333 | |||
| 334 | ✗ | return -1; | |
| 335 | ✗ | } | |
| 336 | ✗ | return http_code; | |
| 337 | } | ||
| 338 | |||
| 339 | /** | ||
| 340 | * @brief Waits for a service to become available with retries and exponential backoff. | ||
| 341 | * | ||
| 342 | * @param url Target endpoint URL. | ||
| 343 | * @param extra_headers Map of custom headers. | ||
| 344 | * @param max_retries Number of retry attempts (default: 10). | ||
| 345 | * @param initial_delay_ms Initial delay in milliseconds (default: 500ms). | ||
| 346 | * @return HTTP status code on success; -1 if service unavailable after retries. | ||
| 347 | */ | ||
| 348 | ✗ | long CurlUtils::wait_for_service(const std::string& url, const std::map<std::string, std::string>& extra_headers, | |
| 349 | int max_retries, int initial_delay_ms) { | ||
| 350 | ✗ | long http_code = -1; | |
| 351 | ✗ | int delay_ms = initial_delay_ms; | |
| 352 | ✗ | std::string message{}; | |
| 353 | |||
| 354 | ✗ | for (int attempt = 0; attempt < max_retries; attempt += 1) { | |
| 355 | ✗ | http_code = this->check_service_status(url, extra_headers); | |
| 356 | |||
| 357 | ✗ | if (http_code != -1) { | |
| 358 | ✗ | message = std::format("Service available (HTTP {}) after {} attempt(s)\n", http_code, attempt + 1); | |
| 359 | ✗ | if (this->ui->backend_running() == false) { | |
| 360 | ✗ | UserInterface::print_success_noninteractive(message); | |
| 361 | } else { | ||
| 362 | ✗ | this->ui->print_success(message); | |
| 363 | } | ||
| 364 | ✗ | return http_code; | |
| 365 | } | ||
| 366 | |||
| 367 | ✗ | if (attempt < max_retries - 1) { | |
| 368 | ✗ | message = std::format("⏳ Waiting for service... (attempt {}/{}, retrying in {}ms)\n", attempt + 1, | |
| 369 | ✗ | max_retries, delay_ms); | |
| 370 | ✗ | if (this->ui->backend_running() == false) { | |
| 371 | ✗ | UserInterface::print_message_noninteractive(message); | |
| 372 | } else { | ||
| 373 | ✗ | this->ui->print_message(message); | |
| 374 | } | ||
| 375 | ✗ | std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); | |
| 376 | ✗ | delay_ms = std::min(delay_ms * 2, 5000); | |
| 377 | } | ||
| 378 | } | ||
| 379 | |||
| 380 | ✗ | message = std::format("Service unavailable after {} attempts\n", max_retries); | |
| 381 | ✗ | if (this->ui->backend_running() == false) { | |
| 382 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 383 | } else { | ||
| 384 | ✗ | this->ui->print_error(message); | |
| 385 | } | ||
| 386 | ✗ | return http_code; | |
| 387 | ✗ | } | |
| 388 | |||
| 389 | /** | ||
| 390 | * @brief Fetches web content from the specified URL via HTTP/HTTPS request. | ||
| 391 | * | ||
| 392 | * Performs an HTTP GET or POST request to the given URL using libcurl, | ||
| 393 | * with automatic redirect following and JSON content-type header. | ||
| 394 | * Shows a spinner while the request is in progress. | ||
| 395 | * | ||
| 396 | * @param url The target URL to fetch from. Must be a valid URL string. | ||
| 397 | * @param post_data Optional POST request body. If provided, the request | ||
| 398 | * will be a POST request; otherwise a GET request. | ||
| 399 | * Defaults to std::nullopt (GET request). | ||
| 400 | * @param custom_request_type Custom request type: GET, POST, PUT. Primarily used for PUT. | ||
| 401 | * @param extra_headers Optional map of custom headers to include (e.g., {"Authorization": "Bearer token"}). | ||
| 402 | * Content-Type application/json is always added automatically. | ||
| 403 | * Defaults to std::nullopt (no extra headers). | ||
| 404 | * @param fail_on_http_error If false, returns response body even on non-200 status codes. | ||
| 405 | * If true (default), exits on non-200 status. Used for existence checks. | ||
| 406 | * Defaults to true. | ||
| 407 | * | ||
| 408 | * @return A string containing the response body. | ||
| 409 | * | ||
| 410 | * @throws Calls std::exit(EXIT_FAILURE) on CURL errors or non-200 HTTP status codes | ||
| 411 | * if the UI is not running. If UI is running, terminates the | ||
| 412 | * session with EXIT_FAILURE. | ||
| 413 | * | ||
| 414 | * @note Initializes and cleans up CURL resources internally. | ||
| 415 | * Automatically manages HTTP headers and follows redirects. | ||
| 416 | * @see check_service_status() | ||
| 417 | */ | ||
| 418 | ✗ | std::string CurlUtils::fetch_web_content(const std::string& url, std::optional<std::string> post_data, | |
| 419 | std::optional<std::string> custom_request_type, | ||
| 420 | std::optional<std::map<std::string, std::string>> extra_headers, | ||
| 421 | bool fail_on_http_error) { | ||
| 422 | ✗ | struct WebContent content {}; | |
| 423 | ✗ | std::string message{}; | |
| 424 | |||
| 425 | ✗ | this->initialize(); | |
| 426 | ✗ | this->spinner->start(); | |
| 427 | |||
| 428 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_URL, url.c_str()); | |
| 429 | |||
| 430 | ✗ | if (post_data != std::nullopt) { | |
| 431 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_POSTFIELDS, post_data->c_str()); | |
| 432 | } | ||
| 433 | |||
| 434 | ✗ | if (custom_request_type != std::nullopt) { | |
| 435 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_CUSTOMREQUEST, custom_request_type->c_str()); | |
| 436 | } | ||
| 437 | |||
| 438 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_WRITEFUNCTION, CurlUtils::curl_write_callback); | |
| 439 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_WRITEDATA, &content.read_buffer); | |
| 440 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_ERRORBUFFER, content.error_buffer); | |
| 441 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_FOLLOWLOCATION, 1L); | |
| 442 | |||
| 443 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_NOPROGRESS, 0L); | |
| 444 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); | |
| 445 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_XFERINFODATA, this->spinner.get()); | |
| 446 | |||
| 447 | ✗ | curl_slist* new_headers = nullptr; | |
| 448 | ✗ | this->add_header(new_headers, "Content-Type: application/json"); | |
| 449 | |||
| 450 | ✗ | if (extra_headers != std::nullopt) { | |
| 451 | ✗ | for (const auto& [key, value] : extra_headers.value()) { | |
| 452 | ✗ | this->add_header(new_headers, key + ": " + value); | |
| 453 | } | ||
| 454 | } | ||
| 455 | ✗ | this->headers.reset(new_headers); | |
| 456 | |||
| 457 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_HTTPHEADER, this->headers.get()); | |
| 458 | |||
| 459 | ✗ | CURLcode result = curl_easy_perform(this->curl.get()); | |
| 460 | ✗ | this->spinner->stop(); | |
| 461 | |||
| 462 | ✗ | curl_easy_getinfo(this->curl.get(), CURLINFO_RESPONSE_CODE, &content.status); | |
| 463 | |||
| 464 | ✗ | this->cleanup(); | |
| 465 | |||
| 466 | ✗ | if (result != CURLE_OK) { | |
| 467 | ✗ | message = std::format("CURL error: {}\n", curl_easy_strerror(result)); | |
| 468 | ✗ | if (this->ui->backend_running() == false) { | |
| 469 | ✗ | if (content.error_buffer[0] != '\0') { | |
| 470 | ✗ | message += std::format("Details: {}\n", content.error_buffer); | |
| 471 | } | ||
| 472 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 473 | } else { | ||
| 474 | ✗ | this->ui->print_error(message); | |
| 475 | ✗ | if (content.error_buffer[0] != '\0') { | |
| 476 | ✗ | message = std::format("Details: {}\n", content.error_buffer); | |
| 477 | ✗ | this->ui->print_error(message); | |
| 478 | } | ||
| 479 | } | ||
| 480 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 481 | ✗ | } else if (content.status != 200) { | |
| 482 | ✗ | message = std::format("Request HTTP status: {}\n", content.status); | |
| 483 | ✗ | if (this->ui->backend_running() == false) { | |
| 484 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 485 | ✗ | if (fail_on_http_error == true) { | |
| 486 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 487 | } else { | ||
| 488 | ✗ | throw HttpException(content.status, url); | |
| 489 | } | ||
| 490 | } else { | ||
| 491 | ✗ | this->ui->print_error(message); | |
| 492 | ✗ | if (fail_on_http_error == true) { | |
| 493 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 494 | } else { | ||
| 495 | ✗ | throw HttpException(content.status, url); | |
| 496 | } | ||
| 497 | } | ||
| 498 | } | ||
| 499 | |||
| 500 | ✗ | return content.read_buffer; | |
| 501 | ✗ | } | |
| 502 | |||
| 503 | /** | ||
| 504 | * Performs an HTTP request and streams the response body to a callback. | ||
| 505 | * | ||
| 506 | * Stores on_chunk as the stream callback, then sends the request through the | ||
| 507 | * shared curl handle. The response body is passed through | ||
| 508 | * curl_streaming_write_callback and process_chunk, which deliver each complete | ||
| 509 | * JSON line to on_chunk as it arrives. Unlike fetch_web_content(), this method | ||
| 510 | * does not start the progress spinner. | ||
| 511 | * | ||
| 512 | * Content-Type: application/json is always sent. extra_headers are added after it. | ||
| 513 | * When the transfer finishes, the handle and headers are released through | ||
| 514 | * cleanup(). The returned WebContentStream reports whether the request succeeded, | ||
| 515 | * along with the HTTP status and any error message. | ||
| 516 | * | ||
| 517 | * On a CURL error or a non-200 status, the error is shown through the UI or to | ||
| 518 | * stdout and stderr. The process then exits (non-interactive mode, or when | ||
| 519 | * fail_on_http_error is true for an HTTP error) or the UI session ends with | ||
| 520 | * EXIT_FAILURE. When fail_on_http_error is false, an HTTP error throws an | ||
| 521 | * HttpException. | ||
| 522 | * | ||
| 523 | * @param url The request URL. | ||
| 524 | * @param post_data Optional request body, sent with CURLOPT_POSTFIELDS. | ||
| 525 | * @param on_chunk Callback invoked once for each complete JSON line in the response. | ||
| 526 | * @param custom_request_type Optional HTTP method override, such as "DELETE". | ||
| 527 | * @param extra_headers Optional additional headers, as name and value pairs. | ||
| 528 | * @param fail_on_http_error If true, a non-200 status ends the program instead of throwing. | ||
| 529 | * | ||
| 530 | * @return A WebContentStream with the HTTP status, the success flag, and the error message. | ||
| 531 | * | ||
| 532 | * @throws HttpException If the HTTP status is not 200 and fail_on_http_error is false. | ||
| 533 | * | ||
| 534 | * @note The post_data string must stay valid until curl_easy_perform() returns. | ||
| 535 | * content.status must be a long, because CURLINFO_RESPONSE_CODE writes a long. | ||
| 536 | */ | ||
| 537 | ✗ | WebContentStream CurlUtils::fetch_web_content_stream(const std::string& url, std::optional<std::string> post_data, | |
| 538 | std::function<void(const std::string&)> on_chunk, | ||
| 539 | std::optional<std::string> custom_request_type, | ||
| 540 | std::optional<std::map<std::string, std::string>> extra_headers, | ||
| 541 | bool fail_on_http_error) { | ||
| 542 | ✗ | this->stream_callback = on_chunk; | |
| 543 | |||
| 544 | ✗ | struct WebContentStream content {}; | |
| 545 | ✗ | std::string message{}; | |
| 546 | |||
| 547 | ✗ | this->initialize(); | |
| 548 | ✗ | this->stream_buffer.clear(); | |
| 549 | |||
| 550 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_URL, url.c_str()); | |
| 551 | |||
| 552 | ✗ | if (post_data != std::nullopt) { | |
| 553 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_POSTFIELDS, post_data->c_str()); | |
| 554 | } | ||
| 555 | |||
| 556 | ✗ | if (custom_request_type != std::nullopt) { | |
| 557 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_CUSTOMREQUEST, custom_request_type->c_str()); | |
| 558 | } | ||
| 559 | |||
| 560 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_WRITEFUNCTION, CurlUtils::curl_streaming_write_callback); | |
| 561 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_WRITEDATA, static_cast<void*>(this)); | |
| 562 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_ERRORBUFFER, content.error_buffer); | |
| 563 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_FOLLOWLOCATION, 1L); | |
| 564 | |||
| 565 | ✗ | curl_slist* new_headers = nullptr; | |
| 566 | ✗ | this->add_header(new_headers, "Content-Type: application/json"); | |
| 567 | |||
| 568 | ✗ | if (extra_headers != std::nullopt) { | |
| 569 | ✗ | for (const auto& [key, value] : extra_headers.value()) { | |
| 570 | ✗ | this->add_header(new_headers, key + ": " + value); | |
| 571 | } | ||
| 572 | } | ||
| 573 | |||
| 574 | ✗ | this->headers.reset(new_headers); | |
| 575 | |||
| 576 | ✗ | curl_easy_setopt(this->curl.get(), CURLOPT_HTTPHEADER, this->headers.get()); | |
| 577 | |||
| 578 | ✗ | CURLcode result = curl_easy_perform(this->curl.get()); | |
| 579 | |||
| 580 | ✗ | curl_easy_getinfo(this->curl.get(), CURLINFO_RESPONSE_CODE, &content.status); | |
| 581 | |||
| 582 | ✗ | this->cleanup(); | |
| 583 | |||
| 584 | ✗ | content.success = true; | |
| 585 | ✗ | if (result != CURLE_OK) { | |
| 586 | ✗ | content.success = false; | |
| 587 | ✗ | content.error_message = curl_easy_strerror(result); | |
| 588 | ✗ | message = std::format("CURL error: {}\n", curl_easy_strerror(result)); | |
| 589 | ✗ | if (this->ui->backend_running() == false) { | |
| 590 | ✗ | if (content.error_buffer[0] != '\0') { | |
| 591 | ✗ | message += std::format("Details: {}\n", content.error_buffer); | |
| 592 | } | ||
| 593 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 594 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 595 | } else { | ||
| 596 | ✗ | this->ui->print_error(message); | |
| 597 | ✗ | if (content.error_buffer[0] != '\0') { | |
| 598 | ✗ | message = std::format("Details: {}\n", content.error_buffer); | |
| 599 | ✗ | this->ui->print_error(message); | |
| 600 | } | ||
| 601 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 602 | } | ||
| 603 | ✗ | } else if (content.status != 200) { | |
| 604 | ✗ | content.success = false; | |
| 605 | ✗ | content.error_message = std::format("HTTP {}", content.status); | |
| 606 | ✗ | message = std::format("Request HTTP status: {}\n", content.status); | |
| 607 | ✗ | if (this->ui->backend_running() == false) { | |
| 608 | ✗ | UserInterface::print_error_noninteractive(message); | |
| 609 | ✗ | if (fail_on_http_error == true) { | |
| 610 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 611 | } else { | ||
| 612 | ✗ | throw HttpException(content.status, url); | |
| 613 | } | ||
| 614 | } else { | ||
| 615 | ✗ | this->ui->print_error(message); | |
| 616 | ✗ | if (fail_on_http_error == true) { | |
| 617 | ✗ | this->ui->end_session(EXIT_FAILURE); | |
| 618 | } else { | ||
| 619 | ✗ | throw HttpException(content.status, url); | |
| 620 | } | ||
| 621 | } | ||
| 622 | } | ||
| 623 | |||
| 624 | ✗ | return content; | |
| 625 | ✗ | } | |
| 626 |