lab2
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-16 05:27:13 +03:00
parent 65003b6119
commit 50b30b4b47
46 changed files with 6221 additions and 14 deletions
+39
View File
@@ -0,0 +1,39 @@
#include "auth.hpp"
#include <sodium.h>
#include <stdexcept>
namespace {
struct SodiumInit {
SodiumInit() {
if (sodium_init() < 0) {
throw std::runtime_error("sodium_init failed");
}
}
};
const SodiumInit g_sodium_init;
}
std::string hash_password(const std::string& plain) {
char hashed[crypto_pwhash_STRBYTES];
if (crypto_pwhash_str(
hashed,
plain.data(), plain.size(),
crypto_pwhash_OPSLIMIT_INTERACTIVE,
crypto_pwhash_MEMLIMIT_INTERACTIVE) != 0) {
throw std::runtime_error("crypto_pwhash_str failed (out of memory?)");
}
return std::string(hashed);
}
bool verify_password(const std::string& plain, const std::string& hash) {
if (hash.empty() || hash.size() >= crypto_pwhash_STRBYTES) {
return false;
}
return crypto_pwhash_str_verify(
hash.c_str(),
plain.data(), plain.size()) == 0;
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <string>
std::string hash_password(const std::string& plain);
bool verify_password(const std::string& plain, const std::string& hash);
+175
View File
@@ -0,0 +1,175 @@
#include "chat_repo.hpp"
#include "cursor.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <random>
#include <sstream>
#include <string>
namespace {
std::string make_uuid() {
static std::mt19937_64 rng{std::random_device{}()};
std::uniform_int_distribution<uint32_t> d16(0, 0xffff);
std::uniform_int_distribution<uint32_t> d32(0, 0xffffffffu);
std::ostringstream out;
out << std::hex << std::setfill('0');
out << std::setw(8) << d32(rng);
out << '-' << std::setw(4) << d16(rng);
out << '-' << std::setw(4) << ((d16(rng) & 0x0fff) | 0x4000);
out << '-' << std::setw(4) << ((d16(rng) & 0x3fff) | 0x8000);
out << '-' << std::setw(4) << d16(rng) << std::setw(8) << d32(rng);
return out.str();
}
std::string epoch_to_rfc3339(long long epoch) {
const std::time_t t = static_cast<std::time_t>(epoch);
std::tm tm{};
gmtime_r(&t, &tm);
std::ostringstream out;
out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
return out.str();
}
std::string now_epoch_str() {
const auto now = std::chrono::system_clock::now();
const auto secs = std::chrono::duration_cast<std::chrono::seconds>(
now.time_since_epoch()).count();
return std::to_string(secs);
}
Chat row_to_chat(const pqxx::row& r) {
Chat c;
c.id = r["id"].as<std::string>();
c.title = r["title"].as<std::string>();
c.created_at = epoch_to_rfc3339(r["created_at_epoch"].as<long long>());
return c;
}
std::vector<std::string> load_member_ids(pqxx::work& tx,
const std::string& chat_id) {
std::vector<std::string> ids;
auto r = tx.exec(
"SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id",
pqxx::params{chat_id});
ids.reserve(r.size());
for (const auto& row : r) {
ids.push_back(row["user_id"].as<std::string>());
}
return ids;
}
constexpr const char* kChatSelect =
"id, title, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch";
}
std::optional<Chat> ChatRepo::create(const std::string& title,
const std::vector<std::string>& member_ids) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string chat_id = make_uuid();
const std::string created = now_epoch_str();
try {
tx.exec(
"INSERT INTO chats (id, title, created_at) "
"VALUES ($1, $2, to_timestamp($3::bigint))",
pqxx::params{chat_id, title, created});
for (const auto& uid : member_ids) {
tx.exec(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
pqxx::params{chat_id, uid});
}
} catch (const pqxx::foreign_key_violation&) {
tx.abort();
return std::nullopt;
} catch (const pqxx::unique_violation&) {
tx.abort();
return std::nullopt;
}
auto r = tx.exec(
"SELECT " + std::string(kChatSelect) + " FROM chats WHERE id = $1",
pqxx::params{chat_id});
Chat c = row_to_chat(r[0]);
c.member_ids = load_member_ids(tx, chat_id);
tx.commit();
return c;
}
std::optional<Chat> ChatRepo::find_by_id(const std::string& id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT " + std::string(kChatSelect) + " FROM chats WHERE id = $1",
pqxx::params{id});
if (r.empty()) {
tx.commit();
return std::nullopt;
}
Chat c = row_to_chat(r[0]);
c.member_ids = load_member_ids(tx, id);
tx.commit();
return c;
}
std::optional<ChatPage> ChatRepo::list_for_user(
const std::string& user_id,
int limit,
const std::optional<std::string>& cursor) {
std::optional<Cursor> cur;
if (cursor) {
cur = parse_cursor(*cursor);
if (!cur) {
return std::nullopt;
}
}
auto lease = pool_.acquire();
pqxx::work tx(*lease);
std::string sql =
"SELECT " + std::string(kChatSelect) + ", " + kCreatedUsSql + " "
"FROM chats "
"WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id = $1) ";
if (cur) {
sql += "AND (created_at, id) > (" + std::string(kCursorTimestampSql) + ", $4::uuid) ";
}
sql += "ORDER BY created_at ASC, id ASC LIMIT $2";
pqxx::result r;
if (cur) {
r = tx.exec(sql, pqxx::params{user_id, limit + 1, cur->created_us, cur->id});
} else {
r = tx.exec(sql, pqxx::params{user_id, limit + 1});
}
ChatPage page;
const bool has_more = (static_cast<int>(r.size()) > limit);
const int take = has_more ? limit : static_cast<int>(r.size());
page.items.reserve(take);
for (int i = 0; i < take; ++i) {
Chat c = row_to_chat(r[static_cast<std::size_t>(i)]);
c.member_ids = load_member_ids(tx, c.id);
page.items.push_back(std::move(c));
}
if (has_more && take > 0) {
const auto& last = r[static_cast<std::size_t>(take - 1)];
page.next_cursor = make_cursor(last["created_us"].as<std::string>(),
last["id"].as<std::string>());
}
tx.commit();
return page;
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
#include <vector>
class ChatRepo {
public:
explicit ChatRepo(PgPool& pool) : pool_(pool) {}
std::optional<Chat> create(const std::string& title,
const std::vector<std::string>& member_ids);
std::optional<Chat> find_by_id(const std::string& id);
std::optional<ChatPage> list_for_user(const std::string& user_id, int limit, const std::optional<std::string>& cursor);
private:
PgPool& pool_;
};
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <optional>
#include <regex>
#include <string>
// Непрозрачный для клиента курсор keyset-пагинации: "<created_at в мкс от epoch>|<uuid>".
// Микросекунды сохраняют точный created_at строки, даже если в JSON время округлено до секунд.
struct Cursor {
std::string created_us;
std::string id;
};
// Выражение SQL, восстанавливающее timestamptz из created_us без потери точности.
constexpr const char* kCursorTimestampSql =
"(timestamptz 'epoch' + $3::bigint * interval '1 microsecond')";
constexpr const char* kCreatedUsSql =
"(EXTRACT(EPOCH FROM created_at) * 1000000)::bigint AS created_us";
inline bool is_uuid(const std::string& s) {
static const std::regex re(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
return std::regex_match(s, re);
}
inline std::optional<Cursor> parse_cursor(const std::string& raw) {
const auto bar = raw.find('|');
if (bar == std::string::npos) {
return std::nullopt;
}
Cursor c{raw.substr(0, bar), raw.substr(bar + 1)};
const bool digits = !c.created_us.empty() && c.created_us.size() <= 18 &&
std::all_of(c.created_us.begin(), c.created_us.end(),
[](unsigned char ch) { return std::isdigit(ch); });
if (!digits || !is_uuid(c.id)) {
return std::nullopt;
}
return c;
}
inline std::string make_cursor(const std::string& created_us, const std::string& id) {
return created_us + "|" + id;
}
+306
View File
@@ -0,0 +1,306 @@
#include "db.hpp"
#include "errors.hpp"
#include <chrono>
#include <fstream>
#include <stdexcept>
#include <algorithm>
#include <filesystem>
#include <vector>
#include <set>
#include <iostream>
#include <nlohmann/json.hpp>
namespace fs = std::filesystem;
namespace {
constexpr int kConnectTimeoutSeconds = 2;
constexpr int kTcpUserTimeoutMs = 5000;
constexpr int kStatementTimeoutMs = 5000;
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) {
try {
pqxx::nontransaction tx(*conn);
tx.exec("SELECT 1");
return true;
} catch (...) {
return false;
}
}
struct Migration {
int version;
std::string path;
};
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(
"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<Migration> 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<int> applied;
{
pqxx::work tx(conn);
for (const auto& row : tx.exec("SELECT version FROM schema_migrations")) {
applied.insert(row[0].as<int>());
}
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<const DependencyUnavailable*>(&e) != nullptr ||
dynamic_cast<const pqxx::broken_connection*>(&e) != nullptr ||
dynamic_cast<const pqxx::in_doubt_error*>(&e) != nullptr) {
return true;
}
if (const auto* sql = dynamic_cast<const pqxx::sql_error*>(&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<pqxx::connection> 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<pqxx::connection>(full);
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<std::mutex> lk(mu_);
shutting_down_ = true;
}
cv_.notify_all();
}
pqxx::connection* PgPool::take() {
std::unique_lock<std::mutex> 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<pqxx::connection> 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<std::mutex> 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<std::mutex> 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;
}
}
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include <condition_variable>
#include <pqxx/pqxx>
#include <cstddef>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
std::string read_secret_file(const char* env_name);
// connect_timeout и tcp_user_timeout добавляются к conninfo, если не заданы;
// statement_timeout — только для соединений пула (миграции могут быть долгими).
std::unique_ptr<pqxx::connection> open_pg_connection(const std::string& conninfo,
bool statement_timeout);
void apply_migrations(pqxx::connection& conn, const std::string& dir);
class PgPool {
public:
bool ping();
PgPool(std::string conninfo, std::size_t n);
~PgPool();
PgPool(const PgPool&) = delete;
PgPool& operator=(const PgPool&) = delete;
class Lease {
public:
explicit Lease(PgPool& pool);
~Lease();
Lease(Lease&& other) noexcept;
Lease& operator=(Lease&&) = delete;
Lease(const Lease&) = delete;
Lease& operator=(const Lease&) = delete;
pqxx::connection& operator*() const { return *conn_; }
pqxx::connection* operator->() const { return conn_; }
private:
PgPool* pool_;
pqxx::connection* conn_;
};
Lease acquire();
private:
friend class Lease;
pqxx::connection* take();
void give_back(pqxx::connection* conn);
std::string conninfo_;
std::vector<std::unique_ptr<pqxx::connection>> all_;
std::vector<pqxx::connection*> idle_;
std::mutex mu_;
std::condition_variable cv_;
bool shutting_down_ = false;
};
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <exception>
#include <stdexcept>
// PostgreSQL или Valkey недоступны либо не ответили вовремя: клиент получает 503.
struct DependencyUnavailable : std::runtime_error {
using std::runtime_error::runtime_error;
};
bool is_dependency_failure(const std::exception& e);
+1241
View File
File diff suppressed because it is too large Load Diff
+146
View File
@@ -0,0 +1,146 @@
#include "message_repo.hpp"
#include "cursor.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <random>
#include <sstream>
#include <string>
namespace {
std::string make_uuid() {
static std::mt19937_64 rng{std::random_device{}()};
std::uniform_int_distribution<uint32_t> d16(0, 0xffff);
std::uniform_int_distribution<uint32_t> d32(0, 0xffffffffu);
std::ostringstream out;
out << std::hex << std::setfill('0');
out << std::setw(8) << d32(rng);
out << '-' << std::setw(4) << d16(rng);
out << '-' << std::setw(4) << ((d16(rng) & 0x0fff) | 0x4000);
out << '-' << std::setw(4) << ((d16(rng) & 0x3fff) | 0x8000);
out << '-' << std::setw(4) << d16(rng) << std::setw(8) << d32(rng);
return out.str();
}
std::string epoch_to_rfc3339(long long epoch) {
const std::time_t t = static_cast<std::time_t>(epoch);
std::tm tm{};
gmtime_r(&t, &tm);
std::ostringstream out;
out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
return out.str();
}
std::string now_epoch_str() {
const auto now = std::chrono::system_clock::now();
const auto secs = std::chrono::duration_cast<std::chrono::seconds>(
now.time_since_epoch()).count();
return std::to_string(secs);
}
Message row_to_message(const pqxx::row& r) {
Message m;
m.id = r["id"].as<std::string>();
m.chat_id = r["chat_id"].as<std::string>();
m.sender_id = r["sender_id"].as<std::string>();
m.text = r["text"].as<std::string>();
m.created_at = epoch_to_rfc3339(r["created_at_epoch"].as<long long>());
return m;
}
constexpr const char* kMessageSelect =
"id, chat_id, sender_id, text, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch";
}
std::optional<Message> MessageRepo::create(const std::string& chat_id,
const std::string& sender_id,
const std::string& text) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto member_check = tx.exec(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
pqxx::params{chat_id, sender_id});
if (member_check.empty()) {
tx.commit();
return std::nullopt;
}
const std::string id = make_uuid();
const std::string created = now_epoch_str();
auto r = tx.exec(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"VALUES ($1, $2, $3, $4, to_timestamp($5::bigint)) "
"RETURNING " + std::string(kMessageSelect),
pqxx::params{id, chat_id, sender_id, text, created});
tx.commit();
return row_to_message(r[0]);
}
std::optional<MessagePage> MessageRepo::list_page(
const std::string& chat_id,
int limit,
const std::optional<std::string>& cursor) {
std::optional<Cursor> cur;
if (cursor) {
cur = parse_cursor(*cursor);
if (!cur) {
return std::nullopt;
}
}
auto lease = pool_.acquire();
pqxx::work tx(*lease);
if (cur) {
auto owner_check = tx.exec(
"SELECT 1 FROM messages WHERE id = $1 AND chat_id = $2",
pqxx::params{cur->id, chat_id});
if (owner_check.empty()) {
tx.commit();
return std::nullopt;
}
}
std::string sql =
"SELECT " + std::string(kMessageSelect) + ", " + kCreatedUsSql + " "
"FROM messages "
"WHERE chat_id = $1 ";
if (cur) {
sql += "AND (created_at, id) > (" + std::string(kCursorTimestampSql) + ", $4::uuid) ";
}
sql += "ORDER BY created_at ASC, id ASC LIMIT $2";
pqxx::result r;
if (cur) {
r = tx.exec(sql, pqxx::params{chat_id, limit + 1, cur->created_us, cur->id});
} else {
r = tx.exec(sql, pqxx::params{chat_id, limit + 1});
}
MessagePage page;
const bool has_more = (static_cast<int>(r.size()) > limit);
const int take = has_more ? limit : static_cast<int>(r.size());
page.items.reserve(take);
for (int i = 0; i < take; ++i) {
page.items.push_back(row_to_message(r[static_cast<std::size_t>(i)]));
}
if (has_more && take > 0) {
const auto& last = r[static_cast<std::size_t>(take - 1)];
page.next_cursor = make_cursor(last["created_us"].as<std::string>(),
last["id"].as<std::string>());
}
tx.commit();
return page;
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
#include <vector>
class MessageRepo {
public:
explicit MessageRepo(PgPool& pool) : pool_(pool) {}
std::optional<Message> create(const std::string& chat_id,
const std::string& sender_id,
const std::string& text);
std::optional<MessagePage> list_page(
const std::string& chat_id,
int limit,
const std::optional<std::string>& cursor);
private:
PgPool& pool_;
};
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <optional>
#include <string>
#include <vector>
struct User {
std::string id;
std::string username;
std::string display_name;
std::string password_hash;
std::string created_at;
};
struct Chat {
std::string id;
std::string title;
std::vector<std::string> member_ids;
std::string created_at;
};
struct Message {
std::string id;
std::string chat_id;
std::string sender_id;
std::string text;
std::string created_at;
};
struct MessagePage {
std::vector<Message> items;
std::optional<std::string> next_cursor;
};
struct ChatPage {
std::vector<Chat> items;
std::optional<std::string> next_cursor;
};
+66
View File
@@ -0,0 +1,66 @@
#include "pg_session_repo.hpp"
#include <pqxx/pqxx>
#include <sodium.h>
#include <ctime>
#include <stdexcept>
#include <string>
namespace {
std::string random_token_hex() {
unsigned char buf[32];
randombytes_buf(buf, sizeof(buf));
static const char hex[] = "0123456789abcdef";
std::string out;
out.resize(sizeof(buf) * 2);
for (std::size_t i = 0; i < sizeof(buf); ++i) {
out[i * 2] = hex[buf[i] >> 4];
out[i * 2 + 1] = hex[buf[i] & 0x0f];
}
return out;
}
std::int64_t now_unix() {
return static_cast<std::int64_t>(std::time(nullptr));
}
}
ISessionRepo::Created PgSessionRepo::create(const std::string& user_id) {
const std::string token = random_token_hex();
const std::int64_t exp = now_unix() + ttl_;
auto lease = pool_.acquire();
pqxx::work tx(*lease);
tx.exec(
"INSERT INTO sessions (token, user_id, expires_at) "
"VALUES ($1, $2, to_timestamp($3::bigint))",
pqxx::params{token, user_id, exp});
tx.commit();
return Created{token, exp};
}
std::optional<std::string> PgSessionRepo::lookup(const std::string& token) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT user_id FROM sessions "
"WHERE token = $1 AND expires_at > now()",
pqxx::params{token});
tx.commit();
if (r.empty()) return std::nullopt;
return r[0]["user_id"].as<std::string>();
}
bool PgSessionRepo::revoke(const std::string& token) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"DELETE FROM sessions WHERE token = $1",
pqxx::params{token});
tx.commit();
return r.affected_rows() > 0;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "db.hpp"
#include "session_repo_base.hpp"
class PgSessionRepo : public ISessionRepo {
public:
PgSessionRepo(PgPool& pool, int ttl_seconds)
: pool_(pool), ttl_(ttl_seconds) {}
Created create(const std::string& user_id) override;
std::optional<std::string> lookup(const std::string& token) override;
bool revoke(const std::string& token) override;
private:
PgPool& pool_;
int ttl_;
};
+216
View File
@@ -0,0 +1,216 @@
#include "redis_pool.hpp"
#include "errors.hpp"
#include <chrono>
#include <cstdlib>
#include <stdexcept>
#include <string>
namespace {
constexpr timeval kConnectTimeout{2, 0};
constexpr timeval kCommandTimeout{2, 0};
constexpr auto kAcquireTimeout = std::chrono::seconds(3);
struct RedisUrl {
std::string host = "127.0.0.1";
int port = 6379;
std::string password;
int db = 0;
};
RedisUrl parse_redis_url(const std::string& url) {
RedisUrl out;
const std::string prefix = "redis://";
if (url.compare(0, prefix.size(), prefix) != 0) {
throw std::runtime_error("redis url must start with redis://");
}
std::string rest = url.substr(prefix.size());
const auto slash = rest.find('/');
if (slash != std::string::npos) {
const std::string db_str = rest.substr(slash + 1);
rest.resize(slash);
if (!db_str.empty()) {
out.db = std::atoi(db_str.c_str());
}
}
const auto at = rest.find('@');
std::string hostport = rest;
if (at != std::string::npos) {
const std::string creds = rest.substr(0, at);
hostport = rest.substr(at + 1);
const auto colon = creds.find(':');
if (colon != std::string::npos) {
out.password = creds.substr(colon + 1);
} else {
out.password = creds;
}
}
const auto colon = hostport.find(':');
if (colon == std::string::npos) {
out.host = hostport;
} else {
out.host = hostport.substr(0, colon);
out.port = std::atoi(hostport.substr(colon + 1).c_str());
}
return out;
}
redisContext* make_connection(const RedisUrl& u) {
redisContext* c = redisConnectWithTimeout(u.host.c_str(), u.port, kConnectTimeout);
if (c == nullptr) {
throw std::runtime_error("redisConnect: allocation failed");
}
if (c->err) {
const std::string err = c->errstr;
redisFree(c);
throw DependencyUnavailable("redisConnect failed: " + err);
}
if (redisSetTimeout(c, kCommandTimeout) != REDIS_OK) {
redisFree(c);
throw DependencyUnavailable("redisSetTimeout failed");
}
if (!u.password.empty()) {
redisReply* r = static_cast<redisReply*>(
redisCommand(c, "AUTH %s", u.password.c_str()));
if (r == nullptr) {
redisFree(c);
throw std::runtime_error("redis AUTH: no reply");
}
const bool ok = (r->type == REDIS_REPLY_STATUS);
freeReplyObject(r);
if (!ok) {
redisFree(c);
throw std::runtime_error("redis AUTH failed");
}
}
if (u.db != 0) {
redisReply* r = static_cast<redisReply*>(
redisCommand(c, "SELECT %d", u.db));
if (r == nullptr) {
redisFree(c);
throw std::runtime_error("redis SELECT: no reply");
}
const bool ok = (r->type == REDIS_REPLY_STATUS);
freeReplyObject(r);
if (!ok) {
redisFree(c);
throw std::runtime_error("redis SELECT failed");
}
}
return c;
}
}
RedisPool::RedisPool(std::string url, std::size_t n)
: url_(std::move(url)) {
if (n == 0) {
throw std::runtime_error("RedisPool: n must be > 0");
}
const RedisUrl parsed = parse_redis_url(url_);
all_.reserve(n);
idle_.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
ConnPtr c(make_connection(parsed));
idle_.push_back(c.get());
all_.push_back(std::move(c));
}
}
RedisPool::~RedisPool() {
{
std::lock_guard<std::mutex> lk(mu_);
shutting_down_ = true;
}
cv_.notify_all();
}
RedisPool::Lease::Lease(RedisPool& pool)
: pool_(&pool), ctx_(pool.take()) {}
RedisPool::Lease::~Lease() {
if (pool_ != nullptr && ctx_ != nullptr) {
pool_->give_back(ctx_);
}
}
RedisPool::Lease::Lease(Lease&& other) noexcept
: pool_(other.pool_), ctx_(other.ctx_) {
other.pool_ = nullptr;
other.ctx_ = nullptr;
}
RedisPool::Lease RedisPool::acquire() {
return Lease(*this);
}
redisContext* RedisPool::take() {
std::unique_lock<std::mutex> lk(mu_);
if (!cv_.wait_for(lk, kAcquireTimeout,
[&]() { return shutting_down_ || !idle_.empty(); })) {
throw DependencyUnavailable("redis pool: acquire timeout");
}
if (shutting_down_) {
throw DependencyUnavailable("redis pool is shutting down");
}
redisContext* c = idle_.back();
idle_.pop_back();
lk.unlock();
bool alive = false;
if (!c->err) {
redisReply* r = static_cast<redisReply*>(redisCommand(c, "PING"));
if (r != nullptr && r->type == REDIS_REPLY_STATUS) {
alive = true;
}
if (r != nullptr) freeReplyObject(r);
}
if (alive) {
return c;
}
ConnPtr fresh;
try {
fresh.reset(make_connection(parse_redis_url(url_)));
} catch (const std::exception& e) {
// Слот возвращается в пул, иначе после нескольких неудач пул опустеет навсегда.
give_back(c);
throw DependencyUnavailable(std::string("redis reconnect failed: ") + e.what());
}
std::lock_guard<std::mutex> lk2(mu_);
for (auto& up : all_) {
if (up.get() == c) {
up = std::move(fresh);
return up.get();
}
}
throw std::logic_error("RedisPool: connection not owned by pool");
}
void RedisPool::give_back(redisContext* c) {
{
std::lock_guard<std::mutex> lk(mu_);
idle_.push_back(c);
}
cv_.notify_one();
}
bool RedisPool::ping() {
try {
auto lease = acquire();
redisContext* c = lease.ctx();
redisReply* r = static_cast<redisReply*>(redisCommand(c, "PING"));
if (r == nullptr) return false;
const bool ok = (r->type == REDIS_REPLY_STATUS);
freeReplyObject(r);
return ok;
} catch (...) {
return false;
}
}
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include <hiredis/hiredis.h>
#include <condition_variable>
#include <cstddef>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
class RedisPool {
public:
RedisPool(std::string url, std::size_t n);
~RedisPool();
RedisPool(const RedisPool&) = delete;
RedisPool& operator=(const RedisPool&) = delete;
class Lease {
public:
explicit Lease(RedisPool& pool);
~Lease();
Lease(Lease&& other) noexcept;
Lease& operator=(Lease&&) = delete;
Lease(const Lease&) = delete;
Lease& operator=(const Lease&) = delete;
redisContext* ctx() const { return ctx_; }
private:
RedisPool* pool_;
redisContext* ctx_;
};
Lease acquire();
bool ping();
private:
friend class Lease;
struct RedisDeleter {
void operator()(redisContext* c) const noexcept {
if (c != nullptr) ::redisFree(c);
}
};
using ConnPtr = std::unique_ptr<redisContext, RedisDeleter>;
redisContext* take();
void give_back(redisContext* c);
std::string url_;
std::vector<ConnPtr> all_;
std::vector<redisContext*> idle_;
std::mutex mu_;
std::condition_variable cv_;
bool shutting_down_ = false;
};
+87
View File
@@ -0,0 +1,87 @@
#include "session_repo.hpp"
#include "errors.hpp"
#include <sodium.h>
#include <ctime>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
std::string random_token_hex() {
unsigned char buf[32];
randombytes_buf(buf, sizeof(buf));
static const char hex[] = "0123456789abcdef";
std::string out;
out.resize(sizeof(buf) * 2);
for (std::size_t i = 0; i < sizeof(buf); ++i) {
out[i * 2] = hex[buf[i] >> 4];
out[i * 2 + 1] = hex[buf[i] & 0x0f];
}
return out;
}
std::int64_t now_unix() {
return static_cast<std::int64_t>(std::time(nullptr));
}
redisReply* check_reply(redisContext* c, redisReply* r) {
if (r == nullptr) {
const std::string err = c->err ? c->errstr : "no reply";
throw DependencyUnavailable("redis command failed: " + err);
}
return r;
}
}
ISessionRepo::Created SessionRepo::create(const std::string& user_id) {
const std::string token = random_token_hex();
const std::int64_t exp = now_unix() + ttl_;
auto lease = pool_.acquire();
redisContext* c = lease.ctx();
redisReply* r = static_cast<redisReply*>(
redisCommand(c, "SET session:%s %s EX %d",
token.c_str(), user_id.c_str(), ttl_));
check_reply(c, r);
const bool ok = (r->type == REDIS_REPLY_STATUS);
freeReplyObject(r);
if (!ok) {
throw std::runtime_error("redis SET returned non-status");
}
return Created{token, exp};
}
std::optional<std::string> SessionRepo::lookup(const std::string& token) {
auto lease = pool_.acquire();
redisContext* c = lease.ctx();
redisReply* r = static_cast<redisReply*>(
redisCommand(c, "GET session:%s", token.c_str()));
check_reply(c, r);
std::optional<std::string> out;
if (r->type == REDIS_REPLY_STRING) {
out = std::string(r->str, r->len);
}
freeReplyObject(r);
return out;
}
bool SessionRepo::revoke(const std::string& token) {
auto lease = pool_.acquire();
redisContext* c = lease.ctx();
redisReply* r = static_cast<redisReply*>(
redisCommand(c, "DEL session:%s", token.c_str()));
check_reply(c, r);
const bool existed = (r->type == REDIS_REPLY_INTEGER && r->integer == 1);
freeReplyObject(r);
return existed;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "redis_pool.hpp"
#include "session_repo_base.hpp"
class SessionRepo : public ISessionRepo {
public:
SessionRepo(RedisPool& pool, int ttl_seconds)
: pool_(pool), ttl_(ttl_seconds) {}
Created create(const std::string& user_id) override;
std::optional<std::string> lookup(const std::string& token) override;
bool revoke(const std::string& token) override;
private:
RedisPool& pool_;
int ttl_;
};
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <cstdint>
#include <optional>
#include <string>
class ISessionRepo {
public:
virtual ~ISessionRepo() = default;
struct Created {
std::string token;
std::int64_t expires_at; // unix-время в секундах UTC
};
virtual Created create(const std::string& user_id) = 0;
virtual std::optional<std::string> lookup(const std::string& token) = 0;
virtual bool revoke(const std::string& token) = 0;
};
+100
View File
@@ -0,0 +1,100 @@
#include "user_repo.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <random>
#include <sstream>
#include <string>
namespace {
std::string make_uuid() {
static std::mt19937_64 rng{std::random_device{}()};
std::uniform_int_distribution<uint32_t> d16(0, 0xffff);
std::uniform_int_distribution<uint32_t> d32(0, 0xffffffffu);
std::ostringstream out;
out << std::hex << std::setfill('0');
out << std::setw(8) << d32(rng);
out << '-' << std::setw(4) << d16(rng);
out << '-' << std::setw(4) << ((d16(rng) & 0x0fff) | 0x4000);
out << '-' << std::setw(4) << ((d16(rng) & 0x3fff) | 0x8000);
out << '-' << std::setw(4) << d16(rng) << std::setw(8) << d32(rng);
return out.str();
}
std::string epoch_to_rfc3339(long long epoch) {
const std::time_t t = static_cast<std::time_t>(epoch);
std::tm tm{};
gmtime_r(&t, &tm);
std::ostringstream out;
out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
return out.str();
}
std::string now_epoch_str() {
const auto now = std::chrono::system_clock::now();
const auto secs = std::chrono::duration_cast<std::chrono::seconds>(
now.time_since_epoch()).count();
return std::to_string(secs);
}
User row_to_user(const pqxx::row& r) {
User u;
u.id = r["id"].as<std::string>();
u.username = r["username"].as<std::string>();
u.display_name = r["display_name"].as<std::string>();
u.password_hash = r["password_hash"].as<std::string>();
u.created_at = epoch_to_rfc3339(r["created_at_epoch"].as<long long>());
return u;
}
constexpr const char* kUserColumns =
"id, username, display_name, password_hash, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch";
}
std::optional<User> UserRepo::create(const std::string& username,
const std::string& display_name,
const std::string& password_hash) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
try {
const std::string id = make_uuid();
auto r = tx.exec(
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
"VALUES ($1, $2, $3, $4, to_timestamp($5::bigint)) "
"RETURNING " + std::string(kUserColumns),
pqxx::params{id, username, display_name, password_hash, now_epoch_str()});
tx.commit();
return row_to_user(r[0]);
} catch (const pqxx::unique_violation&) {
tx.abort();
return std::nullopt;
}
}
std::optional<User> UserRepo::find_by_id(const std::string& id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT " + std::string(kUserColumns) + " FROM users WHERE id = $1",
pqxx::params{id});
tx.commit();
if (r.empty()) return std::nullopt;
return row_to_user(r[0]);
}
std::optional<User> UserRepo::find_by_username(const std::string& username) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT " + std::string(kUserColumns) + " FROM users WHERE username = $1",
pqxx::params{username});
tx.commit();
if (r.empty()) return std::nullopt;
return row_to_user(r[0]);
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
class UserRepo {
public:
explicit UserRepo(PgPool& pool) : pool_(pool) {}
std::optional<User> create(const std::string& username,
const std::string& display_name,
const std::string& password_hash);
std::optional<User> find_by_id(const std::string& id);
std::optional<User> find_by_username(const std::string& username);
private:
PgPool& pool_;
};