#define YAMS_DAEMON_TEST_HOOKS_IMPL 1 // pi-lens-ignore: fatal error #include #undef YAMS_DAEMON_TEST_HOOKS_IMPL #include #include #include #include #include #include #include #include "transport_disconnect.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #include #include #include #endif namespace yams::daemon { ConnectionRegistry& ConnectionRegistry::instance() { // Deliberately process-lifetime. Static destruction can run after transport callback owners // have gone away; destroying the registry then must not traverse connection state. static ConnectionRegistry* const reg = new ConnectionRegistry(); return *reg; } void ConnectionRegistry::add(std::weak_ptr conn) { std::lock_guard lk(mutex_); connections_.push_back(std::move(conn)); } void ConnectionRegistry::closeAll() { std::lock_guard lk(mutex_); for (auto& weak : connections_) { if (auto conn = weak.lock()) { // Socket closure aborts pending I/O without invoking cancellation slots. // A one-shot CLI can destroy those slots before GlobalIOContext teardown; // emitting terminal cancellation then dereferences stale callback state. conn->close(); } } connections_.clear(); } using boost::asio::awaitable; using boost::asio::use_awaitable; namespace this_coro = boost::asio::this_coro; using boost::asio::as_tuple; using boost::asio::use_future; namespace { bool cli_one_shot_shutdown_enabled() { return yams::config::read_env_bool("YAMS_CLI_ONE_SHOT").valueOr(false); } void log_pool_debug(const char* message) noexcept { try { spdlog::debug("{}", message); } catch (...) { return; } } void log_pool_debug(const char* message, const std::exception& e) noexcept { try { spdlog::debug("{}: {}", message, e.what()); } catch (...) { return; } } bool should_run_stale_cleanup(std::atomic& last_cleanup_ns, std::chrono::steady_clock::time_point now) { constexpr int64_t kCleanupIntervalNs = 100'000'000; // 100ms const int64_t now_ns = std::chrono::duration_cast(now.time_since_epoch()).count(); int64_t last = last_cleanup_ns.load(std::memory_order_acquire); while ((now_ns - last) >= kCleanupIntervalNs) { if (last_cleanup_ns.compare_exchange_weak(last, now_ns, std::memory_order_acq_rel, std::memory_order_acquire)) { return true; } } return false; } awaitable>> async_connect_with_timeout(const TransportOptions& opts, boost::asio::any_io_executor socketExecutor) { // Check cancellation before proceeding auto cs = co_await this_coro::cancellation_state; if (cs.cancelled() != boost::asio::cancellation_type::none) { co_return Error{ErrorCode::OperationCancelled, "Operation cancelled"}; } // The coroutine's own cancellation slot: binding to it here (instead of the handler's // associated slot, which is not available during async_initiate) lets a terminal // cancellation resume this co_await with operation_aborted instead of destroying the // suspended frame. Without this, cancelling a pending connect leaves the co_spawn future // with no value (broken promise) and future::get() aborts under _GLIBCXX_ASSERTIONS. auto connectCancelSlot = cs.slot(); static constexpr bool trace = false; auto completion_executor = co_await this_coro::executor; auto io_executor = opts.executor.has_value() ? *opts.executor : GlobalIOContext::instance().get_io_context().get_executor(); auto socket = std::make_unique(socketExecutor); boost::asio::local::stream_protocol::endpoint endpoint(opts.socketPath.string()); if (trace) { spdlog::info("stream-trace: async_connect socket='{}'", opts.socketPath.string()); } // Race connect against timeout using async_initiate (no experimental APIs) using ConnectResult = std::tuple; using RaceResult = std::variant; const auto connect_start = std::chrono::steady_clock::now(); auto connect_result = co_await boost::asio::async_initiate< decltype(use_awaitable), void(std::exception_ptr, RaceResult)>( [&socket, &endpoint, io_executor, completion_executor, timeout = opts.requestTimeout, connectCancelSlot](auto handler) mutable { auto completed = std::make_shared>(false); auto timer = std::make_shared(io_executor); timer->expires_after(timeout); using HandlerT = std::decay_t; auto handlerPtr = std::make_shared(std::move(handler)); auto completion_exec = boost::asio::get_associated_executor(*handlerPtr, completion_executor); // Bind the coroutine's cancellation slot so a terminal cancellation resumes this // co_await with operation_aborted instead of destroying the suspended frame. if (connectCancelSlot.is_connected()) { connectCancelSlot.assign([completed, timer, handlerPtr, completion_exec]( boost::asio::cancellation_type type) mutable { if (type == boost::asio::cancellation_type::none) { return; } if (!completed->exchange(true, std::memory_order_acq_rel)) { timer->cancel(); boost::asio::post(completion_exec, [h = std::move(*handlerPtr)]() mutable { std::move(h)( std::exception_ptr{}, RaceResult(std::in_place_index<0>, ConnectResult{boost::asio::error::operation_aborted})); }); } }); } timer->async_wait([completed, handlerPtr, completion_exec](const boost::system::error_code& ec) mutable { if (ec == boost::asio::error::operation_aborted) return; if (!completed->exchange(true, std::memory_order_acq_rel)) { boost::asio::post(completion_exec, [h = std::move(*handlerPtr)]() mutable { std::move(h)(std::exception_ptr{}, RaceResult(std::in_place_index<1>, true)); }); } }); socket->async_connect(endpoint, [timer, completed, handlerPtr, completion_exec]( const boost::system::error_code& ec) mutable { if (!completed->exchange(true, std::memory_order_acq_rel)) { timer->cancel(); boost::asio::post(completion_exec, [h = std::move(*handlerPtr), ec]() mutable { std::move(h)(std::exception_ptr{}, RaceResult(std::in_place_index<0>, ConnectResult{ec})); }); } }); }, use_awaitable); if (connect_result.index() == 1) { if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - connect_start) .count(); spdlog::warn( "[IPCWait] stage=pool.connect timeout elapsed_ms={} timeout_ms={} socket='{}'", elapsed_ms, opts.requestTimeout.count(), opts.socketPath.string()); } co_await boost::asio::dispatch(socketExecutor, use_awaitable); boost::system::error_code closeEc; // NOLINTNEXTLINE(bugprone-unused-return-value): error_code overload reports via closeEc. socket->close(closeEc); if (closeEc) { log_pool_debug("Timed-out connection close reported an error"); } co_return Error{ErrorCode::Timeout, formatIpcFailure(IpcFailureKind::Timeout, "Connection timeout (socket='" + opts.socketPath.string() + "')")}; } auto& [ec] = std::get<0>(connect_result); if (ec) { if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - connect_start) .count(); spdlog::warn("[IPCWait] stage=pool.connect error='{}' elapsed_ms={} socket='{}'", ec.message(), elapsed_ms, opts.socketPath.string()); } if (ec == boost::asio::error::connection_refused || ec == make_error_code(boost::system::errc::connection_refused)) { co_return Error{ ErrorCode::NetworkError, formatIpcFailure(IpcFailureKind::Refused, std::string("Connection refused (socket='") + opts.socketPath.string() + "'). Is the daemon running? Try 'yams daemon start' or verify " "daemon.socket_path. " + ec.message())}; } co_return Error{ErrorCode::NetworkError, formatIpcFailure(IpcFailureKind::Other, std::string("Connection failed: ") + ec.message())}; } if (trace) { spdlog::info("stream-trace: async_connect succeeded socket='{}'", opts.socketPath.string()); } if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - connect_start) .count(); if (elapsed_ms >= ipc_wait_warn_ms()) { spdlog::info( "[IPCWait] stage=pool.connect slow elapsed_ms={} timeout_ms={} socket='{}'", elapsed_ms, opts.requestTimeout.count(), opts.socketPath.string()); } } co_return std::move(socket); } awaitable>> async_read_exact(AsioConnection::socket_t& socket, size_t size, std::chrono::milliseconds timeout) { // Check cancellation before proceeding auto cs = co_await this_coro::cancellation_state; if (cs.cancelled() != boost::asio::cancellation_type::none) { co_return Error{ErrorCode::OperationCancelled, "Operation cancelled"}; } auto buffer = std::make_shared>(size); auto executor = co_await this_coro::executor; // Race read against timeout using async_initiate (no experimental APIs) using ReadResult = std::tuple; using RaceResult = std::variant; const auto read_start = std::chrono::steady_clock::now(); auto read_result = co_await boost::asio::async_initiate( [&socket, buffer, executor, timeout](auto handler) mutable { auto completed = std::make_shared>(false); auto timer = std::make_shared(executor); timer->expires_after(timeout); using HandlerT = std::decay_t; auto handlerPtr = std::make_shared(std::move(handler)); auto completion_exec = boost::asio::get_associated_executor(*handlerPtr, executor); timer->async_wait([completed, handlerPtr, completion_exec](const boost::system::error_code& ec) mutable { if (ec == boost::asio::error::operation_aborted) return; if (!completed->exchange(true, std::memory_order_acq_rel)) { boost::asio::post(completion_exec, [h = std::move(*handlerPtr)]() mutable { std::move(h)(std::exception_ptr{}, RaceResult(std::in_place_index<1>, true)); }); } }); boost::asio::async_read( socket, boost::asio::buffer(*buffer), [timer, completed, handlerPtr, completion_exec, buffer](const boost::system::error_code& ec, std::size_t bytes) mutable { if (!completed->exchange(true, std::memory_order_acq_rel)) { timer->cancel(); boost::asio::post(completion_exec, [h = std::move(*handlerPtr), ec, bytes]() mutable { std::move(h)(std::exception_ptr{}, RaceResult(std::in_place_index<0>, ReadResult{ec, bytes})); }); } }); }, use_awaitable); if (read_result.index() == 1) { if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - read_start) .count(); spdlog::warn("[IPCWait] stage=pool.read timeout elapsed_ms={} size={} timeout_ms={}", elapsed_ms, size, timeout.count()); } co_return Error{ErrorCode::Timeout, formatIpcFailure(IpcFailureKind::Timeout, "Read timeout")}; } auto& [ec, bytes_read] = std::get<0>(read_result); if (ec) { if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - read_start) .count(); spdlog::warn("[IPCWait] stage=pool.read error='{}' elapsed_ms={} size={}", ec.message(), elapsed_ms, size); } if (ec == boost::asio::error::eof) { co_return Error{ErrorCode::NetworkError, formatIpcFailure(IpcFailureKind::Eof, detail::describeReadError(ec))}; } if (ec == boost::asio::error::operation_aborted) { co_return Error{ErrorCode::OperationCancelled, formatIpcFailure(IpcFailureKind::Cancelled, ec.message())}; } // A dropped AF_UNIX socket: EPIPE/ECONNRESET on Linux, ENOTCONN/ECONNABORTED on macOS. const auto kind = detail::isExpectedDisconnectError(ec) ? IpcFailureKind::ResetOrBrokenPipe : IpcFailureKind::Other; co_return Error{ErrorCode::NetworkError, formatIpcFailure(kind, detail::describeReadError(ec))}; } if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - read_start) .count(); if (elapsed_ms >= ipc_wait_warn_ms()) { spdlog::info( "[IPCWait] stage=pool.read slow elapsed_ms={} size={} bytes={} timeout_ms={}", elapsed_ms, size, bytes_read, timeout.count()); } } co_return std::move(*buffer); } bool socket_looks_healthy(AsioConnection::socket_t& socket) { #ifndef _WIN32 int fd = socket.native_handle(); pollfd pfd{}; pfd.fd = fd; pfd.events = POLLIN | POLLERR | POLLHUP | POLLNVAL; pfd.revents = 0; int res = ::poll(&pfd, 1, 0); if (res < 0) { if (errno == EINTR) { return true; } return false; } if (res == 0) { return true; } if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) { return false; } if (pfd.revents & POLLIN) { char buf{}; // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection): MSG_DONTWAIT never blocks ssize_t n = ::recv(fd, &buf, 1, MSG_PEEK | MSG_DONTWAIT); if (n == 0) { return false; } if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { return false; } } #endif return true; } bool socket_looks_healthy_cached(AsioConnection& conn, std::chrono::steady_clock::time_point now) { constexpr int64_t kTTLns = 100'000'000; // 100ms auto last = conn.last_health_check_ns.load(std::memory_order_relaxed); auto now_ns = now.time_since_epoch().count(); if ((now_ns - last) < kTTLns) { return true; } if (!conn.socket || !conn.socket->is_open()) { return false; } if (!socket_looks_healthy(*conn.socket)) { return false; } conn.last_health_check_ns.store(now_ns, std::memory_order_relaxed); return true; } } // namespace namespace { std::shared_mutex& registry_mutex() { // The pool registry is explicitly drained by shutdown_all(). Its synchronization storage must // remain valid through process teardown because late clients may still reach registry APIs. static std::shared_mutex* const mutex = new std::shared_mutex(); return *mutex; } std::unordered_map>& registry_map() { // Deliberately process-lifetime: destroying shared pools from an atexit callback would invoke // shutdown(), which emits cancellation into callback state whose static lifetime is unknown. static auto* const map = new std::unordered_map>(); return *map; } } // namespace AsioConnectionPool::AsioConnectionPool(const TransportOptions& opts, bool shared) : opts_(opts), shared_(shared) {} AsioConnectionPool::~AsioConnectionPool() { if (!shutdown_.load(std::memory_order_acquire)) { shutdown(std::chrono::milliseconds(500)); } } std::shared_ptr AsioConnectionPool::get_or_create(const TransportOptions& opts) { if (!opts.poolEnabled) { return std::make_shared(opts, false); } auto key = opts.socketPath.string(); // Fast path: check if pool exists with shared lock (concurrent reads) { std::shared_lock lk(registry_mutex()); auto& map = registry_map(); if (auto it = map.find(key); it != map.end()) { auto& pool = it->second; pool->widen_timeouts(opts); return pool; } } // Slow path: create new pool with exclusive lock (single writer) { std::lock_guard lk(registry_mutex()); auto& map = registry_map(); // Double-check: another thread may have created it while we waited if (auto it = map.find(key); it != map.end()) { auto& pool = it->second; pool->widen_timeouts(opts); return pool; } auto pool = std::make_shared(opts, true); map[key] = pool; return pool; } } void AsioConnectionPool::widen_timeouts(const TransportOptions& opts) { std::lock_guard lk(mutex_); if (opts.headerTimeout > opts_.headerTimeout) { opts_.headerTimeout = opts.headerTimeout; } if (opts.bodyTimeout > opts_.bodyTimeout) { opts_.bodyTimeout = opts.bodyTimeout; } if (opts.requestTimeout > opts_.requestTimeout) { opts_.requestTimeout = opts.requestTimeout; } } void AsioConnectionPool::shutdown_all(std::chrono::milliseconds timeout) { std::vector> pools; { std::lock_guard lk(registry_mutex()); auto& map = registry_map(); pools.reserve(map.size()); for (auto& [_, pool] : map) { if (pool) { pools.push_back(pool); } } } for (auto& pool : pools) { pool->shutdown(timeout); } { std::lock_guard lk(registry_mutex()); registry_map().clear(); } } AsioConnectionPool::RegistryStats AsioConnectionPool::registry_stats() { RegistryStats stats; std::vector> pools; { std::shared_lock lk(registry_mutex()); auto& map = registry_map(); pools.reserve(map.size()); for (auto& [_, pool] : map) { if (pool) { pools.push_back(pool); } } } stats.pools = pools.size(); for (auto& pool : pools) { if (!pool) { continue; } if (pool->shared_) { ++stats.sharedPools; } std::lock_guard lk(pool->mutex_); stats.trackedConnections += pool->connection_pool_.size(); for (const auto& weak : pool->connection_pool_) { auto conn = weak.lock(); if (!conn) { continue; } ++stats.liveConnections; if (conn->alive.load(std::memory_order_acquire)) { ++stats.aliveConnections; } if (conn->in_use.load(std::memory_order_acquire)) { ++stats.inUseConnections; } if (conn->socket && conn->socket->is_open()) { ++stats.openSockets; } } } return stats; } #if YAMS_DAEMON_TEST_HOOKS_ENABLED void AsioConnectionPool::testing_setRetryHook(TestingRetryHook hook) { std::lock_guard lk(mutex_); testing_retry_hook_ = std::move(hook); } #endif void AsioConnectionPool::cleanup_stale_connections() { std::erase_if(connection_pool_, [](const std::weak_ptr& weak) { auto conn = weak.lock(); if (!conn) { return true; } return !conn->alive.load(std::memory_order_acquire); }); } void AsioConnectionPool::retire_connection(const std::shared_ptr& conn, const char* reason) { if (!conn) { return; } conn->alive.store(false, std::memory_order_release); conn->streaming_started.store(false, std::memory_order_relaxed); conn->in_use.store(false, std::memory_order_release); conn->cancel(); if (reason && *reason) { spdlog::debug("ConnectionPool: retired connection ({}).", reason); } std::lock_guard lk(mutex_); std::erase_if(connection_pool_, [&](const std::weak_ptr& weak) { return weak.expired() || weak.lock() == conn; }); } awaitable>> AsioConnectionPool::acquire() { YAMS_ZONE_SYNC_N(acquireZone, "ConnectionPool::acquire"); const auto acquire_start = std::chrono::steady_clock::now(); // Check if pool is being shut down if (shutdown_.load(std::memory_order_acquire)) { co_return Error{ErrorCode::SystemShutdown, "Connection pool is shut down"}; } // Fast path: try to reuse an existing idle connection std::vector> pool_snapshot; size_t pool_size = 0; { YAMS_ZONE_SCOPED_N("ConnectionPool::acquire::tryReuse"); std::lock_guard lk(mutex_); if (should_run_stale_cleanup(this->last_cleanup_ns_, acquire_start)) { cleanup_stale_connections(); } pool_snapshot = connection_pool_; pool_size = pool_snapshot.size(); } for (auto& weak : pool_snapshot) { if (auto conn = weak.lock()) { if (conn->alive.load(std::memory_order_acquire) && !conn->in_use.exchange(true, std::memory_order_acq_rel)) { if (conn->read_loop_future.valid() && conn->read_loop_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) { conn->alive.store(false, std::memory_order_release); conn->in_use.store(false, std::memory_order_release); continue; } if (socket_looks_healthy_cached(*conn, acquire_start)) { if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - acquire_start) .count(); if (elapsed_ms >= ipc_wait_warn_ms()) { spdlog::info("[IPCWait] stage=pool.acquire.reuse slow elapsed_ms={} " "pool_size={}", elapsed_ms, pool_size); } } co_return conn; } conn->alive.store(false, std::memory_order_release); conn->in_use.store(false, std::memory_order_release); } } } YAMS_ZONE_END(acquireZone); // Slow path: create new connection auto created = co_await create_connection(); if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - acquire_start) .count(); if (elapsed_ms >= ipc_wait_warn_ms()) { spdlog::info("[IPCWait] stage=pool.acquire.create slow elapsed_ms={} ok={}", elapsed_ms, static_cast(created)); } } co_return created; } void AsioConnectionPool::release(const std::shared_ptr& conn) { YAMS_ZONE_SCOPED_N("ConnectionPool::release"); if (conn) { conn->last_health_check_ns.store(0, std::memory_order_relaxed); conn->in_use.store(false, std::memory_order_release); } } void AsioConnectionPool::shutdown(std::chrono::milliseconds timeout) { // Mark as shutdown first, preventing new operations if (shutdown_.exchange(true, std::memory_order_acq_rel)) { // Already shut down, skip return; } // Emit cancellation signal to abort any pending acquire/create_connection operations // This wakes up coroutines waiting on async_connect_with_timeout shutdown_signal_.emit(boost::asio::cancellation_type::terminal); std::vector> connections; { std::lock_guard lk(mutex_); connections.reserve(connection_pool_.size()); for (auto& weak : connection_pool_) { if (auto conn = weak.lock()) { connections.push_back(std::move(conn)); } } } auto effective_timeout = timeout; if (cli_one_shot_shutdown_enabled()) { // One-shot CLI callers should not block on a stuck read loop for the full request timeout. effective_timeout = std::min(effective_timeout, std::chrono::milliseconds(100)); } for (auto& conn : connections) { // Use cancel() to emit cancellation signals to all pending coroutines. Socket cancellation // is dispatched through the connection strand so it cannot race pending read/write ops. conn->cancel(); if (effective_timeout.count() > 0 && conn->read_loop_future.valid()) { try { auto status = conn->read_loop_future.wait_for(effective_timeout); (void)status; } catch (const std::exception& e) { log_pool_debug("Timed wait on read loop future threw", e); } catch (...) { log_pool_debug("Timed wait on read loop future threw unknown exception"); } } } if (effective_timeout.count() > 0) { std::unique_lock lk(mutex_); pending_create_cv_.wait_for(lk, effective_timeout, [&] { return pending_creates_ == 0; }); } { std::lock_guard lk(mutex_); connection_pool_.clear(); } } awaitable>> AsioConnectionPool::create_connection() { const auto create_start = std::chrono::steady_clock::now(); // This coroutine runs on the IO threads, which a pending reset() needs to finish the // creations it waits for: fail fast rather than block one of them on the lock. auto io_guard = GlobalIOContext::instance().try_acquire_operation_guard(); if (!io_guard.owns_lock()) { co_return Error{ErrorCode::SystemShutdown, "Client IO is being reset"}; } struct PendingCreateGuard { AsioConnectionPool& pool; bool active{false}; explicit PendingCreateGuard(AsioConnectionPool& p) : pool(p) { std::lock_guard lk(pool.mutex_); if (pool.shutdown_.load(std::memory_order_acquire)) { return; } ++pool.pending_creates_; active = true; } ~PendingCreateGuard() { if (!active) { return; } { std::lock_guard lk(pool.mutex_); if (pool.pending_creates_ > 0) { --pool.pending_creates_; } } pool.pending_create_cv_.notify_all(); } } pendingCreate(*this); if (!pendingCreate.active) { co_return Error{ErrorCode::SystemShutdown, "Connection pool is shut down"}; } auto conn = std::make_shared(opts_); auto socketMissing = [&]() { std::error_code ec; return !std::filesystem::exists(opts_.socketPath, ec); }; constexpr int kMaxRetries = 3; auto backoff = std::chrono::milliseconds(50); int attempts_used = 0; Result> socket_res = Error{ErrorCode::NetworkError, "Connection failed"}; for (int attempt = 0; attempt < kMaxRetries; ++attempt) { attempts_used = attempt + 1; if (socketMissing()) { if (attempt + 1 < kMaxRetries) { auto exec = co_await this_coro::executor; boost::asio::steady_timer timer(exec); timer.expires_after(backoff); try { co_await timer.async_wait(use_awaitable); } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::operation_aborted) { co_return Error{ErrorCode::SystemShutdown, "Connection pool shut down while connecting"}; } throw; } if (shutdown_.load(std::memory_order_acquire)) { co_return Error{ErrorCode::SystemShutdown, "Connection pool shut down while connecting"}; } backoff = std::min(backoff * 2, std::chrono::milliseconds(250)); continue; } } socket_res = co_await async_connect_with_timeout(opts_, conn->strand); if (socket_res) { break; } const auto failureKind = parseIpcFailureKind(socket_res.error().message); const bool retryable = socketMissing() || failureKind == IpcFailureKind::Refused; if (retryable && attempt + 1 < kMaxRetries) { #if YAMS_DAEMON_TEST_HOOKS_ENABLED if (failureKind == IpcFailureKind::Refused) { TestingRetryHook retryHook; { std::lock_guard lk(mutex_); retryHook = testing_retry_hook_; } if (retryHook) { retryHook(); } } #endif auto exec = co_await this_coro::executor; boost::asio::steady_timer timer(exec); timer.expires_after(backoff); try { co_await timer.async_wait(use_awaitable); } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::operation_aborted) { co_return Error{ErrorCode::SystemShutdown, "Connection pool shut down while connecting"}; } throw; } if (shutdown_.load(std::memory_order_acquire)) { co_return Error{ErrorCode::SystemShutdown, "Connection pool shut down while connecting"}; } backoff = std::min(backoff * 2, std::chrono::milliseconds(250)); continue; } break; } // Check shutdown after connection attempt - pool may have been shut down while connecting if (shutdown_.load(std::memory_order_acquire)) { // Close the socket if we got one, then bail if (socket_res && socket_res.value()) { co_await boost::asio::dispatch(conn->strand, use_awaitable); boost::system::error_code ec; // NOLINTNEXTLINE(bugprone-unused-return-value): error_code overload reports via ec. socket_res.value()->close(ec); if (ec) { log_pool_debug("Shutdown connection close reported an error"); } } co_return Error{ErrorCode::SystemShutdown, "Connection pool shut down while connecting"}; } if (!socket_res) { if (socketMissing()) { spdlog::debug("[ConnectionPool::create_connection] socket not available: {}", opts_.socketPath.string()); co_return Error{ErrorCode::NetworkError, formatIpcFailure(IpcFailureKind::SocketMissing, "Daemon not started (socket not found at '" + opts_.socketPath.string() + "').")}; } else { spdlog::debug("[ConnectionPool::create_connection] socket_res is error: {}", socket_res.error().message); // Preserve the underlying error (refused, timeout, etc.) instead of collapsing to // nullptr. const auto& msg = socket_res.error().message; if (parseIpcFailureKind(msg)) { co_return socket_res.error(); } co_return Error{socket_res.error().code, formatIpcFailure(IpcFailureKind::Other, msg)}; } } conn->socket = std::move(socket_res.value()); conn->alive.store(true, std::memory_order_release); conn->in_use.store(true, std::memory_order_release); // Mark as in-use for caller try { if (conn->socket && conn->socket->is_open()) { boost::asio::socket_base::send_buffer_size send_sz(64 * 1024); boost::asio::socket_base::receive_buffer_size recv_sz(64 * 1024); conn->socket->set_option(send_sz); conn->socket->set_option(recv_sz); } } catch (const std::exception& e) { log_pool_debug("Failed to tune socket buffer sizes", e); } catch (...) { log_pool_debug("Failed to tune socket buffer sizes"); } { std::lock_guard lk(mutex_); cleanup_stale_connections(); connection_pool_.push_back(conn); } // For non-shared pools, keep the pool alive as long as the connection is in use if (!shared_) { conn->pool_keepalive = shared_from_this(); } ConnectionRegistry::instance().add(conn); if (ipc_wait_trace_enabled()) { const auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - create_start) .count(); if (elapsed_ms >= ipc_wait_warn_ms()) { spdlog::info( "[IPCWait] stage=pool.create_connection slow elapsed_ms={} attempts={} socket='{}'", elapsed_ms, attempts_used, opts_.socketPath.string()); } } co_return conn; } awaitable AsioConnectionPool::ensure_read_loop_started(std::shared_ptr conn) { // Serialize read loop checks/starts on the connection's strand to prevent races co_await boost::asio::dispatch(conn->strand, use_awaitable); // Check if loop needs to be started/restarted bool need_start = false; if (!conn->read_started.load(std::memory_order_acquire)) { need_start = true; conn->read_started.store(true, std::memory_order_release); } else if (!conn->read_loop_future.valid()) { need_start = true; } else if (conn->read_loop_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) { try { conn->read_loop_future.get(); } catch (const std::exception& e) { log_pool_debug("Previous read loop exited with exception", e); } catch (...) { log_pool_debug("Previous read loop exited with unknown exception"); } need_start = true; } if (!need_start) { co_return; } auto weak_pool = weak_from_this(); conn->read_loop_future = co_spawn( conn->opts.executor.has_value() ? *conn->opts.executor : GlobalIOContext::instance().get_io_context().get_executor(), [conn, weak_pool]() -> awaitable { co_await boost::asio::post(conn->strand, use_awaitable); MessageFramer framer; for (;;) { // Check cancellation state at each iteration auto cs = co_await this_coro::cancellation_state; if (cs.cancelled() != boost::asio::cancellation_type::none) { co_return; } // Check connection's alive flag (set to false by cancel()) if (!conn->alive.load(std::memory_order_acquire)) { co_return; } if (!conn->socket || !conn->socket->is_open()) { co_return; } auto hres = co_await async_read_exact( *conn->socket, sizeof(MessageFramer::FrameHeader), conn->streaming_started.load(std::memory_order_relaxed) ? conn->opts.bodyTimeout : conn->opts.headerTimeout); if (!hres) { // If connection was cancelled, exit immediately without cleanup // (cleanup is handled by the shutdown code) if (!conn->alive.load(std::memory_order_acquire)) { co_return; } Error e = hres.error(); if (e.code == ErrorCode::OperationCancelled) { co_return; } // Preserve stable IPC classification when available. if (!parseIpcFailureKind(e.message)) { if (e.message == "Read timeout") { e.message = formatIpcFailure(IpcFailureKind::Timeout, e.message); } else if (e.message.find("End of file") != std::string::npos) { e.message = formatIpcFailure(IpcFailureKind::Eof, e.message); } } // Acquire strand before accessing handlers map co_await boost::asio::dispatch(conn->strand, use_awaitable); for (auto& [rid, h] : conn->handlers) { if (h.unary) { try { h.unary->promise->set_value(Result(e)); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (h.unary->notify_timer) { h.unary->notify_timer->cancel(); } } if (h.streaming) { h.streaming->onError(e); try { h.streaming->done_promise->set_value(Result(e)); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (h.streaming->notify_timer) { h.streaming->notify_timer->cancel(); } } } conn->handlers.clear(); conn->alive = false; conn->streaming_started.store(false, std::memory_order_relaxed); if (auto pool = weak_pool.lock()) { pool->retire_connection(conn, e.message.c_str()); } else { conn->cancel(); } co_return; } MessageFramer::FrameHeader netHeader; std::memcpy(&netHeader, hres.value().data(), sizeof(netHeader)); auto header = netHeader; header.from_network(); std::vector payload; if (header.payload_size > 0) { auto pres = co_await async_read_exact(*conn->socket, header.payload_size, conn->opts.bodyTimeout); if (!pres) { // If connection was cancelled, exit immediately without cleanup if (!conn->alive.load(std::memory_order_acquire)) { co_return; } Error e = pres.error(); if (e.code == ErrorCode::OperationCancelled) { co_return; } // Preserve stable IPC classification when available. if (!parseIpcFailureKind(e.message)) { if (e.message == "Read timeout") { e.message = formatIpcFailure(IpcFailureKind::Timeout, e.message); } else if (e.message.find("End of file") != std::string::npos) { e.message = formatIpcFailure(IpcFailureKind::Eof, e.message); } } // Acquire strand before accessing handlers map co_await boost::asio::dispatch(conn->strand, use_awaitable); for (auto& [rid, h] : conn->handlers) { if (h.unary) { try { h.unary->promise->set_value(Result(e)); } catch (const std::future_error& ex) { log_pool_debug( "Promise already satisfied while completing handler", ex); } // Cancel timer to wake up waiter if (h.unary->notify_timer) { h.unary->notify_timer->cancel(); } } if (h.streaming) { h.streaming->onError(e); try { h.streaming->done_promise->set_value(Result(e)); } catch (const std::future_error& ex) { log_pool_debug( "Promise already satisfied while completing handler", ex); } // Cancel timer to wake up waiter if (h.streaming->notify_timer) { h.streaming->notify_timer->cancel(); } } } conn->handlers.clear(); conn->alive = false; conn->streaming_started.store(false, std::memory_order_relaxed); if (auto pool = weak_pool.lock()) { pool->retire_connection(conn, e.message.c_str()); } else { conn->cancel(); } co_return; } payload = std::move(pres.value()); } std::vector frame; frame.reserve(sizeof(MessageFramer::FrameHeader) + payload.size()); frame.insert(frame.end(), hres.value().begin(), hres.value().end()); frame.insert(frame.end(), payload.begin(), payload.end()); auto msgRes = framer.parse_frame(frame); if (!msgRes) { // If connection was cancelled, exit immediately without cleanup if (!conn->alive.load(std::memory_order_acquire)) { co_return; } Error e{ErrorCode::InvalidData, "Failed to parse daemon response frame"}; // Acquire strand before accessing handlers map co_await boost::asio::dispatch(conn->strand, use_awaitable); for (auto& [rid, h] : conn->handlers) { if (h.unary) { try { h.unary->promise->set_value(Result(e)); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (h.unary->notify_timer) { h.unary->notify_timer->cancel(); } } if (h.streaming) { h.streaming->onError(e); try { h.streaming->done_promise->set_value(Result(e)); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (h.streaming->notify_timer) { h.streaming->notify_timer->cancel(); } } } conn->handlers.clear(); conn->alive = false; conn->streaming_started.store(false, std::memory_order_relaxed); if (auto pool = weak_pool.lock()) { pool->retire_connection(conn, e.message.c_str()); } else { conn->cancel(); } co_return; } auto& msg = msgRes.value(); static std::atomic warned{false}; if (!warned.load()) { try { if (msg.version < PROTOCOL_VERSION) { spdlog::warn( "Daemon protocol v{} < client v{}; consider upgrading daemon", msg.version, PROTOCOL_VERSION); warned.store(true); } else if (msg.version > PROTOCOL_VERSION) { spdlog::warn( "Daemon protocol v{} > client v{}; consider upgrading client", msg.version, PROTOCOL_VERSION); warned.store(true); } } catch (const std::exception& e) { log_pool_debug("Failed to emit protocol version warning", e); } catch (...) { log_pool_debug("Failed to emit protocol version warning"); } } uint64_t reqId = msg.requestId; // Check if connection was cancelled before trying strand dispatch if (!conn->alive.load(std::memory_order_acquire)) { co_return; } // Re-acquire strand protection before accessing handlers map // to prevent race with concurrent emplace() from send_request co_await boost::asio::dispatch(conn->strand, use_awaitable); AsioConnection::Handler* handlerPtr = nullptr; if (auto it = conn->handlers.find(reqId); it != conn->handlers.end()) { handlerPtr = &it->second; } if (!handlerPtr) { bool wasTimedOut = false; if (auto it = conn->timed_out_requests.find(reqId); it != conn->timed_out_requests.end()) { wasTimedOut = true; conn->timed_out_requests.erase(it); } try { if (wasTimedOut) { spdlog::debug("ASIO read loop: late daemon response after timeout " "(request id {})", reqId); } else { spdlog::warn( "ASIO read loop: no handler for daemon response with request " "id {}. This may indicate a response was already received or " "the request timed out.", reqId); } } catch (const std::exception& e) { log_pool_debug("Failed to log missing handler response", e); } catch (...) { log_pool_debug("Failed to log missing handler response"); } continue; } bool isChunked = header.is_chunked(); bool isHeaderOnly = header.is_header_only(); bool isLast = header.is_last_chunk(); // Move the response to avoid copying large vectors (e.g., DeleteResponse with // many results) Response r = std::move(std::get(msg.payload)); if (!isChunked) { if (handlerPtr->unary) { try { handlerPtr->unary->promise->set_value(Result(std::move(r))); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel the notify timer to wake up the waiter immediately if (handlerPtr->unary->notify_timer) { handlerPtr->unary->notify_timer->cancel(); } conn->handlers.erase(reqId); } else if (handlerPtr->streaming) { handlerPtr->streaming->onHeader(r); handlerPtr->streaming->onComplete(); try { handlerPtr->streaming->done_promise->set_value(Result()); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (handlerPtr->streaming->notify_timer) { handlerPtr->streaming->notify_timer->cancel(); } conn->handlers.erase(reqId); conn->streaming_started.store(false, std::memory_order_relaxed); } continue; } if (handlerPtr->streaming) { if (isHeaderOnly) { conn->streaming_started.store(true, std::memory_order_relaxed); handlerPtr->streaming->onHeader(r); } else { bool cont = handlerPtr->streaming->onChunk(r, isLast); if (!cont || isLast) { handlerPtr->streaming->onComplete(); try { handlerPtr->streaming->done_promise->set_value(Result()); } catch (const std::future_error& e) { log_pool_debug("Promise already satisfied while completing handler", e); } // Cancel timer to wake up waiter if (handlerPtr->streaming->notify_timer) { handlerPtr->streaming->notify_timer->cancel(); } conn->handlers.erase(reqId); conn->streaming_started.store(false, std::memory_order_relaxed); } } } } }, boost::asio::use_future); co_return; } } // namespace yams::daemon