Line data Source code
1 : #include "async_client.hpp"
2 : #include "../../util/logger.hpp"
3 :
4 : namespace thinger::http {
5 :
6 241 : async_client::async_client()
7 723 : : worker_client("http_async_client") {
8 241 : LOG_DEBUG("Created HTTP async client");
9 241 : }
10 :
11 241 : async_client::~async_client() {
12 241 : LOG_DEBUG("Destroying HTTP async client");
13 241 : if (is_running()) {
14 235 : stop();
15 : }
16 241 : }
17 :
18 421 : void async_client::track_request_start() {
19 421 : ++active_requests_;
20 842 : LOG_DEBUG("Async client: request started, active: {}", active_requests_.load());
21 421 : }
22 :
23 403 : void async_client::track_request_end() {
24 403 : size_t remaining = --active_requests_;
25 403 : LOG_DEBUG("Async client: request ended, active: {}", remaining);
26 :
27 403 : if (remaining == 0) {
28 181 : std::lock_guard<std::mutex> lock(requests_mutex_);
29 181 : requests_cv_.notify_all();
30 181 : }
31 403 : }
32 :
33 244 : bool async_client::stop() {
34 244 : LOG_DEBUG("Stopping HTTP async client");
35 :
36 : // Call base implementation
37 244 : bool result = worker_client::stop();
38 :
39 : // Notify any waiters
40 : {
41 244 : std::lock_guard<std::mutex> lock(requests_mutex_);
42 244 : requests_cv_.notify_all();
43 244 : }
44 :
45 244 : return result;
46 : }
47 :
48 175 : void async_client::wait() {
49 175 : std::unique_lock<std::mutex> lock(requests_mutex_);
50 :
51 : // Wait until no active requests or client stopped
52 175 : requests_cv_.wait(lock, [this] {
53 341 : return active_requests_ == 0 || !running_;
54 : });
55 175 : }
56 :
57 21 : bool async_client::wait_for(std::chrono::milliseconds timeout) {
58 21 : std::unique_lock<std::mutex> lock(requests_mutex_);
59 :
60 : // Wait with timeout
61 21 : bool completed = requests_cv_.wait_for(lock, timeout, [this] {
62 42 : return active_requests_ == 0 || !running_;
63 : });
64 :
65 42 : return completed && active_requests_ == 0;
66 21 : }
67 :
68 : } // namespace thinger::http
|