This commit is contained in:
2026-10-30 21:09:56 +03:00
parent ec540a1a72
commit 3223dd469a
87 changed files with 15475 additions and 33 deletions
+125
View File
@@ -0,0 +1,125 @@
#include "attachment_repo.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
namespace {
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);
}
Attachment row_to_attachment(const pqxx::row& r) {
Attachment a;
a.id = r["id"].as<std::string>();
a.chat_id = r["chat_id"].as<std::string>();
a.owner_id = r["owner_id"].as<std::string>();
a.filename = r["filename"].as<std::string>();
a.content_type = r["content_type"].as<std::string>();
a.size_bytes = r["size_bytes"].as<int>();
a.sha256 = r["sha256"].as<std::string>();
a.status = r["status"].as<std::string>();
a.s3_key = r["s3_key"].as<std::string>();
if (r["error_code"].is_null()) {
a.error_code = std::nullopt;
} else {
a.error_code = r["error_code"].as<std::string>();
}
a.created_at = epoch_to_rfc3339(r["created_at_epoch"].as<long long>());
a.updated_at = epoch_to_rfc3339(r["updated_at_epoch"].as<long long>());
a.variants.clear();
return a;
}
constexpr const char* kAttachmentColumns =
"id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"status, s3_key, error_code, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch, "
"EXTRACT(EPOCH FROM updated_at)::bigint AS updated_at_epoch";
} // namespace
Attachment AttachmentRepo::insert(const Attachment& in) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string ts = now_epoch_str();
pqxx::result r;
if (in.error_code) {
r = tx.exec(
"INSERT INTO attachments ("
" id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
" status, s3_key, error_code, created_at, updated_at"
") VALUES ("
" $1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, $10, "
" to_timestamp($11::bigint), to_timestamp($12::bigint)"
") RETURNING " +
std::string(kAttachmentColumns),
pqxx::params{in.id, in.chat_id, in.owner_id, in.filename,
in.content_type, in.size_bytes, in.sha256, in.status,
in.s3_key, *in.error_code, ts, ts});
} else {
r = tx.exec(
"INSERT INTO attachments ("
" id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
" status, s3_key, error_code, created_at, updated_at"
") VALUES ("
" $1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, NULL, "
" to_timestamp($10::bigint), to_timestamp($11::bigint)"
") RETURNING " +
std::string(kAttachmentColumns),
pqxx::params{in.id, in.chat_id, in.owner_id, in.filename,
in.content_type, in.size_bytes, in.sha256, in.status,
in.s3_key, ts, ts});
}
tx.commit();
return row_to_attachment(r[0]);
}
std::optional<Attachment> AttachmentRepo::find_by_id(const std::string& id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT " + std::string(kAttachmentColumns) +
" FROM attachments WHERE id = $1::uuid",
pqxx::params{id});
if (r.empty()) {
return std::nullopt;
}
return row_to_attachment(r[0]);
}
bool AttachmentRepo::all_belong_to_chat(const std::string& chat_id,
const std::vector<std::string>& ids) {
if (ids.empty()) {
return true;
}
auto lease = pool_.acquire();
pqxx::work tx(*lease);
for (const auto& id : ids) {
auto r = tx.exec(
"SELECT 1 FROM attachments "
"WHERE id = $1::uuid AND chat_id = $2::uuid AND status = 'ready'",
pqxx::params{id, chat_id});
if (r.empty()) {
return false;
}
}
return true;
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
#include <vector>
class AttachmentRepo {
public:
explicit AttachmentRepo(PgPool& pool) : pool_(pool) {}
Attachment insert(const Attachment& a);
std::optional<Attachment> find_by_id(const std::string& id);
// All IDs must exist, belong to chat_id, and have status=ready.
// Returns false if any id is missing/foreign/failed.
bool all_belong_to_chat(const std::string& chat_id,
const std::vector<std::string>& ids);
private:
PgPool& pool_;
};
+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);
+186
View File
@@ -0,0 +1,186 @@
#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);
if (cur) {
auto owner_check = tx.exec(
"SELECT 1 FROM chats WHERE id = $1 AND id IN "
"(SELECT chat_id FROM chat_members WHERE user_id = $2)",
pqxx::params{cur->id, user_id});
if (owner_check.empty()) {
tx.commit();
return std::nullopt;
}
}
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;
}
+360
View File
@@ -0,0 +1,360 @@
#include "db.hpp"
#include "errors.hpp"
#include <chrono>
#include <fstream>
#include <future>
#include <thread>
#include <sys/socket.h>
#include <sys/time.h>
#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 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<void> 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<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);
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<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;
}
}
+62
View File
@@ -0,0 +1,62 @@
#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);
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;
};
+167
View File
@@ -0,0 +1,167 @@
#include "direct_upload_repo.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
namespace {
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);
}
DirectUpload row_to(const pqxx::row& r) {
DirectUpload d;
d.id = r["id"].as<std::string>();
d.chat_id = r["chat_id"].as<std::string>();
d.owner_id = r["owner_id"].as<std::string>();
d.filename = r["filename"].as<std::string>();
d.content_type = r["content_type"].as<std::string>();
d.expected_size = r["expected_size"].as<int>();
d.expected_sha256 = r["expected_sha256"].as<std::string>();
d.s3_key = r["s3_key"].as<std::string>();
d.status = r["status"].as<std::string>();
if (r["attachment_id"].is_null()) {
d.attachment_id = std::nullopt;
} else {
d.attachment_id = r["attachment_id"].as<std::string>();
}
d.expires_at = epoch_to_rfc3339(r["expires_at_epoch"].as<long long>());
d.created_at = epoch_to_rfc3339(r["created_at_epoch"].as<long long>());
d.updated_at = epoch_to_rfc3339(r["updated_at_epoch"].as<long long>());
return d;
}
constexpr const char* kCols =
"id, chat_id, owner_id, filename, content_type, expected_size, "
"expected_sha256, s3_key, status, attachment_id, "
"EXTRACT(EPOCH FROM expires_at)::bigint AS expires_at_epoch, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch, "
"EXTRACT(EPOCH FROM updated_at)::bigint AS updated_at_epoch";
} // namespace
DirectUpload DirectUploadRepo::insert(const DirectUpload& in) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string ts = now_epoch_str();
// expires_at is already an absolute epoch string from the caller.
auto r = tx.exec(
"INSERT INTO direct_uploads ("
" id, chat_id, owner_id, filename, content_type, expected_size, "
" expected_sha256, s3_key, status, attachment_id, "
" expires_at, created_at, updated_at"
") VALUES ("
" $1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, NULL, "
" to_timestamp($10::bigint), to_timestamp($11::bigint), "
" to_timestamp($12::bigint)"
") RETURNING " +
std::string(kCols),
pqxx::params{in.id, in.chat_id, in.owner_id, in.filename,
in.content_type, in.expected_size, in.expected_sha256,
in.s3_key, in.status, in.expires_at_epoch, ts, ts});
tx.commit();
return row_to(r[0]);
}
std::optional<DirectUpload> DirectUploadRepo::find_by_id(
const std::string& id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT " + std::string(kCols) +
" FROM direct_uploads WHERE id = $1::uuid",
pqxx::params{id});
if (r.empty()) {
return std::nullopt;
}
return row_to(r[0]);
}
std::optional<DirectUpload> DirectUploadRepo::mark_completed(
const std::string& id, const std::string& attachment_id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string ts = now_epoch_str();
auto r = tx.exec(
"UPDATE direct_uploads SET status = 'completed', "
" attachment_id = $2::uuid, "
" updated_at = to_timestamp($3::bigint) "
"WHERE id = $1::uuid AND status = 'pending' "
"RETURNING " +
std::string(kCols),
pqxx::params{id, attachment_id, ts});
if (r.empty()) {
return std::nullopt;
}
tx.commit();
return row_to(r[0]);
}
std::optional<DirectUpload> DirectUploadRepo::mark_aborted(
const std::string& id) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string ts = now_epoch_str();
auto r = tx.exec(
"UPDATE direct_uploads SET status = 'aborted', "
" updated_at = to_timestamp($2::bigint) "
"WHERE id = $1::uuid AND status = 'pending' "
"RETURNING " +
std::string(kCols),
pqxx::params{id, ts});
if (r.empty()) {
return std::nullopt;
}
tx.commit();
return row_to(r[0]);
}
std::vector<DirectUpload> DirectUploadRepo::expire_stale() {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
const std::string ts = now_epoch_str();
auto r = tx.exec(
"UPDATE direct_uploads SET status = 'expired', "
" updated_at = to_timestamp($1::bigint) "
"WHERE status = 'pending' AND expires_at < now() "
"RETURNING " +
std::string(kCols),
pqxx::params{ts});
tx.commit();
std::vector<DirectUpload> out;
out.reserve(r.size());
for (const auto& row : r) {
out.push_back(row_to(row));
}
return out;
}
std::vector<std::string> DirectUploadRepo::pending_s3_keys() {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto r = tx.exec(
"SELECT s3_key FROM direct_uploads WHERE status = 'pending'");
std::vector<std::string> out;
out.reserve(r.size());
for (const auto& row : r) {
out.push_back(row["s3_key"].as<std::string>());
}
return out;
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
#include <vector>
class DirectUploadRepo {
public:
explicit DirectUploadRepo(PgPool& pool) : pool_(pool) {}
DirectUpload insert(const DirectUpload& in);
std::optional<DirectUpload> find_by_id(const std::string& id);
// Mark completed and link attachment_id. Returns nullopt if not pending
// (or already finished / wrong owner handled by caller).
std::optional<DirectUpload> mark_completed(const std::string& id,
const std::string& attachment_id);
std::optional<DirectUpload> mark_aborted(const std::string& id);
// pending → expired where expires_at < now; returns expired rows (s3_key).
std::vector<DirectUpload> expire_stale();
// Active pending keys (for orphan GC exclusion).
std::vector<std::string> pending_s3_keys();
private:
PgPool& pool_;
};
+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);
+90
View File
@@ -0,0 +1,90 @@
#include "image_util.hpp"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_STDIO
#define STBI_ONLY_JPEG
#define STBI_ONLY_PNG
#include "stb_image.h"
#include <cstring>
std::optional<std::string> sniff_content_type(const std::uint8_t* data,
std::size_t len) {
if (!data || len < 3) {
return std::nullopt;
}
// JPEG: FF D8 FF
if (data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF) {
return std::string("image/jpeg");
}
// PNG: 89 50 4E 47
if (len >= 4 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E &&
data[3] == 0x47) {
return std::string("image/png");
}
return std::nullopt;
}
std::string_view image_reject_code(ImageReject r) {
switch (r) {
case ImageReject::unsupported_media_type:
return "unsupported_media_type";
case ImageReject::payload_too_large:
return "payload_too_large";
case ImageReject::invalid_image:
return "invalid_image";
}
return "invalid_image";
}
std::optional<ImageReject> validate_image(const std::uint8_t* data,
std::size_t len,
const ImageLimits& limits,
ImageInfo& out) {
if (!data || len == 0) {
return ImageReject::unsupported_media_type;
}
if (static_cast<std::int64_t>(len) > limits.max_bytes) {
return ImageReject::payload_too_large;
}
auto sniffed = sniff_content_type(data, len);
if (!sniffed) {
return ImageReject::unsupported_media_type;
}
int w = 0;
int h = 0;
int comp = 0;
if (!stbi_info_from_memory(reinterpret_cast<const stbi_uc*>(data),
static_cast<int>(len), &w, &h, &comp)) {
return ImageReject::invalid_image;
}
if (w <= 0 || h <= 0) {
return ImageReject::invalid_image;
}
const std::int64_t pixels =
static_cast<std::int64_t>(w) * static_cast<std::int64_t>(h);
if (pixels > limits.max_pixels) {
return ImageReject::payload_too_large;
}
int load_w = 0;
int load_h = 0;
int load_comp = 0;
stbi_uc* decoded = stbi_load_from_memory(
reinterpret_cast<const stbi_uc*>(data), static_cast<int>(len), &load_w,
&load_h, &load_comp, 0);
if (!decoded) {
return ImageReject::invalid_image;
}
// Integrity only — do not retain decoded raster.
stbi_image_free(decoded);
out.content_type = *sniffed;
out.width = w;
out.height = h;
out.pixel_count = pixels;
return std::nullopt;
}
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
struct ImageLimits {
std::int64_t max_bytes = 10'485'760; // 10 MiB
std::int64_t max_pixels = 40'000'000; // decoded width*height
};
enum class ImageReject {
unsupported_media_type, // → 415
payload_too_large, // → 413 (bytes or pixels)
invalid_image, // → 415 (corrupt / undecodable)
};
struct ImageInfo {
std::string content_type; // image/png | image/jpeg
int width = 0;
int height = 0;
std::int64_t pixel_count = 0;
};
// Magic sniff only (does not decode). Returns nullopt if neither PNG nor JPEG.
std::optional<std::string> sniff_content_type(const std::uint8_t* data,
std::size_t len);
// Full validation pipeline from contracts:
// sniff → stbi_info (dims) → pixel limit → stbi_load (integrity) → free.
// On success fills `out`. On failure returns ImageReject; decoded pixels are
// never retained after return.
std::optional<ImageReject> validate_image(const std::uint8_t* data,
std::size_t len,
const ImageLimits& limits,
ImageInfo& out);
// Human-readable error_code for Attachment failed path / API body.
std::string_view image_reject_code(ImageReject r);
+2312
View File
File diff suppressed because it is too large Load Diff
+374
View File
@@ -0,0 +1,374 @@
#include "message_repo.hpp"
#include "cursor.hpp"
#include <pqxx/pqxx>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <mutex>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <sodium.h>
#include <vector>
namespace {
std::string make_uuid() {
static std::mutex rng_mu;
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::lock_guard<std::mutex> lock(rng_mu);
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 sha256_hex(const std::string& s) {
unsigned char out[crypto_hash_sha256_BYTES];
crypto_hash_sha256(out, reinterpret_cast<const unsigned char*>(s.data()), s.size());
static const char hex[] = "0123456789abcdef";
std::string r;
r.resize(sizeof(out) * 2);
for (std::size_t i = 0; i < sizeof(out); ++i) {
r[i * 2] = hex[out[i] >> 4];
r[i * 2 + 1] = hex[out[i] & 0x0f];
}
return r;
}
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::string canonical_message_body(const std::string& text,
const std::vector<std::string>& attachment_ids) {
std::ostringstream out;
out << "text=" << text << "\nattachment_ids=";
for (std::size_t i = 0; i < attachment_ids.size(); ++i) {
if (i > 0) {
out << ',';
}
out << attachment_ids[i];
}
return out.str();
}
int idempotency_ttl_seconds() {
const char* env = std::getenv("IDEMPOTENCY_TTL_SECONDS");
if (env == nullptr || *env == '\0') {
return 86400;
}
try {
const int v = std::stoi(env);
if (v <= 0) {
return 86400;
}
return v;
} catch (...) {
return 86400;
}
}
bool attachments_belong_to_chat(pqxx::work& tx,
const std::string& chat_id,
const std::vector<std::string>& attachment_ids) {
if (attachment_ids.empty()) {
return true;
}
for (const auto& id : attachment_ids) {
auto r = tx.exec(
"SELECT 1 FROM attachments "
"WHERE id = $1 AND chat_id = $2 AND status = 'ready'",
pqxx::params{id, chat_id});
if (r.empty()) {
return false;
}
}
return true;
}
void link_attachments(pqxx::work& tx,
const std::string& message_id,
const std::vector<std::string>& attachment_ids) {
for (std::size_t i = 0; i < attachment_ids.size(); ++i) {
tx.exec(
"INSERT INTO message_attachments (message_id, attachment_id, position) "
"VALUES ($1, $2, $3)",
pqxx::params{message_id, attachment_ids[i], static_cast<int>(i)});
}
}
std::vector<std::string> load_attachment_ids(pqxx::work& tx,
const std::string& message_id) {
auto r = tx.exec(
"SELECT attachment_id FROM message_attachments "
"WHERE message_id = $1 ORDER BY position ASC",
pqxx::params{message_id});
std::vector<std::string> ids;
ids.reserve(r.size());
for (const auto& row : r) {
ids.push_back(row["attachment_id"].as<std::string>());
}
return ids;
}
void fill_attachment_ids(pqxx::work& tx, Message& m) {
m.attachment_ids = load_attachment_ids(tx, m.id);
}
void fill_attachment_ids(pqxx::work& tx, std::vector<Message>& items) {
for (auto& m : items) {
fill_attachment_ids(tx, m);
}
}
Message insert_message(pqxx::work& tx,
const std::string& chat_id,
const std::string& sender_id,
const std::string& text,
const std::vector<std::string>& attachment_ids) {
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});
Message m = row_to_message(r[0]);
link_attachments(tx, m.id, attachment_ids);
m.attachment_ids = attachment_ids;
return m;
}
bool insert_idempotency_key(pqxx::work& tx,
const std::string& user_id,
const std::string& chat_id,
const std::string& idem_key,
const std::string& request_hash,
const std::string& message_id) {
auto inserted = tx.exec(
"INSERT INTO idempotency_keys "
"(user_id, chat_id, key, request_hash, message_id) "
"VALUES ($1, $2, $3, $4, $5) "
"ON CONFLICT (user_id, chat_id, key) DO NOTHING "
"RETURNING message_id",
pqxx::params{user_id, chat_id, idem_key, request_hash, message_id});
return !inserted.empty();
}
Message load_message(pqxx::work& tx, const std::string& message_id) {
auto r = tx.exec(
"SELECT " + std::string(kMessageSelect) + " FROM messages WHERE id = $1",
pqxx::params{message_id});
if (r.empty()) {
throw std::runtime_error("idempotent message row is missing");
}
Message m = row_to_message(r[0]);
fill_attachment_ids(tx, m);
return m;
}
} // namespace
std::optional<Message> MessageRepo::create(const std::string& chat_id,
const std::string& sender_id,
const std::string& text,
const std::vector<std::string>& attachment_ids) {
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;
}
if (!attachments_belong_to_chat(tx, chat_id, attachment_ids)) {
tx.commit();
return std::nullopt;
}
Message created = insert_message(tx, chat_id, sender_id, text, attachment_ids);
tx.commit();
return created;
}
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)]));
}
fill_attachment_ids(tx, page.items);
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;
}
CreateResult MessageRepo::create_idempotent(
const std::string& chat_id,
const std::string& sender_id,
const std::string& text,
const std::vector<std::string>& attachment_ids,
const std::string& idem_key) {
const int ttl = idempotency_ttl_seconds();
const std::string hash = sha256_hex(canonical_message_body(text, attachment_ids));
for (int attempt = 0; attempt < 3; ++attempt) {
{
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 CreateResult{CreateResult::Status::NotFound, std::nullopt};
}
if (!attachments_belong_to_chat(tx, chat_id, attachment_ids)) {
tx.commit();
return CreateResult{CreateResult::Status::NotFound, std::nullopt};
}
const Message created =
insert_message(tx, chat_id, sender_id, text, attachment_ids);
if (insert_idempotency_key(tx, sender_id, chat_id, idem_key, hash,
created.id)) {
tx.commit();
return CreateResult{CreateResult::Status::Created, created};
}
}
auto lease = pool_.acquire();
pqxx::work tx(*lease);
auto existing = tx.exec(
"SELECT request_hash, message_id, "
"EXTRACT(EPOCH FROM (now() - created_at))::bigint AS age_seconds "
"FROM idempotency_keys "
"WHERE user_id = $1 AND chat_id = $2 AND key = $3 "
"FOR UPDATE",
pqxx::params{sender_id, chat_id, idem_key});
if (existing.empty()) {
tx.commit();
continue;
}
const std::string existing_hash = existing[0]["request_hash"].as<std::string>();
const long long age = existing[0]["age_seconds"].as<long long>();
const std::string message_id = existing[0]["message_id"].as<std::string>();
if (age < ttl) {
if (existing_hash != hash) {
tx.commit();
return CreateResult{CreateResult::Status::KeyConflict, std::nullopt};
}
const Message replayed = load_message(tx, message_id);
tx.commit();
return CreateResult{CreateResult::Status::Replayed, replayed};
}
tx.exec(
"DELETE FROM idempotency_keys "
"WHERE user_id = $1 AND chat_id = $2 AND key = $3",
pqxx::params{sender_id, chat_id, idem_key});
if (!attachments_belong_to_chat(tx, chat_id, attachment_ids)) {
tx.commit();
return CreateResult{CreateResult::Status::NotFound, std::nullopt};
}
const Message created =
insert_message(tx, chat_id, sender_id, text, attachment_ids);
if (insert_idempotency_key(tx, sender_id, chat_id, idem_key, hash,
created.id)) {
tx.commit();
return CreateResult{CreateResult::Status::Created, created};
}
}
throw std::runtime_error("idempotency retry exhausted");
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include "db.hpp"
#include "models.hpp"
#include <optional>
#include <string>
#include <vector>
struct CreateResult {
enum class Status { Created, Replayed, NotFound, KeyConflict };
Status status;
std::optional<Message> message;
};
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,
const std::vector<std::string>& attachment_ids);
std::optional<MessagePage> list_page(
const std::string& chat_id,
int limit,
const std::optional<std::string>& cursor);
CreateResult create_idempotent(const std::string& chat_id,
const std::string& sender_id,
const std::string& text,
const std::vector<std::string>& attachment_ids,
const std::string& idem_key);
private:
PgPool& pool_;
};
+81
View File
@@ -0,0 +1,81 @@
#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;
std::vector<std::string> attachment_ids;
};
struct MessagePage {
std::vector<Message> items;
std::optional<std::string> next_cursor;
};
struct ChatPage {
std::vector<Chat> items;
std::optional<std::string> next_cursor;
};
// Lab4: variants stay empty ([]); lab5 fills thumbnail/crop/optimized.
struct Variant {
std::string name;
std::string content_type;
int size_bytes = 0;
std::string sha256;
};
struct Attachment {
std::string id;
std::string chat_id;
std::string owner_id;
std::string filename;
std::string content_type;
int size_bytes = 0;
std::string sha256;
std::string status; // lab4: "ready"
std::vector<Variant> variants; // lab4: always empty
std::optional<std::string> error_code;
std::string s3_key; // internal; never exposed in API JSON
std::string created_at;
std::string updated_at;
};
// Track 1: pending presigned PUT session (not a public attachment until complete).
struct DirectUpload {
std::string id;
std::string chat_id;
std::string owner_id;
std::string filename;
std::string content_type;
int expected_size = 0;
std::string expected_sha256;
std::string s3_key; // internal
std::string status; // pending|completed|aborted|expired
std::optional<std::string> attachment_id;
std::string expires_at; // RFC3339 for JSON
long long expires_at_epoch = 0; // for INSERT
std::string created_at;
std::string updated_at;
};
+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;
};
+238
View File
@@ -0,0 +1,238 @@
#include "s3_client.hpp"
#include <miniocpp/args.h>
#include <miniocpp/client.h>
#include <miniocpp/providers.h>
#include <miniocpp/request.h>
#include <miniocpp/response.h>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
namespace {
std::string read_file_trim(const std::string& path) {
std::ifstream in(path);
if (!in) {
throw std::runtime_error("cannot open secret/file: " + path);
}
std::string s((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) {
s.pop_back();
}
return s;
}
std::string env_or(const char* key, const char* fallback = "") {
const char* v = std::getenv(key);
return (v && *v) ? std::string(v) : std::string(fallback);
}
void parse_endpoint(const std::string& endpoint, std::string& host, unsigned& port,
bool& https) {
https = true;
host = endpoint;
port = 0;
if (host.rfind("http://", 0) == 0) {
https = false;
host = host.substr(7);
} else if (host.rfind("https://", 0) == 0) {
https = true;
host = host.substr(8);
}
// strip path
const auto slash = host.find('/');
if (slash != std::string::npos) {
host = host.substr(0, slash);
}
const auto colon = host.rfind(':');
if (colon != std::string::npos) {
port = static_cast<unsigned>(std::stoul(host.substr(colon + 1)));
host = host.substr(0, colon);
}
if (port == 0) {
port = https ? 443u : 80u;
}
}
} // namespace
struct S3Client::Impl {
minio::s3::BaseUrl base_url;
minio::s3::BaseUrl presign_url;
std::unique_ptr<minio::creds::StaticProvider> provider;
std::unique_ptr<minio::s3::Client> client;
std::unique_ptr<minio::s3::Client> presign_client; // null → use client
};
S3Client::Config S3Client::from_env() {
Config c;
// Ops endpoint (Stat/Get/Put/Delete). Presign may use S3_PRESIGN_ENDPOINT
// (read in ctor) so signed Host matches the client-reachable address.
c.endpoint = env_or("S3_ENDPOINT", "http://minio:9000");
c.region = env_or("S3_REGION", "us-east-1");
c.bucket = env_or("S3_BUCKET");
if (c.bucket.empty()) {
throw std::runtime_error("S3_BUCKET is required");
}
const std::string key_file = env_or("S3_ACCESS_KEY_ID_FILE");
const std::string secret_file = env_or("S3_SECRET_ACCESS_KEY_FILE");
if (key_file.empty() || secret_file.empty()) {
throw std::runtime_error(
"S3_ACCESS_KEY_ID_FILE and S3_SECRET_ACCESS_KEY_FILE are required");
}
c.access_key = read_file_trim(key_file);
c.secret_key = read_file_trim(secret_file);
if (c.access_key.empty() || c.secret_key.empty()) {
throw std::runtime_error("S3 credentials files are empty");
}
return c;
}
S3Client::S3Client(Config cfg) : cfg_(std::move(cfg)), impl_(std::make_unique<Impl>()) {
if (cfg_.endpoint.empty() || cfg_.bucket.empty() ||
cfg_.access_key.empty() || cfg_.secret_key.empty()) {
throw std::runtime_error("S3Client: incomplete config");
}
std::string host;
unsigned port = 0;
bool https = false;
parse_endpoint(cfg_.endpoint, host, port, https);
impl_->base_url = minio::s3::BaseUrl(host, https, cfg_.region);
impl_->base_url.port = port;
// MinIO requires path-style addressing.
impl_->base_url.virtual_style = false;
impl_->provider = std::make_unique<minio::creds::StaticProvider>(
cfg_.access_key, cfg_.secret_key);
impl_->client =
std::make_unique<minio::s3::Client>(impl_->base_url, impl_->provider.get());
// Separate BaseUrl for presigning when S3_PRESIGN_ENDPOINT differs.
const std::string presign_ep = env_or("S3_PRESIGN_ENDPOINT");
if (!presign_ep.empty() && presign_ep != cfg_.endpoint) {
std::string ph;
unsigned pp = 0;
bool phttps = false;
parse_endpoint(presign_ep, ph, pp, phttps);
impl_->presign_url = minio::s3::BaseUrl(ph, phttps, cfg_.region);
impl_->presign_url.port = pp;
impl_->presign_url.virtual_style = false;
impl_->presign_client = std::make_unique<minio::s3::Client>(
impl_->presign_url, impl_->provider.get());
}
}
S3Client::~S3Client() = default;
void S3Client::put_object(const std::string& key,
std::istream& body,
std::int64_t size_bytes,
const std::string& content_type) {
if (size_bytes < 0) {
throw std::invalid_argument("put_object: negative size");
}
// part_size=0 → library chooses multipart sizing; streams from `body`.
minio::s3::PutObjectArgs args(body, static_cast<long>(size_bytes), 0);
args.bucket = cfg_.bucket;
args.object = key;
if (!content_type.empty()) {
args.content_type = content_type;
}
minio::s3::PutObjectResponse resp = impl_->client->PutObject(args);
if (!resp) {
throw std::runtime_error("S3 PutObject failed: " + resp.Error().String());
}
}
void S3Client::get_object(const std::string& key, std::ostream& out) {
get_object(key, [&](const char* data, std::size_t n) {
out.write(data, static_cast<std::streamsize>(n));
if (!out) {
throw std::runtime_error("get_object: write failed");
}
});
}
std::int64_t S3Client::get_object(
const std::string& key,
const std::function<void(const char*, std::size_t)>& on_chunk) {
std::int64_t total = 0;
minio::s3::GetObjectArgs args;
args.bucket = cfg_.bucket;
args.object = key;
args.datafunc = [&](minio::http::DataFunctionArgs da) -> bool {
on_chunk(da.datachunk.data(), da.datachunk.size());
total += static_cast<std::int64_t>(da.datachunk.size());
return true;
};
minio::s3::GetObjectResponse resp = impl_->client->GetObject(args);
if (!resp) {
throw std::runtime_error("S3 GetObject failed: " + resp.Error().String());
}
return total;
}
void S3Client::delete_object(const std::string& key) {
minio::s3::RemoveObjectArgs args;
args.bucket = cfg_.bucket;
args.object = key;
minio::s3::RemoveObjectResponse resp = impl_->client->RemoveObject(args);
if (!resp) {
throw std::runtime_error("S3 DeleteObject failed: " + resp.Error().String());
}
}
bool S3Client::stat_object(const std::string& key, std::int64_t& size_bytes,
std::string& etag) {
minio::s3::StatObjectArgs args;
args.bucket = cfg_.bucket;
args.object = key;
minio::s3::StatObjectResponse resp = impl_->client->StatObject(args);
if (!resp) {
// NoSuchKey / Not Found → absent
const std::string err = resp.Error().String();
if (resp.code == "NoSuchKey" || resp.status_code == 404) {
return false;
}
throw std::runtime_error("S3 StatObject failed: " + err);
}
size_bytes = static_cast<std::int64_t>(resp.size);
etag = resp.etag;
return true;
}
std::string S3Client::presign_put(const std::string& key,
unsigned expiry_seconds,
const std::string& content_type) {
if (expiry_seconds < 1 || expiry_seconds > 7 * 24 * 3600u) {
throw std::invalid_argument("presign_put: bad expiry");
}
minio::s3::Client* c =
impl_->presign_client ? impl_->presign_client.get() : impl_->client.get();
// Note: minio-cpp query-presign signs method/host/path/query only — it does
// not bind Content-Type into the signature. Clients should still send
// Content-Type so the object metadata is correct; complete() re-validates
// magic/sha256 against the session.
(void)content_type;
minio::s3::GetPresignedObjectUrlArgs args;
args.bucket = cfg_.bucket;
args.object = key;
args.method = minio::http::Method::kPut;
args.expiry_seconds = expiry_seconds;
minio::s3::GetPresignedObjectUrlResponse resp = c->GetPresignedObjectUrl(args);
if (!resp) {
throw std::runtime_error("S3 PresignPut failed: " + resp.Error().String());
}
return resp.url;
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <cstdint>
#include <functional>
#include <istream>
#include <memory>
#include <ostream>
#include <string>
// Thin wrapper over AWS SDK for C++ (S3 only). Credentials and SigV4 come from
// the SDK — no hand-rolled signing.
class S3Client {
public:
struct Config {
std::string endpoint; // e.g. http://minio:9000
std::string region; // e.g. us-east-1
std::string bucket;
std::string access_key;
std::string secret_key;
};
explicit S3Client(Config cfg);
~S3Client();
S3Client(const S3Client&) = delete;
S3Client& operator=(const S3Client&) = delete;
static Config from_env();
const std::string& bucket() const { return cfg_.bucket; }
// Stream upload. `body` must yield exactly `size_bytes` bytes.
void put_object(const std::string& key,
std::istream& body,
std::int64_t size_bytes,
const std::string& content_type);
// Stream download into `out` (chunked reads from SDK body stream).
void get_object(const std::string& key, std::ostream& out);
// Stream download with a consumer callback (chunk, size). Returns total bytes.
std::int64_t get_object(const std::string& key,
const std::function<void(const char*, std::size_t)>& on_chunk);
void delete_object(const std::string& key);
// HeadObject-style metadata. Returns false if the object does not exist.
bool stat_object(const std::string& key, std::int64_t& size_bytes,
std::string& etag);
// Presigned PUT URL via minio-cpp (SigV4). Optional required Content-Type
// is bound into the signature when non-empty.
// expiry_seconds: typically 60–600 for Track 1.
std::string presign_put(const std::string& key,
unsigned expiry_seconds,
const std::string& content_type);
private:
struct Impl;
Config cfg_;
std::unique_ptr<Impl> impl_;
};
+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_;
};