#include "db.hpp" #include "errors.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace fs = std::filesystem; namespace { constexpr int kConnectTimeoutSeconds = 2; constexpr int kTcpUserTimeoutMs = 5000; constexpr int kStatementTimeoutMs = 5000; constexpr int kClientIoTimeoutSeconds = 5; constexpr auto kAcquireTimeout = std::chrono::seconds(3); std::string add_conn_param(std::string conninfo, const std::string& key, const std::string& value) { if (conninfo.find(key + "=") != std::string::npos) { return conninfo; } const bool is_url = conninfo.rfind("postgres://", 0) == 0 || conninfo.rfind("postgresql://", 0) == 0; if (is_url) { conninfo += (conninfo.find('?') == std::string::npos ? "?" : "&"); } else { conninfo += " "; } return conninfo + key + "=" + value; } bool is_alive(pqxx::connection* conn) { std::promise done; auto fut = done.get_future(); std::thread th([conn, &done]() { try { pqxx::nontransaction tx(*conn); tx.exec("SELECT 1"); done.set_value(); } catch (...) { done.set_exception(std::current_exception()); } }); if (fut.wait_for(std::chrono::seconds(kClientIoTimeoutSeconds)) != std::future_status::ready) { const int fd = conn->sock(); if (fd >= 0) { ::shutdown(fd, SHUT_RDWR); } th.join(); return false; } th.join(); try { fut.get(); return true; } catch (...) { return false; } } struct Migration { int version; std::string path; }; constexpr int kMigrationsAdvisoryLockKey = 0x6d747573; Migration parse_migration_name(const fs::path& p) { const std::string name = p.filename().string(); const auto dot = name.find('.'); if (dot == std::string::npos || name.substr(dot) != ".sql") { throw std::runtime_error("migration file must end with .sql: " + name); } const auto us = name.find('_'); if (us == std::string::npos || us == 0) { throw std::runtime_error( "migration file must be named NNN_name.sql: " + name); } const std::string num = name.substr(0, us); if (!std::all_of(num.begin(), num.end(), [](unsigned char c){ return std::isdigit(c); })) { throw std::runtime_error( "migration file prefix must be digits: " + name); } Migration m; m.version = std::stoi(num); m.path = p.string(); return m; }} void apply_migrations(pqxx::connection& conn, const std::string& dir) { { pqxx::work tx(conn); tx.exec("SELECT pg_advisory_lock($1)", pqxx::params{kMigrationsAdvisoryLockKey}); tx.commit(); } std::clog << "migration advisory lock acquired\n"; struct Unlock { pqxx::connection& c; ~Unlock() { try { pqxx::work tx(c); tx.exec("SELECT pg_advisory_unlock($1)", pqxx::params{kMigrationsAdvisoryLockKey}); tx.commit(); } catch (...) {} } } unlock_guard{conn}; { pqxx::work tx(conn); tx.exec( "CREATE TABLE IF NOT EXISTS schema_migrations (" " version int PRIMARY KEY," " applied_at timestamptz NOT NULL DEFAULT now()" ")"); tx.commit(); } if (!fs::exists(dir) || !fs::is_directory(dir)) { throw std::runtime_error("migrations dir not found: " + dir); } std::vector files; for (const auto& entry : fs::directory_iterator(dir)) { if (entry.is_regular_file()) { files.push_back(parse_migration_name(entry.path())); } } std::sort(files.begin(), files.end(), [](const Migration& a, const Migration& b){ return a.version < b.version; }); for (std::size_t i = 1; i < files.size(); ++i) { if (files[i].version == files[i-1].version) { throw std::runtime_error( "duplicate migration version: " + std::to_string(files[i].version)); } } std::set applied; { pqxx::work tx(conn); for (const auto& row : tx.exec("SELECT version FROM schema_migrations")) { applied.insert(row[0].as()); } tx.commit(); } for (const auto& m : files) { if (applied.count(m.version)) { continue; } std::ifstream f(m.path, std::ios::binary); if (!f) { throw std::runtime_error("cannot open migration: " + m.path); } std::stringstream buf; buf << f.rdbuf(); const std::string sql = buf.str(); pqxx::work tx(conn); tx.exec(sql); tx.exec("INSERT INTO schema_migrations(version) VALUES ($1)", m.version); tx.commit(); std::clog << "applied migration " << m.version << " (" << m.path << ")\n"; } } std::string read_secret_file(const char* env_name) { const char* path = std::getenv(env_name); if (path == nullptr || *path == '\0') { throw std::runtime_error( std::string("environment variable not set: ") + env_name); } std::ifstream f(path, std::ios::binary); if (!f) { throw std::runtime_error( std::string("cannot open secret file: ") + path); } std::string s; std::getline(f, s); if (!s.empty() && s.back() == '\r') { s.pop_back(); } if (s.empty()) { throw std::runtime_error( std::string("secret file is empty: ") + path); } return s; } bool is_dependency_failure(const std::exception& e) { if (dynamic_cast(&e) != nullptr || dynamic_cast(&e) != nullptr || dynamic_cast(&e) != nullptr) { return true; } if (const auto* sql = dynamic_cast(&e)) { // 08xxx — ошибки соединения, 57xxx — отмена (statement_timeout) и остановка сервера. const std::string& state = sql->sqlstate(); return state.rfind("08", 0) == 0 || state.rfind("57", 0) == 0; } return false; } std::unique_ptr open_pg_connection(const std::string& conninfo, bool statement_timeout) { std::string full = add_conn_param(conninfo, "connect_timeout", std::to_string(kConnectTimeoutSeconds)); full = add_conn_param(full, "tcp_user_timeout", std::to_string(kTcpUserTimeoutMs)); auto conn = std::make_unique(full); const int fd = conn->sock(); if (fd >= 0) { timeval tv{}; tv.tv_sec = kClientIoTimeoutSeconds; tv.tv_usec = 0; ::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); ::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); } if (statement_timeout) { pqxx::nontransaction tx(*conn); tx.exec("SET statement_timeout = " + std::to_string(kStatementTimeoutMs)); } return conn; } PgPool::PgPool(std::string conninfo, std::size_t n) : conninfo_(std::move(conninfo)) { if (n == 0) { throw std::runtime_error("PgPool: n must be > 0"); } all_.reserve(n); idle_.reserve(n); for (std::size_t i = 0; i < n; ++i) { auto conn = open_pg_connection(conninfo_, true); idle_.push_back(conn.get()); all_.push_back(std::move(conn)); } } PgPool::~PgPool() { { std::lock_guard lk(mu_); shutting_down_ = true; } cv_.notify_all(); } pqxx::connection* PgPool::take() { std::unique_lock lk(mu_); if (!cv_.wait_for(lk, kAcquireTimeout, [&]() { return shutting_down_ || !idle_.empty(); })) { throw DependencyUnavailable("postgres pool: acquire timeout"); } if (shutting_down_) { throw DependencyUnavailable("postgres pool is shutting down"); } pqxx::connection* conn = idle_.back(); idle_.pop_back(); lk.unlock(); if (is_alive(conn)) { return conn; } std::unique_ptr fresh; try { fresh = open_pg_connection(conninfo_, true); } catch (const std::exception& e) { // Мёртвое соединение возвращается в пул: следующий take() снова // попробует переподключиться, и пул не теряет слот. give_back(conn); throw DependencyUnavailable(std::string("postgres reconnect failed: ") + e.what()); } std::lock_guard lk2(mu_); for (auto& up : all_) { if (up.get() == conn) { up = std::move(fresh); return up.get(); } } throw std::logic_error("PgPool: connection not owned by pool"); } void PgPool::give_back(pqxx::connection* conn) { { std::lock_guard lk(mu_); idle_.push_back(conn); } cv_.notify_one(); } PgPool::Lease::Lease(PgPool& pool) : pool_(&pool), conn_(pool.take()) {} PgPool::Lease::~Lease() { if (pool_ != nullptr && conn_ != nullptr) { pool_->give_back(conn_); } } PgPool::Lease::Lease(Lease&& other) noexcept : pool_(other.pool_), conn_(other.conn_) { other.pool_ = nullptr; other.conn_ = nullptr; } PgPool::Lease PgPool::acquire() { return Lease(*this); } bool PgPool::ping() { try { auto lease = acquire(); pqxx::work tx(*lease); tx.exec("SELECT 1"); tx.commit(); return true; } catch (...) { return false; } }