Files
mtusi2026lab5/src/direct_upload_repo.cpp
T
2026-11-16 09:28:38 +03:00

293 lines
10 KiB
C++

#include "direct_upload_repo.hpp"
#include "outbox.hpp"
#include <pqxx/pqxx>
#include <nlohmann/json.hpp>
#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.staging_key = r["staging_key"].as<std::string>();
d.status = r["status"].as<std::string>();
d.overdue = r["overdue"].as<bool>();
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, staging_key, status, attachment_id, "
"(status = 'pending' AND expires_at < now()) AS overdue, "
"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";
constexpr const char* kAttachmentColumns =
"id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"status, s3_key, error_code, variants, "
"EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch, "
"EXTRACT(EPOCH FROM updated_at)::bigint AS updated_at_epoch";
Attachment attachment_from_row(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>());
for (const auto& v : nlohmann::json::parse(r["variants"].as<std::string>())) {
a.variants.push_back(Variant{v.at("name").get<std::string>(),
v.at("content_type").get<std::string>(), v.at("size_bytes").get<int>(),
v.at("sha256").get<std::string>(), v.at("width").get<int>(),
v.at("height").get<int>(), v.value("storage_key", "")});
}
return a;
}
} // 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, staging_key, status, attachment_id, "
" expires_at, created_at, updated_at"
") VALUES ("
" $1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, $10, NULL, "
" to_timestamp($11::bigint), to_timestamp($12::bigint), "
" to_timestamp($13::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.staging_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 staging_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["staging_key"].as<std::string>());
}
return out;
}
void DirectUploadRepo::with_lock(const std::function<void(UploadLock&)>& fn) {
auto lease = pool_.acquire();
pqxx::work tx(*lease);
UploadLock lock(tx);
fn(lock);
}
std::optional<DirectUpload> UploadLock::lock(const std::string& id) {
auto r = tx_.exec(
"SELECT " + std::string(kCols) +
" FROM direct_uploads WHERE id = $1::uuid FOR UPDATE",
pqxx::params{id});
if (r.empty()) {
return std::nullopt;
}
return row_to(r[0]);
}
std::optional<Attachment> UploadLock::find_attachment(const std::string& id) {
auto r = tx_.exec(
"SELECT " + std::string(kAttachmentColumns) +
" FROM attachments WHERE id = $1::uuid",
pqxx::params{id});
if (r.empty()) {
return std::nullopt;
}
return attachment_from_row(r[0]);
}
std::optional<Attachment> UploadLock::insert_queued(const Attachment& in,
bool& inserted) {
inserted = false;
const std::string ts = now_epoch_str();
auto r = tx_.exec(
"INSERT INTO attachments ("
" id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
" status, s3_key, staging_key, error_code, created_at, updated_at"
") VALUES ("
" $1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7, $8, $9, $9, NULL, "
" to_timestamp($10::bigint), to_timestamp($11::bigint)"
") ON CONFLICT (id) DO NOTHING 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});
if (r.empty()) {
return std::nullopt;
}
tx_.exec("INSERT INTO jobs(id, attachment_id, source_key) VALUES($1::uuid, $1::uuid, $2)",
pqxx::params{in.id, in.s3_key});
enqueue_attachment_job(tx_, in.id);
inserted = true;
return attachment_from_row(r[0]);
}
void UploadLock::mark_completed(const std::string& id,
const std::string& attachment_id) {
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'",
pqxx::params{id, attachment_id, ts});
if (r.affected_rows() != 1) {
throw std::runtime_error("direct upload complete lost the pending row");
}
}
void UploadLock::mark_expired(const std::string& id) {
const std::string ts = now_epoch_str();
tx_.exec(
"UPDATE direct_uploads SET status = 'expired', "
" updated_at = to_timestamp($2::bigint) "
"WHERE id = $1::uuid AND status = 'pending'",
pqxx::params{id, ts});
}
void UploadLock::commit() {
if (committed_) {
return;
}
tx_.commit();
committed_ = true;
}