Files
Library/src/ShortUrlStorage/StorageRepository.cpp
T

471 lines
15 KiB
C++

#include <Void/ShortUrlStorage/StorageRepository.hpp>
#include <Void/Security/Security.hpp>
#include <charconv>
#include <cstring>
#include <format>
#include <string>
#include <string_view>
#include <vector>
namespace Void::ShortUrl::V2
{
namespace
{
constexpr std::string_view kLinkPrefix = "shorturl:v1:link:";
constexpr std::string_view kIdemPrefix = "shorturl:v1:idem:";
constexpr std::string_view kMetaCountsKey = "shorturl:v1:meta:counts";
void append_u32(std::string& out, std::uint32_t v)
{
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<char>(v & 0xFFU));
}
void append_u64(std::string& out, std::uint64_t v)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<char>((v >> shift) & 0xFFU));
}
}
void append_str(std::string& out, std::string_view s)
{
append_u32(out, static_cast<std::uint32_t>(s.size()));
out.append(s);
}
[[nodiscard]] bool read_u32(std::string_view& in,
std::uint32_t& out) noexcept
{
if (in.size() < 4U) return false;
out = (static_cast<std::uint32_t>(static_cast<unsigned char>(in[0]))
<< 24U) |
(static_cast<std::uint32_t>(static_cast<unsigned char>(in[1]))
<< 16U) |
(static_cast<std::uint32_t>(static_cast<unsigned char>(in[2]))
<< 8U) |
static_cast<std::uint32_t>(static_cast<unsigned char>(in[3]));
in.remove_prefix(4U);
return true;
}
[[nodiscard]] bool read_u64(std::string_view& in,
std::uint64_t& out) noexcept
{
if (in.size() < 8U) return false;
std::uint64_t v = 0;
for (std::size_t i = 0; i < 8U; ++i) {
v = (v << 8U) |
static_cast<std::uint64_t>(
static_cast<unsigned char>(in[i]));
}
in.remove_prefix(8U);
out = v;
return true;
}
[[nodiscard]] bool read_str(std::string_view& in, std::string& out)
{
std::uint32_t len = 0;
if (!read_u32(in, len) || len > in.size()) {
return false;
}
out.assign(in.data(), len);
in.remove_prefix(len);
return true;
}
[[nodiscard]] std::string encode_link(const LinkRecord& r)
{
std::string out;
append_u32(out, r.schema_version);
out.push_back(static_cast<char>(static_cast<std::uint8_t>(r.state)));
append_u64(out, static_cast<std::uint64_t>(r.created_at_unix_seconds));
append_u64(out, static_cast<std::uint64_t>(r.expires_at_unix_seconds));
append_str(out, r.key);
append_str(out, r.target_url);
append_str(out, r.operation_id);
return out;
}
[[nodiscard]] std::optional<LinkRecord>
decode_link(std::string_view raw)
{
std::uint32_t ver = 0;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion) {
return std::nullopt;
}
if (raw.empty()) return std::nullopt;
const auto st = static_cast<std::uint8_t>(raw.front());
raw.remove_prefix(1U);
if (st != static_cast<std::uint8_t>(LinkState::Active) &&
st != static_cast<std::uint8_t>(LinkState::Revoked)) {
return std::nullopt;
}
std::uint64_t created = 0;
std::uint64_t expires = 0;
if (!read_u64(raw, created) || !read_u64(raw, expires)) {
return std::nullopt;
}
LinkRecord rec;
rec.schema_version = ver;
rec.state = static_cast<LinkState>(st);
rec.created_at_unix_seconds = static_cast<std::int64_t>(created);
rec.expires_at_unix_seconds = static_cast<std::int64_t>(expires);
if (!read_str(raw, rec.key) || !read_str(raw, rec.target_url) ||
!read_str(raw, rec.operation_id) || !raw.empty()) {
return std::nullopt;
}
return rec;
}
[[nodiscard]] std::string encode_idem(const IdempotencyRecord& r)
{
std::string out;
append_u32(out, kRecordSchemaVersion);
append_u64(out, static_cast<std::uint64_t>(r.created_at_unix_seconds));
append_u64(out,
static_cast<std::uint64_t>(r.retain_until_unix_seconds));
append_str(out, r.operation_id);
append_str(out, r.key);
append_str(out, r.target_url);
return out;
}
[[nodiscard]] std::optional<IdempotencyRecord>
decode_idem(std::string_view raw)
{
std::uint32_t ver = 0;
std::uint64_t created = 0;
std::uint64_t retain = 0;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion ||
!read_u64(raw, created) || !read_u64(raw, retain)) {
return std::nullopt;
}
IdempotencyRecord rec;
rec.created_at_unix_seconds = static_cast<std::int64_t>(created);
rec.retain_until_unix_seconds = static_cast<std::int64_t>(retain);
if (!read_str(raw, rec.operation_id) || !read_str(raw, rec.key) ||
!read_str(raw, rec.target_url) || !raw.empty()) {
return std::nullopt;
}
return rec;
}
struct MetaCounts {
std::uint64_t entries{0};
std::uint64_t retained_identities{0};
std::uint64_t approx_bytes{0};
};
[[nodiscard]] std::string encode_counts(const MetaCounts& c)
{
std::string out;
append_u32(out, kRecordSchemaVersion);
append_u64(out, c.entries);
append_u64(out, c.retained_identities);
append_u64(out, c.approx_bytes);
return out;
}
[[nodiscard]] std::optional<MetaCounts>
decode_counts(std::string_view raw)
{
std::uint32_t ver = 0;
MetaCounts c;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion ||
!read_u64(raw, c.entries) ||
!read_u64(raw, c.retained_identities) ||
!read_u64(raw, c.approx_bytes) || !raw.empty()) {
return std::nullopt;
}
return c;
}
} // namespace
Void::Result::Result<void>
SecurityRandomBytesPort::fill(std::span<std::byte> out)
{
std::size_t off = 0;
while (off < out.size()) {
auto key = Void::Security::random_secret_key();
if (!key.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Internal,
std::format("ShortUrlStorage: CSPRNG failed: {}",
key.error().message()))};
}
const std::size_t take = std::min(key->size(), out.size() - off);
std::memcpy(out.data() + off, key->data(), take);
Void::Security::wipe_bytes(*key);
off += take;
}
return {};
}
StorageLinkRepository::StorageLinkRepository(
std::shared_ptr<Void::Storage::Engine> engine,
std::uint64_t disk_quota_bytes)
: m_engine(std::move(engine)), m_disk_quota_bytes(disk_quota_bytes)
{
}
Void::Result::Result<InsertOutcome>
StorageLinkRepository::insert_conditional(
const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds, std::size_t max_entries,
std::size_t max_retained_identities)
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
std::lock_guard lock{m_write_mutex};
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
// 1. Check existing idempotency record first.
std::string idem_storage_key;
if (idem.has_value() && !idem->operation_id.empty()) {
idem_storage_key = std::string{kIdemPrefix} + idem->operation_id;
auto existing_idem = m_engine->get(*snap, idem_storage_key);
if (existing_idem.has_value()) {
auto decoded = decode_idem(existing_idem->as_string_view());
if (!decoded.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt idempotency record")};
}
if (decoded->retain_until_unix_seconds <= now_unix_seconds) {
return InsertOutcome{InsertStatus::IdentityExpired, {}};
}
const std::string link_k =
std::string{kLinkPrefix} + decoded->key;
auto existing_link = m_engine->get(*snap, link_k);
if (!existing_link.has_value()) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
auto link_dec = decode_link(existing_link->as_string_view());
if (!link_dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
return InsertOutcome{InsertStatus::IdempotentReplay, *link_dec};
}
if (existing_idem.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get idempotency failed: {}",
existing_idem.error().message()))};
}
}
// 2. Check existing link key.
const std::string link_storage_key =
std::string{kLinkPrefix} + record.key;
auto existing_link = m_engine->get(*snap, link_storage_key);
if (existing_link.has_value()) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (existing_link.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get link failed: {}",
existing_link.error().message()))};
}
// 3. Load and verify counts + disk quota.
MetaCounts counts{};
std::optional<Void::Storage::Sequence> counts_version;
auto counts_res = m_engine->get(*snap, kMetaCountsKey);
if (counts_res.has_value()) {
auto dec = decode_counts(counts_res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt metadata counts record")};
}
counts = *dec;
counts_version = counts_res->version;
} else if (counts_res.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get counts failed: {}",
counts_res.error().message()))};
}
const std::string encoded_link = encode_link(record);
std::string encoded_idem;
if (!idem_storage_key.empty()) {
if (counts.retained_identities >= max_retained_identities) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
encoded_idem = encode_idem(*idem);
}
if (counts.entries >= max_entries) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
const std::uint64_t added_bytes =
link_storage_key.size() + encoded_link.size() +
idem_storage_key.size() + encoded_idem.size();
if (m_disk_quota_bytes > 0 &&
(added_bytes > m_disk_quota_bytes ||
counts.approx_bytes > m_disk_quota_bytes - added_bytes)) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
counts.entries += 1U;
if (!idem_storage_key.empty()) {
counts.retained_identities += 1U;
}
counts.approx_bytes += added_bytes;
// 4. Atomic conditional WriteBatch.
Void::Storage::Batch batch;
batch.require_absent(link_storage_key);
batch.put(link_storage_key, encoded_link);
if (!idem_storage_key.empty()) {
batch.require_absent(idem_storage_key);
batch.put(idem_storage_key, encoded_idem);
}
if (counts_version.has_value()) {
batch.require_version(kMetaCountsKey, *counts_version);
} else {
batch.require_absent(kMetaCountsKey);
}
batch.put(kMetaCountsKey, encode_counts(counts));
auto wr = m_engine->write(std::move(batch), Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome == Void::Storage::Outcome::Unknown) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlStorage: commit outcome unknown: {}",
wr.error().cause.error.message()))};
}
if (wr.error().cause.code ==
Void::Storage::StorageErrorCode::conflict) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: conditional write failed: {}",
wr.error().cause.error.message()))};
}
return InsertOutcome{InsertStatus::Inserted, record};
}
Void::Result::Result<std::optional<LinkRecord>>
StorageLinkRepository::get(std::string_view key) const
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
const std::string storage_key =
std::string{kLinkPrefix} + std::string{key};
auto res = m_engine->get(*snap, storage_key);
if (!res.has_value()) {
if (res.error().kind() == Void::Result::ErrorKind::not_found) {
return std::optional<LinkRecord>{};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get failed: {}",
res.error().message()))};
}
auto dec = decode_link(res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
return std::optional<LinkRecord>{std::move(*dec)};
}
Void::Result::Result<void>
StorageLinkRepository::revoke(std::string_view key, std::int64_t)
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
std::lock_guard lock{m_write_mutex};
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
const std::string storage_key =
std::string{kLinkPrefix} + std::string{key};
auto res = m_engine->get(*snap, storage_key);
if (!res.has_value()) {
if (res.error().kind() == Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound,
"ShortUrlStorage: key not found for revoke")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get failed: {}",
res.error().message()))};
}
auto dec = decode_link(res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
if (dec->state == LinkState::Revoked) {
return {};
}
dec->state = LinkState::Revoked;
Void::Storage::Batch batch;
batch.require_version(storage_key, res->version);
batch.put(storage_key, encode_link(*dec));
auto wr =
m_engine->write(std::move(batch), Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome == Void::Storage::Outcome::Unknown) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
"ShortUrlStorage: revoke outcome unknown")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: revoke write failed: {}",
wr.error().cause.error.message()))};
}
return {};
}
} // namespace Void::ShortUrl::V2