fit: complete lab4, fix P1.1-P1.3, add Track 1 presigned

This commit is contained in:
2026-11-06 04:23:59 +03:00
parent 3223dd469a
commit 7741b66fd2
16 changed files with 577 additions and 219 deletions
+123 -8
View File
@@ -36,7 +36,9 @@ DirectUpload row_to(const pqxx::row& r) {
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 {
@@ -50,11 +52,40 @@ DirectUpload row_to(const pqxx::row& r) {
constexpr const char* kCols =
"id, chat_id, owner_id, filename, content_type, expected_size, "
"expected_sha256, s3_key, status, attachment_id, "
"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, "
"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>());
a.variants.clear();
return a;
}
} // namespace
DirectUpload DirectUploadRepo::insert(const DirectUpload& in) {
@@ -65,17 +96,18 @@ DirectUpload DirectUploadRepo::insert(const DirectUpload& in) {
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, "
" 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, NULL, "
" to_timestamp($10::bigint), to_timestamp($11::bigint), "
" to_timestamp($12::bigint)"
" $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.status, in.expires_at_epoch, ts, ts});
in.s3_key, in.staging_key, in.status, in.expires_at_epoch,
ts, ts});
tx.commit();
return row_to(r[0]);
}
@@ -157,11 +189,94 @@ 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'");
"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["s3_key"].as<std::string>());
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_ready(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, 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)"
") 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;
}
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;
}
+31 -2
View File
@@ -3,10 +3,13 @@
#include "db.hpp"
#include "models.hpp"
#include <functional>
#include <optional>
#include <string>
#include <vector>
class UploadLock;
class DirectUploadRepo {
public:
explicit DirectUploadRepo(PgPool& pool) : pool_(pool) {}
@@ -22,12 +25,38 @@ public:
std::optional<DirectUpload> mark_aborted(const std::string& id);
// pending → expired where expires_at < now; returns expired rows (s3_key).
// pending → expired where expires_at < now; returns expired rows.
std::vector<DirectUpload> expire_stale();
// Active pending keys (for orphan GC exclusion).
// Staging keys of still-pending sessions (orphan GC must keep these).
std::vector<std::string> pending_s3_keys();
// One PG transaction. Callback may call S3 while the row lock is held.
// Commit explicitly via UploadLock::commit(); otherwise the work rolls back.
void with_lock(const std::function<void(UploadLock&)>& fn);
private:
PgPool& pool_;
};
// Row lock for a single complete(). Not safe to use after with_lock returns.
class UploadLock {
public:
std::optional<DirectUpload> lock(const std::string& id);
std::optional<Attachment> find_attachment(const std::string& id);
// ON CONFLICT (id) DO NOTHING. inserted=false and nullopt → row already exists.
std::optional<Attachment> insert_ready(const Attachment& in, bool& inserted);
void mark_completed(const std::string& id, const std::string& attachment_id);
void mark_expired(const std::string& id);
void commit();
private:
friend class DirectUploadRepo;
explicit UploadLock(pqxx::work& tx) : tx_(tx) {}
pqxx::work& tx_;
bool committed_ = false;
};
+175 -158
View File
@@ -1686,6 +1686,7 @@ static void handle_client(int client,
send_all(client, error_response(503, "unavailable",
"service unavailable", request_id));
} else {
bool response_headers_sent = false;
try {
const auto att = attachments.find_by_id(attachment_id);
if (!att) {
@@ -1705,36 +1706,51 @@ static void handle_client(int client,
409, "conflict",
"attachment not ready", request_id));
} else {
std::string head =
"HTTP/1.1 200 OK\r\n"
"Content-Type: " + att->content_type + "\r\n"
"X-Request-Id: " + request_id + "\r\n"
"X-Instance-Id: " + g_instance_id + "\r\n"
"Content-Length: " +
std::to_string(att->size_bytes) + "\r\n"
"Connection: close\r\n"
"\r\n";
send_all(client, head);
s3->get_object(att->s3_key, [&](const char* data,
std::size_t n) {
size_t sent = 0;
while (sent < n) {
const ssize_t w = ::write(
client, data + sent, n - sent);
if (w <= 0) {
throw std::runtime_error(
"content write failed");
std::int64_t object_size = 0;
std::string etag;
if (!s3->stat_object(att->s3_key, object_size, etag)) {
send_all(client, error_response(
404, "not_found", "not found", request_id));
} else if (object_size != att->size_bytes) {
send_all(client, error_response(
500, "internal_error", "internal error",
request_id));
} else {
std::string head =
"HTTP/1.1 200 OK\r\n"
"Content-Type: " + att->content_type + "\r\n"
"X-Request-Id: " + request_id + "\r\n"
"X-Instance-Id: " + g_instance_id + "\r\n"
"Content-Length: " +
std::to_string(att->size_bytes) + "\r\n"
"Connection: close\r\n"
"\r\n";
response_headers_sent = true;
send_all(client, head);
s3->get_object(att->s3_key, [&](const char* data,
std::size_t n) {
size_t sent = 0;
while (sent < n) {
const ssize_t w = ::write(
client, data + sent, n - sent);
if (w <= 0) {
throw std::runtime_error(
"content write failed");
}
sent += static_cast<size_t>(w);
}
sent += static_cast<size_t>(w);
}
});
});
}
}
}
} catch (const std::exception& e) {
// If headers were not sent yet, return JSON error; otherwise
// the connection is already mid-body — just close.
send_all(client, failure_response(e, "download_attachment",
request_id));
if (response_headers_sent) {
std::clog << "download_attachment stream failed: "
<< e.what() << "\n";
} else {
send_all(client, failure_response(e, "download_attachment",
request_id));
}
}
}
}
@@ -1845,6 +1861,7 @@ static void handle_client(int client,
d.expected_size = static_cast<int>(*size_b);
d.expected_sha256 = *sha;
d.s3_key = "attachments/" + chat_id + "/" + d.id;
d.staging_key = "staging/" + chat_id + "/" + d.id;
d.status = "pending";
const auto now = std::chrono::system_clock::now();
const auto secs =
@@ -1854,7 +1871,7 @@ static void handle_client(int client,
d.expires_at_epoch = secs + ttl;
const DirectUpload saved = direct_uploads.insert(d);
const std::string url = s3->presign_put(
saved.s3_key, static_cast<unsigned>(ttl),
saved.staging_key, static_cast<unsigned>(ttl),
saved.content_type);
nlohmann::json out;
out["id"] = saved.id;
@@ -1890,137 +1907,137 @@ static void handle_client(int client,
"service unavailable", request_id));
} else {
try {
auto sess = direct_uploads.find_by_id(direct_upload_id);
if (!sess || sess->owner_id != user_id) {
send_all(client, error_response(404, "not_found",
"not found", request_id));
} else if (sess->status != "pending") {
send_all(client, error_response(
409, "conflict",
"upload session not pending", request_id));
} else {
// Flip overdue pending → expired, then re-read.
direct_uploads.expire_stale();
sess = direct_uploads.find_by_id(direct_upload_id);
if (!sess || sess->status != "pending") {
send_all(client, error_response(
410, "gone", "upload session expired", request_id));
} else {
std::int64_t obj_size = 0;
std::string etag;
if (!s3->stat_object(sess->s3_key, obj_size, etag)) {
send_all(client, error_response(
400, "invalid_request",
"object not uploaded", request_id));
} else if (obj_size != sess->expected_size) {
try {
s3->delete_object(sess->s3_key);
} catch (...) {
}
direct_uploads.mark_aborted(sess->id);
send_all(client, error_response(
400, "invalid_request",
"size mismatch", request_id));
} else {
std::vector<std::uint8_t> buf;
buf.reserve(static_cast<std::size_t>(obj_size));
s3->get_object(
sess->s3_key,
[&](const char* data, std::size_t n) {
buf.insert(buf.end(),
reinterpret_cast<const std::uint8_t*>(
data),
reinterpret_cast<const std::uint8_t*>(
data) +
n);
});
if (static_cast<std::int64_t>(buf.size()) !=
sess->expected_size) {
send_all(client, error_response(
400, "invalid_request",
"size mismatch", request_id));
} else {
const std::string got_sha = sha256_hex_bytes(
buf.data(), buf.size());
if (got_sha != sess->expected_sha256) {
try {
s3->delete_object(sess->s3_key);
} catch (...) {
}
direct_uploads.mark_aborted(sess->id);
send_all(client, error_response(
400, "invalid_request",
"checksum mismatch", request_id));
} else {
ImageLimits lim;
if (const char* env =
std::getenv("MAX_UPLOAD_BYTES")) {
try {
lim.max_bytes = std::stoll(env);
} catch (...) {
}
}
if (const char* env =
std::getenv("MAX_IMAGE_PIXELS")) {
try {
lim.max_pixels = std::stoll(env);
} catch (...) {
}
}
ImageInfo info;
auto rej = validate_image(
buf.data(), buf.size(), lim, info);
if (rej ||
info.content_type != sess->content_type) {
try {
s3->delete_object(sess->s3_key);
} catch (...) {
}
direct_uploads.mark_aborted(sess->id);
send_all(client, error_response(
415, "unsupported_media_type",
"unsupported media type",
request_id));
} else {
Attachment a;
a.id = sess->id; // stable id = session id
a.chat_id = sess->chat_id;
a.owner_id = sess->owner_id;
a.filename = sess->filename;
a.content_type = sess->content_type;
a.size_bytes = sess->expected_size;
a.sha256 = sess->expected_sha256;
a.status = "ready";
a.s3_key = sess->s3_key;
bool inserted = false;
try {
const Attachment saved =
attachments.insert(a);
inserted = true;
direct_uploads.mark_completed(
sess->id, saved.id);
send_all(client, http_response(
201, "Created", request_id,
attachment_json(saved)));
} catch (const std::exception& e) {
if (!inserted) {
try {
s3->delete_object(a.s3_key);
} catch (...) {
}
direct_uploads.mark_aborted(
sess->id);
}
send_all(client, failure_response(
e, "direct_upload_complete",
request_id));
}
}
}
}
std::string response;
direct_uploads.with_lock([&](UploadLock& upload) {
const auto sess = upload.lock(direct_upload_id);
if (!sess || sess->owner_id != user_id) {
response = error_response(404, "not_found", "not found",
request_id);
return;
}
if (sess->status == "completed") {
const auto saved = upload.find_attachment(
sess->attachment_id.value_or(sess->id));
if (!saved) {
throw std::runtime_error(
"completed upload has no attachment");
}
upload.commit();
response = http_response(200, "OK", request_id,
attachment_json(*saved));
return;
}
if (sess->status != "pending") {
response = error_response(
409, "conflict", "upload session not pending",
request_id);
return;
}
if (sess->overdue) {
upload.mark_expired(sess->id);
upload.commit();
response = error_response(410, "gone",
"upload session expired",
request_id);
return;
}
std::int64_t obj_size = 0;
std::string etag;
if (!s3->stat_object(sess->staging_key, obj_size, etag)) {
upload.commit();
response = error_response(409, "not_ready",
"upload object not ready",
request_id);
return;
}
if (obj_size != sess->expected_size) {
upload.commit();
response = error_response(409, "hash_mismatch",
"uploaded object mismatch",
request_id);
return;
}
std::vector<std::uint8_t> buf;
buf.reserve(static_cast<std::size_t>(obj_size));
s3->get_object(
sess->staging_key,
[&](const char* data, std::size_t n) {
buf.insert(buf.end(),
reinterpret_cast<const std::uint8_t*>(data),
reinterpret_cast<const std::uint8_t*>(data) + n);
});
if (static_cast<std::int64_t>(buf.size()) !=
sess->expected_size ||
sha256_hex_bytes(buf.data(), buf.size()) !=
sess->expected_sha256) {
upload.commit();
response = error_response(409, "hash_mismatch",
"uploaded object mismatch",
request_id);
return;
}
ImageLimits lim;
if (const char* env = std::getenv("MAX_UPLOAD_BYTES")) {
try {
lim.max_bytes = std::stoll(env);
} catch (...) {
}
}
}
if (const char* env = std::getenv("MAX_IMAGE_PIXELS")) {
try {
lim.max_pixels = std::stoll(env);
} catch (...) {
}
}
ImageInfo info;
const auto rejection =
validate_image(buf.data(), buf.size(), lim, info);
if (rejection || info.content_type != sess->content_type) {
upload.commit();
response = error_response(415, "unsupported_media_type",
"unsupported media type",
request_id);
return;
}
Attachment a;
a.id = sess->id;
a.chat_id = sess->chat_id;
a.owner_id = sess->owner_id;
a.filename = sess->filename;
a.content_type = sess->content_type;
a.size_bytes = sess->expected_size;
a.sha256 = sess->expected_sha256;
a.status = "ready";
a.s3_key = sess->s3_key;
s3->copy_object(sess->staging_key, a.s3_key);
bool inserted = false;
auto saved = upload.insert_ready(a, inserted);
if (!saved) {
saved = upload.find_attachment(a.id);
}
if (!saved) {
throw std::runtime_error(
"attachment insert conflict without existing row");
}
try {
s3->delete_object(sess->staging_key);
} catch (const std::exception& e) {
std::clog << "direct upload staging cleanup failed: "
<< e.what() << "\n";
}
upload.mark_completed(sess->id, saved->id);
upload.commit();
response = http_response(inserted ? 201 : 200,
inserted ? "Created" : "OK",
request_id,
attachment_json(*saved));
});
send_all(client, response);
} catch (const std::exception& e) {
send_all(client, failure_response(e, "direct_upload_complete",
request_id));
@@ -2050,8 +2067,8 @@ static void handle_client(int client,
try {
std::int64_t sz = 0;
std::string et;
if (s3->stat_object(sess->s3_key, sz, et)) {
s3->delete_object(sess->s3_key);
if (s3->stat_object(sess->staging_key, sz, et)) {
s3->delete_object(sess->staging_key);
}
} catch (const std::exception& de) {
std::clog << "abort DeleteObject failed: "
+3 -1
View File
@@ -71,8 +71,10 @@ struct DirectUpload {
std::string content_type;
int expected_size = 0;
std::string expected_sha256;
std::string s3_key; // internal
std::string s3_key; // final key: attachments/{chat}/{id}
std::string staging_key; // presigned PUT target: staging/{chat}/{id}
std::string status; // pending|completed|aborted|expired
bool overdue = false; // pending && expires_at < now(); not a column
std::optional<std::string> attachment_id;
std::string expires_at; // RFC3339 for JSON
long long expires_at_epoch = 0; // for INSERT
+16
View File
@@ -181,6 +181,22 @@ std::int64_t S3Client::get_object(
return total;
}
void S3Client::copy_object(const std::string& src_key,
const std::string& dst_key) {
if (src_key.empty() || dst_key.empty() || src_key == dst_key) {
throw std::invalid_argument("copy_object: bad keys");
}
minio::s3::CopyObjectArgs args;
args.bucket = cfg_.bucket;
args.object = dst_key;
args.source.bucket = cfg_.bucket;
args.source.object = src_key;
minio::s3::CopyObjectResponse resp = impl_->client->CopyObject(args);
if (!resp) {
throw std::runtime_error("S3 CopyObject failed: " + resp.Error().String());
}
}
void S3Client::delete_object(const std::string& key) {
minio::s3::RemoveObjectArgs args;
args.bucket = cfg_.bucket;
+3
View File
@@ -45,6 +45,9 @@ public:
void delete_object(const std::string& key);
// Server-side copy inside the bucket (complete: staging → final).
void copy_object(const std::string& src_key, const std::string& dst_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);