Files
moloapp/src/clients/pool.h
T
retoor 3c4334cec9 feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security,
data, app, realtime, supervisor, clients, CLI, example plus
enterprise tenancy, audit, operability, governance,
supplychain. Postgres via docker compose for tests.
2026-10-23 18:20:04 +02:00

66 lines
1.9 KiB
C++

#pragma once
// Keep-alive connection pool. Owns idle socket fds keyed by pool key,
// enforces per-client, per-host, and idle caps with bounded acquire waits.
#include <chrono>
#include <cstddef>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <vector>
namespace molo::clients {
struct PooledConnection {
int fd = -1;
std::chrono::steady_clock::time_point idle_since;
std::chrono::steady_clock::time_point expires_at;
};
struct PoolStats {
std::size_t in_use = 0;
std::size_t idle = 0;
std::size_t created = 0;
std::size_t reused = 0;
std::size_t closed = 0;
std::size_t evicted_idle_overflow = 0;
};
class ConnectionPool {
public:
ConnectionPool();
~ConnectionPool();
ConnectionPool(const ConnectionPool&) = delete;
ConnectionPool& operator=(const ConnectionPool&) = delete;
// Takes an idle connection for key, or nullopt when none is reusable.
std::optional<PooledConnection> acquire(const std::string& key);
// Returns a connection to the idle set (reusable=true) or closes it.
void release(const std::string& key, int fd, bool reusable);
// Records that the caller opened a fresh connection outside the pool.
// Returns false when the per-host or total cap forbids a new connection.
bool reserve(const std::string& key);
// Drops a reservation made by reserve() (connect failed).
void drop_reservation(const std::string& key);
// Closes a connection that bypassed release() (I/O error mid-use).
void discard(int fd);
void close_all();
PoolStats stats() const;
private:
void prune_locked(const std::string& key,
std::chrono::steady_clock::time_point now);
mutable std::mutex mutex_;
std::map<std::string, std::vector<PooledConnection>> idle_;
std::map<std::string, std::size_t> in_use_;
std::size_t total_ = 0;
PoolStats stats_;
};
} // namespace molo::clients