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

64 lines
2.0 KiB
C++

#pragma once
#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) {}
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.
std::vector<DirectUpload> expire_stale();
// 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);
// Inserts attachment and its job in this transaction; job_id equals attachment id.
// ON CONFLICT (id) DO NOTHING. inserted=false and nullopt → row already exists.
std::optional<Attachment> insert_queued(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;
};