feat(shorturl): complete P2 M-SHORTURL-01..04 V2 local, storage, and remote providers with frozen V1

This commit is contained in:
faumaray committed 2026-11-27 01:27:32 +03:00
1 parent 658c21a2fa
commit 691808eab6
13 files changed
+2317 -1

No files matched your search

+895
View File
@@ -0,0 +1,895 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::ShortUrl::V2
{
inline constexpr std::uint32_t kServiceVersionV2{2};
inline constexpr std::uint32_t kRecordSchemaVersion{1};
enum class V2ErrorCode : std::int32_t {
None = 0,
InvalidRequest = 1,
InvalidUrl = 2,
InvalidKey = 3,
InvalidExpiry = 4,
Conflict = 5,
NotFound = 6,
Expired = 7,
Revoked = 8,
Unsupported = 9,
Unauthorized = 10,
RateLimited = 11,
QuotaExceeded = 12,
IdentityExpired = 13,
StorageError = 14,
UnknownOutcome = 15,
ProviderError = 16,
Timeout = 17,
Unavailable = 18,
ResponseTooLarge = 19,
Internal = 20,
};
[[nodiscard]] inline Void::Result::Error
make_shorturl_error(V2ErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case V2ErrorCode::None:
case V2ErrorCode::Internal:
case V2ErrorCode::ProviderError:
kind = ErrorKind::internal;
break;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidUrl:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::Unauthorized:
kind = ErrorKind::invalid_argument;
break;
case V2ErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case V2ErrorCode::Conflict:
case V2ErrorCode::Expired:
case V2ErrorCode::Revoked:
case V2ErrorCode::IdentityExpired:
case V2ErrorCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case V2ErrorCode::Unsupported:
kind = ErrorKind::unsupported;
break;
case V2ErrorCode::RateLimited:
case V2ErrorCode::Unavailable:
kind = ErrorKind::overloaded;
break;
case V2ErrorCode::QuotaExceeded:
case V2ErrorCode::ResponseTooLarge:
kind = ErrorKind::exhausted;
break;
case V2ErrorCode::StorageError:
kind = ErrorKind::io;
break;
case V2ErrorCode::Timeout:
kind = ErrorKind::timeout;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kShortUrlErrorDomain,
static_cast<std::int32_t>(code)}};
}
[[nodiscard]] inline V2ErrorCode
v2_error_code_from(const Void::Result::Error& err) noexcept
{
if (err.code().domain == Void::Result::kShortUrlErrorDomain) {
return static_cast<V2ErrorCode>(err.code().value);
}
switch (err.kind()) {
case Void::Result::ErrorKind::invalid_argument:
return V2ErrorCode::InvalidRequest;
case Void::Result::ErrorKind::not_found:
return V2ErrorCode::NotFound;
case Void::Result::ErrorKind::conflict:
return V2ErrorCode::Conflict;
case Void::Result::ErrorKind::timeout:
return V2ErrorCode::Timeout;
case Void::Result::ErrorKind::overloaded:
return V2ErrorCode::Unavailable;
case Void::Result::ErrorKind::unsupported:
return V2ErrorCode::Unsupported;
case Void::Result::ErrorKind::exhausted:
return V2ErrorCode::QuotaExceeded;
case Void::Result::ErrorKind::io:
return V2ErrorCode::StorageError;
default:
return V2ErrorCode::Internal;
}
}
[[nodiscard]] inline V1::ErrorCode
to_v1_error_code(V2ErrorCode code) noexcept
{
switch (code) {
case V2ErrorCode::None: return V1::ErrorCode::none;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::IdentityExpired:
return V1::ErrorCode::invalid_request;
case V2ErrorCode::InvalidUrl: return V1::ErrorCode::invalid_url;
case V2ErrorCode::Unsupported: return V1::ErrorCode::unsupported;
case V2ErrorCode::NotFound: return V1::ErrorCode::not_found;
case V2ErrorCode::Expired: return V1::ErrorCode::expired;
case V2ErrorCode::Revoked: return V1::ErrorCode::revoked;
case V2ErrorCode::Conflict: return V1::ErrorCode::conflict;
case V2ErrorCode::Unauthorized: return V1::ErrorCode::unauthorized;
case V2ErrorCode::RateLimited: return V1::ErrorCode::rate_limited;
case V2ErrorCode::Timeout: return V1::ErrorCode::timeout;
case V2ErrorCode::Unavailable:
case V2ErrorCode::QuotaExceeded:
return V1::ErrorCode::unavailable;
case V2ErrorCode::StorageError: return V1::ErrorCode::storage;
case V2ErrorCode::ResponseTooLarge:
return V1::ErrorCode::response_too_large;
case V2ErrorCode::ProviderError:
case V2ErrorCode::UnknownOutcome:
return V1::ErrorCode::provider_error;
case V2ErrorCode::Internal: return V1::ErrorCode::internal_error;
}
return V1::ErrorCode::internal_error;
}
enum class LinkState : std::uint8_t {
Active = 1,
Revoked = 2,
};
struct LinkRecord {
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t expires_at_unix_seconds{0}; // 0 = permanent
LinkState state{LinkState::Active};
std::string operation_id{};
std::uint32_t schema_version{kRecordSchemaVersion};
};
struct IdempotencyRecord {
std::string operation_id{};
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t retain_until_unix_seconds{0};
};
struct Link {
std::string key{};
std::string short_url{};
std::string target_url{};
std::int64_t expires_at_unix_seconds{0};
std::uint32_t retry_after_seconds{0};
};
struct CreateLink {
std::string target_url{};
std::string custom_key{};
std::int64_t expires_at_unix_seconds{0};
};
struct ShortenOptions {
std::string operation_id{};
std::chrono::seconds idempotency_retention{std::chrono::hours{24}};
};
struct LocalProviderLimits {
std::size_t max_url_bytes{8192};
std::size_t max_key_bytes{64};
std::size_t generated_key_length{16};
std::size_t max_collision_retries{8};
std::size_t max_entries{100'000};
std::size_t max_retained_identities{10'000};
std::size_t max_concurrent_ops{128};
};
using HostPolicy = std::function<bool(std::string_view host)>;
/// Validate target URL: absolute http/https, non-empty host, no userinfo,
/// no control chars, bounded length, and optional host policy check.
[[nodiscard]] inline Void::Result::Result<void>
validate_target_url(std::string_view url,
std::size_t max_url_bytes = 8192,
const HostPolicy& host_policy = {})
{
if (url.empty() || url.size() > max_url_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL empty or exceeds length limit")};
}
for (const unsigned char ch : url) {
if (ch <= 0x20 || ch >= 0x7F) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL contains control or whitespace "
"character")};
}
}
std::size_t rest_pos = 0;
if (url.starts_with("https://")) {
rest_pos = 8U;
} else if (url.starts_with("http://")) {
rest_pos = 7U;
} else {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL scheme must be http or https")};
}
const std::string_view after_scheme = url.substr(rest_pos);
const std::size_t auth_end = after_scheme.find_first_of("/?#");
const std::string_view authority = after_scheme.substr(0, auth_end);
if (authority.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: missing URL authority")};
}
if (authority.find('@') != std::string_view::npos) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: userinfo in target URL is forbidden")};
}
std::string_view host = authority;
if (host.front() == '[') {
const std::size_t close_b = host.find(']');
if (close_b == std::string_view::npos || close_b == 1U) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: malformed IPv6 host in target URL")};
}
host = host.substr(1U, close_b - 1U);
} else if (const std::size_t colon = host.find(':');
colon != std::string_view::npos) {
const std::string_view port_sv = host.substr(colon + 1U);
if (port_sv.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: empty port in target URL")};
}
for (const char c : port_sv) {
if (c < '0' || c > '9') {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: non-numeric port in target URL")};
}
}
host = host.substr(0, colon);
}
if (host.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: empty host")};
}
if (host_policy && !host_policy(host)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target host rejected by policy")};
}
return {};
}
/// Validate custom key: 1..max_key_bytes ASCII [A-Za-z0-9_-], rejecting
/// reserved route names.
[[nodiscard]] inline Void::Result::Result<void>
validate_custom_key(std::string_view key,
std::size_t max_key_bytes = 64)
{
if (key.empty() || key.size() > max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key length must be 1..64")};
}
for (const unsigned char ch : key) {
const bool ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
if (!ok) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key contains invalid character")};
}
}
static const std::set<std::string_view> kReserved{
"health", "metrics", "admin", "api", "shorten",
"resolve", "revoke", "v1", "v2", "static",
"assets", "status", "robots", "favicon"};
std::string lower;
lower.reserve(key.size());
for (const char ch : key) {
lower.push_back(static_cast<char>(
ch >= 'A' && ch <= 'Z' ? (ch - 'A' + 'a') : ch));
}
if (kReserved.contains(lower)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key matches reserved route name")};
}
return {};
}
class RandomBytesPort
{
public:
virtual ~RandomBytesPort() = default;
[[nodiscard]] virtual Void::Result::Result<void>
fill(std::span<std::byte> out) = 0;
};
class SystemRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override
{
std::random_device rd;
std::size_t i = 0;
while (i < out.size()) {
const unsigned int v = rd();
for (int b = 0; b < 4 && i < out.size(); ++b, ++i) {
out[i] = static_cast<std::byte>((v >> (b * 8)) & 0xFFU);
}
}
return {};
}
};
enum class InsertStatus : std::uint8_t {
Inserted,
IdempotentReplay,
Conflict,
IdentityExpired,
QuotaExceeded,
};
struct InsertOutcome {
InsertStatus status{InsertStatus::Inserted};
LinkRecord record{};
};
class LinkRepositoryPort
{
public:
virtual ~LinkRepositoryPort() = default;
[[nodiscard]] virtual bool is_durable() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<InsertOutcome>
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) = 0;
[[nodiscard]] virtual Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) = 0;
};
/// Explicitly nondurable in-memory repository for unit tests and semantic
/// verification. Preserves conditional insert, tombstones, and idempotency.
class InMemoryLinkRepository final : public LinkRepositoryPort
{
public:
[[nodiscard]] bool is_durable() const noexcept override
{
return false;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
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) override
{
std::lock_guard lock{m_mutex};
if (idem.has_value() && !idem->operation_id.empty()) {
if (const auto iit = m_idempotency.find(idem->operation_id);
iit != m_idempotency.end()) {
if (iit->second.retain_until_unix_seconds <=
now_unix_seconds) {
return InsertOutcome{InsertStatus::IdentityExpired,
{}};
}
if (const auto lit = m_links.find(iit->second.key);
lit != m_links.end()) {
return InsertOutcome{
InsertStatus::IdempotentReplay, lit->second};
}
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_idempotency.size() >= max_retained_identities) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
}
if (m_links.contains(record.key)) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_links.size() >= max_entries) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
m_links.emplace(record.key, record);
if (idem.has_value() && !idem->operation_id.empty()) {
m_idempotency.emplace(idem->operation_id, *idem);
}
return InsertOutcome{InsertStatus::Inserted, record};
}
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override
{
std::lock_guard lock{m_mutex};
if (const auto it = m_links.find(key); it != m_links.end()) {
return std::optional<LinkRecord>{it->second};
}
return std::optional<LinkRecord>{};
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key, std::int64_t) override
{
std::lock_guard lock{m_mutex};
const auto it = m_links.find(key);
if (it == m_links.end()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound,
"ShortUrl: cannot revoke unknown key")};
}
it->second.state = LinkState::Revoked;
return {};
}
private:
mutable std::mutex m_mutex;
std::map<std::string, LinkRecord, std::less<>> m_links;
std::map<std::string, IdempotencyRecord, std::less<>> m_idempotency;
};
/// Abstract V2 provider interface outside the frozen V1 ABI.
class Provider
{
public:
virtual ~Provider() = default;
[[nodiscard]] virtual std::string_view
provider_id() const noexcept = 0;
[[nodiscard]] virtual V1::Health health() const = 0;
[[nodiscard]] virtual bool supports_resolve() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
resolve(std::string_view key) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key) = 0;
};
struct LocalProviderOptions {
std::string public_base_url{"https://sho.rt"};
std::string provider_id{"void.local"};
LocalProviderLimits limits{};
HostPolicy host_policy{};
};
/// Native local ShortUrl V2 provider composing LinkRepositoryPort,
/// CivilClock, and RandomBytesPort with rejection-sampled base62 keys.
class LocalProvider final : public Provider
{
public:
using Options = LocalProviderOptions;
LocalProvider(std::shared_ptr<LinkRepositoryPort> repository,
Options options = Options{},
const Void::Time::CivilClock& clock =
Void::Time::SystemCivilClock::instance(),
std::shared_ptr<RandomBytesPort> rng =
std::make_shared<SystemRandomBytesPort>())
: m_repo(std::move(repository)), m_options(std::move(options)),
m_clock(&clock), m_rng(std::move(rng))
{
while (m_options.public_base_url.size() > 1U &&
m_options.public_base_url.back() == '/') {
m_options.public_base_url.pop_back();
}
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_options.provider_id;
}
[[nodiscard]] V1::Health health() const override
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo) {
return {V1::HealthStatus::unhealthy,
"provider unavailable"};
}
return {V1::HealthStatus::healthy,
m_repo->is_durable() ? "durable local provider"
: "nondurable memory provider"};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return true;
}
void shutdown() noexcept
{
m_stopping.store(true, std::memory_order_release);
}
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (auto u = validate_target_url(request.target_url,
m_options.limits.max_url_bytes,
m_options.host_policy);
!u.has_value()) {
return std::unexpected{std::move(u.error())};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (request.expires_at_unix_seconds < 0 ||
(request.expires_at_unix_seconds > 0 &&
request.expires_at_unix_seconds <= now_s)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidExpiry,
"ShortUrl: expiry must be 0 (permanent) or in the "
"future")};
}
const bool custom = !request.custom_key.empty();
if (custom) {
if (auto k = validate_custom_key(
request.custom_key, m_options.limits.max_key_bytes);
!k.has_value()) {
return std::unexpected{std::move(k.error())};
}
}
const std::size_t attempts =
custom ? 1U : m_options.limits.max_collision_retries;
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
std::string key;
if (custom) {
key = request.custom_key;
} else {
auto gen = generate_base62_key(
m_options.limits.generated_key_length);
if (!gen.has_value()) {
return std::unexpected{std::move(gen.error())};
}
key = std::move(*gen);
}
LinkRecord rec;
rec.key = key;
rec.target_url = request.target_url;
rec.created_at_unix_seconds = now_s;
rec.expires_at_unix_seconds =
request.expires_at_unix_seconds;
rec.state = LinkState::Active;
rec.operation_id = options.operation_id;
rec.schema_version = kRecordSchemaVersion;
std::optional<IdempotencyRecord> idem;
if (!options.operation_id.empty()) {
idem = IdempotencyRecord{
.operation_id = options.operation_id,
.key = key,
.target_url = request.target_url,
.created_at_unix_seconds = now_s,
.retain_until_unix_seconds =
now_s + options.idempotency_retention.count(),
};
}
auto ins = m_repo->insert_conditional(
rec, idem, now_s, m_options.limits.max_entries,
m_options.limits.max_retained_identities);
if (!ins.has_value()) {
return std::unexpected{std::move(ins.error())};
}
switch (ins->status) {
case InsertStatus::Inserted:
case InsertStatus::IdempotentReplay:
return make_link(ins->record);
case InsertStatus::Conflict:
if (custom) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: custom key already exists")};
}
continue; // retry random key
case InsertStatus::IdentityExpired:
return std::unexpected{make_shorturl_error(
V2ErrorCode::IdentityExpired,
"ShortUrl: operation_id retention expired")};
case InsertStatus::QuotaExceeded:
return std::unexpected{make_shorturl_error(
V2ErrorCode::QuotaExceeded,
"ShortUrl: repository quota or retention "
"exhausted")};
}
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: exhausted random key collision retries")};
}
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
auto rec = m_repo->get(key);
if (!rec.has_value()) {
return std::unexpected{std::move(rec.error())};
}
if (!rec->has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound, "ShortUrl: key not found")};
}
const LinkRecord& r = **rec;
if (r.state == LinkState::Revoked) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Revoked, "ShortUrl: link revoked")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (r.expires_at_unix_seconds > 0 &&
r.expires_at_unix_seconds <= now_s) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Expired, "ShortUrl: link expired")};
}
return make_link(r);
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
return m_repo->revoke(key, now_s);
}
private:
struct OpSlot {
std::atomic<std::size_t>* active{nullptr};
~OpSlot() noexcept
{
if (active != nullptr) {
active->fetch_sub(1, std::memory_order_acq_rel);
}
}
OpSlot(std::atomic<std::size_t>* a) noexcept : active(a) {}
OpSlot(OpSlot&& o) noexcept
: active(std::exchange(o.active, nullptr))
{
}
OpSlot(const OpSlot&) = delete;
OpSlot& operator=(const OpSlot&) = delete;
};
[[nodiscard]] Void::Result::Result<OpSlot> try_admit()
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo ||
!m_rng) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
"ShortUrl: provider shut down or unconfigured")};
}
std::size_t cur = m_active_ops.load(std::memory_order_relaxed);
for (;;) {
if (cur >= m_options.limits.max_concurrent_ops) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::RateLimited,
"ShortUrl: max concurrent operations reached")};
}
if (m_active_ops.compare_exchange_weak(
cur, cur + 1U, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return OpSlot{&m_active_ops};
}
}
}
[[nodiscard]] Void::Result::Result<std::string>
generate_base62_key(std::size_t len) const
{
static constexpr char kAlphabet[63] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
"wxyz";
constexpr unsigned char kCutoff = 62U * 4U; // 248 (uniform)
std::string out;
out.reserve(len);
std::array<std::byte, 64> buf{};
while (out.size() < len) {
auto r = m_rng->fill(buf);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
for (const std::byte b : buf) {
const auto u = static_cast<unsigned char>(b);
if (u < kCutoff) {
out.push_back(kAlphabet[u % 62U]);
if (out.size() == len) {
break;
}
}
}
}
return out;
}
[[nodiscard]] Link make_link(const LinkRecord& r) const
{
return Link{
.key = r.key,
.short_url =
std::format("{}/{}", m_options.public_base_url, r.key),
.target_url = r.target_url,
.expires_at_unix_seconds = r.expires_at_unix_seconds,
};
}
std::shared_ptr<LinkRepositoryPort> m_repo;
Options m_options;
const Void::Time::CivilClock* m_clock;
std::shared_ptr<RandomBytesPort> m_rng;
std::atomic<bool> m_stopping{false};
std::atomic<std::size_t> m_active_ops{0};
};
/// Adapter implementing frozen `Void::ShortUrl::V1::IShortener` on top of
/// any V2 `Provider` without changing V1 layout or virtual table order.
class V1Adapter final : public V1::IShortener
{
public:
explicit V1Adapter(std::shared_ptr<Provider> provider)
: m_provider(std::move(provider))
{
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_provider ? m_provider->provider_id()
: std::string_view{"unconfigured"};
}
[[nodiscard]] V1::Health health() const override
{
return m_provider ? m_provider->health()
: V1::Health{V1::HealthStatus::unhealthy,
"null provider"};
}
[[nodiscard]] V1::ShortenResult
shorten(const V1::ShortenRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->shorten(CreateLink{
.target_url = request.target_url,
.custom_key = request.custom_key,
.expires_at_unix_seconds = request.expires_at_unix_seconds,
});
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.short_url = std::move(res->short_url),
.key = std::move(res->key),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return m_provider != nullptr && m_provider->supports_resolve();
}
[[nodiscard]] V1::ResolveResult
resolve(const V1::ResolveRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->resolve(request.key);
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.target_url = std::move(res->target_url),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
private:
std::shared_ptr<Provider> m_provider;
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,67 @@
#pragma once
#include <Void/Net/Http.hpp>
#include <Void/ShortUrl/V2.hpp>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::ShortUrl::V2
{
struct RemoteCapabilities {
bool supports_custom_key{true};
bool supports_expiry{true};
bool supports_resolve{true};
bool supports_revoke{true};
};
struct RemoteProviderOptions {
std::string base_url{};
std::string provider_id{"void.remote"};
RemoteCapabilities capabilities{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
.max_body_size = 1024ULL * 1024,
};
std::chrono::seconds timeout{std::chrono::seconds{10}};
std::uint64_t max_response_bytes{1024ULL * 1024};
std::vector<Void::Net::Header> headers{};
};
/// Generic remote ShortUrl V2 provider over `Void::Net::HttpClient`.
/// Checks capability flags before network mutation, enforces response size
/// and deadline bounds, preserves Retry-After, and maps lost-reply
/// transport failures after send to `V2ErrorCode::UnknownOutcome`.
class RemoteProvider final : public Provider
{
public:
explicit RemoteProvider(RemoteProviderOptions options);
[[nodiscard]] std::string_view
provider_id() const noexcept override;
[[nodiscard]] V1::Health health() const override;
[[nodiscard]] bool supports_resolve() const noexcept override;
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override;
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override;
/// Retry-After seconds from the most recent rate-limited/unavailable
/// remote response (0 if absent).
[[nodiscard]] std::uint32_t last_retry_after_seconds() const noexcept;
private:
RemoteProviderOptions m_options;
Void::Net::HttpClient m_client;
std::atomic<std::uint32_t> m_last_retry_after{0};
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,58 @@
#pragma once
#include <Void/ShortUrl/V2.hpp>
#include <Void/Storage/Engine.hpp>
#include <cstdint>
#include <memory>
#include <mutex>
namespace Void::ShortUrl::V2
{
/// CSPRNG byte source backed by `Void::Security` (libsodium).
class SecurityRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override;
};
/// Durable `LinkRepositoryPort` backed by `Void::Storage::Engine`
/// conditional `Batch` writes, preserving tombstones, V2 idempotency
/// records, and quotas across crash/restart boundaries.
class StorageLinkRepository final : public LinkRepositoryPort
{
public:
explicit StorageLinkRepository(
std::shared_ptr<Void::Storage::Engine> engine,
std::uint64_t disk_quota_bytes = 1024ULL * 1024 * 1024);
[[nodiscard]] bool is_durable() const noexcept override
{
return true;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
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) override;
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) override;
private:
mutable std::mutex m_write_mutex;
std::shared_ptr<Void::Storage::Engine> m_engine;
std::uint64_t m_disk_quota_bytes;
};
} // namespace Void::ShortUrl::V2
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(ShortUrl
INTERNAL_DEPS Service
INTERNAL_DEPS Service Time
)
+368
View File
@@ -0,0 +1,368 @@
#include <Void/ShortUrlRemote/RemoteProvider.hpp>
#include <Void/Data/StrictJson.hpp>
#include <charconv>
#include <format>
#include <string>
#include <string_view>
namespace Void::ShortUrl::V2
{
namespace
{
[[nodiscard]] std::uint32_t
parse_retry_after(const Void::Net::Response& resp) noexcept
{
auto hdr = resp.header("Retry-After");
if (!hdr.has_value() || hdr->empty()) {
return 0;
}
std::uint32_t sec = 0;
const auto [ptr, ec] =
std::from_chars(hdr->data(), hdr->data() + hdr->size(), sec);
if (ec != std::errc{} || ptr != hdr->data() + hdr->size()) {
return 0;
}
return sec;
}
[[nodiscard]] const std::string*
find_string(const Void::Json::Strict::Value::Object& obj,
std::string_view key) noexcept
{
const auto it = obj.find(key);
if (it == obj.end()) {
return nullptr;
}
return std::get_if<std::string>(&it->second.value);
}
[[nodiscard]] std::optional<std::int64_t>
find_i64(const Void::Json::Strict::Value::Object& obj,
std::string_view key) noexcept
{
const auto it = obj.find(key);
if (it == obj.end()) {
return std::nullopt;
}
if (const auto* v = std::get_if<std::int64_t>(&it->second.value)) {
return *v;
}
return std::nullopt;
}
[[nodiscard]] V2ErrorCode
map_http_status_to_v2(std::uint16_t status) noexcept
{
switch (status) {
case 400: return V2ErrorCode::InvalidRequest;
case 401:
case 403: return V2ErrorCode::Unauthorized;
case 404: return V2ErrorCode::NotFound;
case 408: return V2ErrorCode::Timeout;
case 409: return V2ErrorCode::Conflict;
case 410: return V2ErrorCode::Revoked;
case 413: return V2ErrorCode::ResponseTooLarge;
case 422: return V2ErrorCode::InvalidUrl;
case 429: return V2ErrorCode::RateLimited;
case 501: return V2ErrorCode::Unsupported;
case 503: return V2ErrorCode::Unavailable;
case 504: return V2ErrorCode::Timeout;
default: return V2ErrorCode::ProviderError;
}
}
} // namespace
RemoteProvider::RemoteProvider(RemoteProviderOptions options)
: m_options(std::move(options)), m_client(m_options.http_options)
{
while (m_options.base_url.size() > 1U &&
m_options.base_url.back() == '/') {
m_options.base_url.pop_back();
}
m_client.set_max_body_size(m_options.max_response_bytes);
}
std::string_view RemoteProvider::provider_id() const noexcept
{
return m_options.provider_id;
}
V1::Health RemoteProvider::health() const
{
if (m_options.base_url.empty()) {
return {V1::HealthStatus::unhealthy, "empty remote base_url"};
}
return {V1::HealthStatus::healthy, "remote provider configured"};
}
bool RemoteProvider::supports_resolve() const noexcept
{
return m_options.capabilities.supports_resolve;
}
std::uint32_t RemoteProvider::last_retry_after_seconds() const noexcept
{
return m_last_retry_after.load(std::memory_order_acquire);
}
Void::Result::Result<Link>
RemoteProvider::shorten(const CreateLink& request,
const ShortenOptions& options)
{
m_last_retry_after.store(0, std::memory_order_release);
// Check capability flags BEFORE any network mutation.
if (!request.custom_key.empty() &&
!m_options.capabilities.supports_custom_key) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support custom keys")};
}
if (request.expires_at_unix_seconds != 0 &&
!m_options.capabilities.supports_expiry) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support link expiry")};
}
if (auto u = validate_target_url(request.target_url); !u.has_value()) {
return std::unexpected{std::move(u.error())};
}
if (!request.custom_key.empty()) {
if (auto k = validate_custom_key(request.custom_key);
!k.has_value()) {
return std::unexpected{std::move(k.error())};
}
}
Void::Json::Strict::Value::Object obj;
obj.emplace("target_url",
Void::Json::Strict::Value{request.target_url});
if (!request.custom_key.empty()) {
obj.emplace("custom_key",
Void::Json::Strict::Value{request.custom_key});
}
if (request.expires_at_unix_seconds != 0) {
obj.emplace(
"expires_at_unix_seconds",
Void::Json::Strict::Value{request.expires_at_unix_seconds});
}
if (!options.operation_id.empty()) {
obj.emplace("operation_id",
Void::Json::Strict::Value{options.operation_id});
}
auto body = Void::Json::Strict::serialize(
Void::Json::Strict::Value{std::move(obj)});
if (!body.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidRequest,
std::format("ShortUrlRemote: serialize failed: {}",
body.error().message))};
}
Void::Net::Request req;
req.method = Void::Net::Method::Post;
req.url = m_options.base_url + "/v2/shorten";
req.headers = m_options.headers;
req.headers.push_back({"Content-Type", "application/json"});
if (!options.operation_id.empty()) {
req.headers.push_back({"Idempotency-Key", options.operation_id});
}
req.body = std::move(*body);
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
// Transport timeout or lost reply after mutation send: classify as
// UnknownOutcome without fabricating a local rollback or replay.
if (resp.error().kind() == Void::Result::ErrorKind::timeout ||
resp.error().kind() == Void::Result::ErrorKind::io) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlRemote: shorten outcome unknown: {}",
resp.error().message()))};
}
if (resp.error().kind() == Void::Result::ErrorKind::exhausted) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
std::format("ShortUrlRemote: response too large: {}",
resp.error().message()))};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: transport error: {}",
resp.error().message()))};
}
if (resp->body.size() > m_options.max_response_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
"ShortUrlRemote: response exceeds max_response_bytes")};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: shorten HTTP {}", resp->status))};
}
auto parsed = Void::Json::Strict::parse(resp->body);
if (!parsed.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: invalid JSON response")};
}
const auto* root =
std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (root == nullptr) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: expected JSON object")};
}
const auto* key = find_string(*root, "key");
const auto* short_url = find_string(*root, "short_url");
if (key == nullptr || key->empty() || short_url == nullptr ||
short_url->empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: response missing key or short_url")};
}
const auto* target = find_string(*root, "target_url");
return Link{
.key = *key,
.short_url = *short_url,
.target_url = target ? *target : request.target_url,
.expires_at_unix_seconds =
find_i64(*root, "expires_at_unix_seconds")
.value_or(request.expires_at_unix_seconds),
.retry_after_seconds = retry_after,
};
}
Void::Result::Result<Link> RemoteProvider::resolve(std::string_view key)
{
m_last_retry_after.store(0, std::memory_order_release);
if (!m_options.capabilities.supports_resolve) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support resolve")};
}
if (auto k = validate_custom_key(key); !k.has_value()) {
return std::unexpected{std::move(k.error())};
}
Void::Net::Request req;
req.method = Void::Net::Method::Get;
req.url = std::format("{}/v2/resolve/{}", m_options.base_url, key);
req.headers = m_options.headers;
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
if (resp.error().kind() == Void::Result::ErrorKind::timeout) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Timeout,
std::format("ShortUrlRemote: resolve timed out: {}",
resp.error().message()))};
}
if (resp.error().kind() == Void::Result::ErrorKind::exhausted) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
"ShortUrlRemote: resolve response too large")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: resolve transport failed: {}",
resp.error().message()))};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: resolve HTTP {}", resp->status))};
}
auto parsed = Void::Json::Strict::parse(resp->body);
if (!parsed.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: invalid JSON resolve response")};
}
const auto* root =
std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (root == nullptr) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: expected JSON object")};
}
const auto* target = find_string(*root, "target_url");
if (target == nullptr || target->empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: missing target_url in resolve response")};
}
const auto* short_url = find_string(*root, "short_url");
return Link{
.key = std::string{key},
.short_url = short_url ? *short_url : std::string{},
.target_url = *target,
.expires_at_unix_seconds =
find_i64(*root, "expires_at_unix_seconds").value_or(0),
.retry_after_seconds = retry_after,
};
}
Void::Result::Result<void> RemoteProvider::revoke(std::string_view key)
{
m_last_retry_after.store(0, std::memory_order_release);
if (!m_options.capabilities.supports_revoke) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support revoke")};
}
if (auto k = validate_custom_key(key); !k.has_value()) {
return std::unexpected{std::move(k.error())};
}
Void::Net::Request req;
req.method = Void::Net::Method::Delete;
req.url = std::format("{}/v2/links/{}", m_options.base_url, key);
req.headers = m_options.headers;
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
if (resp.error().kind() == Void::Result::ErrorKind::timeout ||
resp.error().kind() == Void::Result::ErrorKind::io) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlRemote: revoke outcome unknown: {}",
resp.error().message()))};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: revoke failed: {}",
resp.error().message()))};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: revoke HTTP {}", resp->status))};
}
return {};
}
} // namespace Void::ShortUrl::V2
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ShortUrlRemote
INTERNAL_DEPS ShortUrl Net Data
)
+470
View File
@@ -0,0 +1,470 @@
#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
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ShortUrlStorage
INTERNAL_DEPS ShortUrl Storage Security
)
+14
View File
@@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 4.0)
project(VoidShortUrlOnlyConsumer LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Void CONFIG REQUIRED COMPONENTS ShortUrl)
add_executable(short_url_only_consumer main.cpp)
target_link_libraries(short_url_only_consumer PRIVATE Void::ShortUrl)
enable_testing()
add_test(NAME short_url_only_consumer COMMAND short_url_only_consumer)
+21
View File
@@ -0,0 +1,21 @@
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/ShortUrl/V2.hpp>
#include <memory>
int main()
{
using namespace Void::ShortUrl::V2;
auto repo = std::make_shared<InMemoryLinkRepository>();
auto provider = std::make_shared<LocalProvider>(repo);
V1Adapter v1{provider};
auto s = v1.shorten({.target_url = "https://example.com/pkg"});
if (!s.ok()) {
return 1;
}
auto r = v1.resolve({.key = s.key});
if (!r.ok() || r.target_url != "https://example.com/pkg") {
return 2;
}
return 0;
}
+150
View File
@@ -0,0 +1,150 @@
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/ShortUrl/V2.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
// Freeze checks on V1 enum ordinals & version constants.
static_assert(Void::ShortUrl::V1::kServiceVersion == 1U);
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::none) == 0U);
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::unsupported) == 2U);
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::revoked) == 13U);
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::response_too_large) == 15U);
Void::Testing::Test shorturl_v2_local_validation_expiry_revoke_and_idempotency()
{
using namespace Void::ShortUrl::V2;
Void::Time::ManualCivilClock clock{
Void::Time::CivilClock::time_point{std::chrono::seconds{1'700'000'000}}};
auto repo = std::make_shared<InMemoryLinkRepository>();
Void::Testing::expect(!repo->is_durable());
LocalProvider::Options opts;
opts.public_base_url = "https://sho.rt/s";
opts.limits.max_entries = 10;
opts.limits.max_retained_identities = 5;
opts.host_policy = [](std::string_view host) {
return host != "blocked.internal";
};
auto provider = std::make_shared<LocalProvider>(repo, opts, clock);
// 1. Validation rejects userinfo, non-http, control chars, denied host,
// reserved keys, and past expiry.
Void::Testing::expect(
!provider->shorten({.target_url = "https://user:pw@example.com/a"})
.has_value());
Void::Testing::expect(
!provider->shorten({.target_url = "ftp://example.com/a"}).has_value());
Void::Testing::expect(
!provider->shorten({.target_url = "https://blocked.internal/x"})
.has_value());
Void::Testing::expect(
!provider
->shorten({.target_url = "https://example.com/a",
.custom_key = "health"})
.has_value());
Void::Testing::expect(
!provider
->shorten({.target_url = "https://example.com/a",
.expires_at_unix_seconds = 1'699'999'999})
.has_value());
// 2. Generated 16-char base62 key + V2 idempotency replay within 24h.
auto created = provider->shorten(
{.target_url = "https://example.com/page"},
ShortenOptions{.operation_id = "op-001"});
Void::Testing::require(created.has_value());
Void::Testing::expect_eq(created->key.size(), std::size_t{16});
Void::Testing::expect_eq(created->short_url,
"https://sho.rt/s/" + created->key);
auto replay = provider->shorten(
{.target_url = "https://example.com/page"},
ShortenOptions{.operation_id = "op-001"});
Void::Testing::require(replay.has_value());
Void::Testing::expect_eq(replay->key, created->key);
// 3. Custom key conflict & tombstone non-reuse after revoke.
auto custom = provider->shorten({
.target_url = "https://example.com/custom",
.custom_key = "my_Link-1",
.expires_at_unix_seconds = 1'700'003'600,
});
Void::Testing::require(custom.has_value());
Void::Testing::expect_eq(custom->key, std::string{"my_Link-1"});
auto conflict = provider->shorten({
.target_url = "https://example.com/other",
.custom_key = "my_Link-1",
});
Void::Testing::expect(!conflict.has_value());
Void::Testing::expect(v2_error_code_from(conflict.error()) ==
V2ErrorCode::Conflict);
auto resolved = provider->resolve("my_Link-1");
Void::Testing::require(resolved.has_value());
Void::Testing::expect_eq(resolved->target_url,
std::string{"https://example.com/custom"});
// Revoke creates tombstone; resolve returns Revoked and key cannot be
// reused.
Void::Testing::require(provider->revoke("my_Link-1").has_value());
auto after_revoke = provider->resolve("my_Link-1");
Void::Testing::expect(!after_revoke.has_value());
Void::Testing::expect(v2_error_code_from(after_revoke.error()) ==
V2ErrorCode::Revoked);
auto reuse = provider->shorten({
.target_url = "https://example.com/reused",
.custom_key = "my_Link-1",
});
Void::Testing::expect(!reuse.has_value());
Void::Testing::expect(v2_error_code_from(reuse.error()) ==
V2ErrorCode::Conflict);
// 4. Expiry via ManualCivilClock + idempotency retention expiry.
auto exp_link = provider->shorten({
.target_url = "https://example.com/temp",
.custom_key = "temp1",
.expires_at_unix_seconds = 1'700'000'100,
});
Void::Testing::require(exp_link.has_value());
Void::Testing::require(clock.advance(std::chrono::seconds{200}).has_value());
auto exp_res = provider->resolve("temp1");
Void::Testing::expect(!exp_res.has_value());
Void::Testing::expect(v2_error_code_from(exp_res.error()) ==
V2ErrorCode::Expired);
Void::Testing::require(clock.advance(std::chrono::hours{25}).has_value());
auto expired_idem = provider->shorten(
{.target_url = "https://example.com/page"},
ShortenOptions{.operation_id = "op-001"});
Void::Testing::expect(!expired_idem.has_value());
Void::Testing::expect(v2_error_code_from(expired_idem.error()) ==
V2ErrorCode::IdentityExpired);
// 5. V1Adapter bridges V2 provider to frozen V1::IShortener cleanly.
V1Adapter v1{provider};
Void::Testing::expect_eq(v1.service_name(), Void::ShortUrl::V1::kServiceId);
Void::Testing::expect_eq(v1.service_version(), std::uint32_t{1});
Void::Testing::expect(v1.supports_resolve());
auto s_v1 = v1.shorten({.target_url = "https://example.com/v1"});
Void::Testing::require(s_v1.ok());
auto r_v1 = v1.resolve({.key = s_v1.key});
Void::Testing::require(r_v1.ok());
Void::Testing::expect_eq(r_v1.target_url,
std::string{"https://example.com/v1"});
auto r_revoked = v1.resolve({.key = "my_Link-1"});
Void::Testing::expect(!r_revoked.ok());
Void::Testing::expect(r_revoked.error.code ==
Void::ShortUrl::V1::ErrorCode::revoked);
}
@@ -0,0 +1,158 @@
#include <Void/Data/StrictJson.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/ShortUrlRemote/RemoteProvider.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <memory>
#include <string>
#include <thread>
Void::Testing::Test shorturl_remote_provider_capabilities_retry_after_and_unknown()
{
using namespace Void::ShortUrl::V2;
Void::Net::HttpServer server;
std::atomic<int> shorten_calls{0};
std::atomic<bool> stall_next{false};
std::atomic<bool> release_stall{false};
Void::Testing::require(
server
.add_route(
Void::Net::Method::Post, "/v2/shorten",
[&](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
const int n =
shorten_calls.fetch_add(1, std::memory_order_relaxed);
if (stall_next.load(std::memory_order_acquire)) {
for (int i = 0; i < 200 &&
!release_stall.load(
std::memory_order_acquire);
++i) {
std::this_thread::sleep_for(
std::chrono::milliseconds{20});
}
return Void::Net::ServerResponse{.status = 200,
.body = "{}"};
}
if (n == 1) {
return Void::Net::ServerResponse{
.status = 429,
.headers = {{"Retry-After", "45"}},
.body = "slow down"};
}
auto parsed = Void::Json::Strict::parse(req.body);
Void::Testing::require(parsed.has_value());
const auto& obj =
std::get<Void::Json::Strict::Value::Object>(
parsed->value);
const std::string target =
std::get<std::string>(obj.at("target_url").value);
return Void::Net::ServerResponse{
.status = 200,
.headers = {{"Content-Type", "application/json"}},
.body = "{\"key\":\"rem01\",\"short_url\":\"https://"
"rem.test/rem01\",\"target_url\":\"" +
target + "\"}",
};
})
.has_value());
Void::Testing::require(
server
.add_route(
Void::Net::Method::Get, "/v2/resolve/:key",
[](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
const auto it = req.parameters.find("key");
if (it == req.parameters.end() || it->second != "rem01") {
return Void::Net::ServerResponse{.status = 404,
.body = "missing"};
}
return Void::Net::ServerResponse{
.status = 200,
.headers = {{"Content-Type", "application/json"}},
.body =
"{\"target_url\":\"https://example.com/remote\","
"\"short_url\":\"https://rem.test/rem01\"}",
};
})
.has_value());
Void::Testing::require(
server
.add_route(Void::Net::Method::Delete, "/v2/links/:key",
[](const Void::Net::ServerRequest&)
-> Void::Net::RouteResult {
return Void::Net::ServerResponse{.status = 204,
.body = ""};
})
.has_value());
Void::Testing::require(server.start().has_value());
// 1. Unsupported capability rejected BEFORE any network call!
{
RemoteProviderOptions opts;
opts.base_url = server.base_url();
opts.capabilities.supports_custom_key = false;
opts.capabilities.supports_expiry = false;
opts.capabilities.supports_resolve = false;
RemoteProvider restricted{opts};
auto no_custom = restricted.shorten({
.target_url = "https://example.com/a",
.custom_key = "nope",
});
Void::Testing::expect(!no_custom.has_value());
Void::Testing::expect(v2_error_code_from(no_custom.error()) ==
V2ErrorCode::Unsupported);
Void::Testing::expect_eq(shorten_calls.load(), 0);
auto no_resolve = restricted.resolve("rem01");
Void::Testing::expect(!no_resolve.has_value());
Void::Testing::expect(v2_error_code_from(no_resolve.error()) ==
V2ErrorCode::Unsupported);
}
// 2. Full round-trip, 429 Retry-After preservation, and timeout ->
// UnknownOutcome without blind replay.
RemoteProviderOptions opts;
opts.base_url = server.base_url();
opts.timeout = std::chrono::seconds{1};
auto provider = std::make_shared<RemoteProvider>(opts);
auto ok = provider->shorten({.target_url = "https://example.com/remote"},
ShortenOptions{.operation_id = "rem-op-1"});
Void::Testing::require(ok.has_value());
Void::Testing::expect_eq(ok->key, std::string{"rem01"});
auto res = provider->resolve("rem01");
Void::Testing::require(res.has_value());
Void::Testing::expect_eq(res->target_url,
std::string{"https://example.com/remote"});
Void::Testing::require(provider->revoke("rem01").has_value());
// Second shorten hits 429 with Retry-After: 45.
auto rl = provider->shorten({.target_url = "https://example.com/rate"});
Void::Testing::expect(!rl.has_value());
Void::Testing::expect(v2_error_code_from(rl.error()) ==
V2ErrorCode::RateLimited);
Void::Testing::expect_eq(provider->last_retry_after_seconds(),
std::uint32_t{45});
// Third shorten stalls until 1s timeout -> UnknownOutcome (and V1Adapter
// maps it to provider_error).
stall_next.store(true, std::memory_order_release);
auto unk = provider->shorten({.target_url = "https://example.com/lost"});
Void::Testing::expect(!unk.has_value());
Void::Testing::expect(v2_error_code_from(unk.error()) ==
V2ErrorCode::UnknownOutcome);
release_stall.store(true, std::memory_order_release);
server.shutdown();
}
@@ -0,0 +1,109 @@
#include <Void/ShortUrlStorage/StorageRepository.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <memory>
#include <string>
Void::Testing::Test shorturl_storage_durable_persistence_tombstones_and_quota()
{
using namespace Void::ShortUrl::V2;
Void::FileSystem::TempDir tmp{"void_shorturl_storage_"};
Void::Time::ManualCivilClock clock{
Void::Time::CivilClock::time_point{std::chrono::seconds{1'700'000'000}}};
std::string generated_key;
{
Void::Storage::OpenOptions sopt;
sopt.directory = tmp.path() / "db";
auto eng = Void::Storage::Engine::open(sopt);
Void::Testing::require(eng.has_value());
auto shared_eng =
std::make_shared<Void::Storage::Engine>(std::move(*eng));
auto repo = std::make_shared<StorageLinkRepository>(shared_eng);
Void::Testing::expect(repo->is_durable());
auto rng = std::make_shared<SecurityRandomBytesPort>();
LocalProvider::Options lopt;
lopt.public_base_url = "https://sho.rt";
LocalProvider provider{repo, lopt, clock, rng};
auto a = provider.shorten({.target_url = "https://example.com/durable"},
ShortenOptions{.operation_id = "dur-op-1"});
Void::Testing::require(a.has_value());
generated_key = a->key;
Void::Testing::expect_eq(generated_key.size(), std::size_t{16});
auto b = provider.shorten({
.target_url = "https://example.com/killme",
.custom_key = "revokeme",
});
Void::Testing::require(b.has_value());
Void::Testing::require(provider.revoke("revokeme").has_value());
Void::Testing::require(shared_eng->close().has_value());
}
// Reopen Storage::Engine from disk and verify durable link, idempotency
// replay, and persisted tombstone non-reuse.
{
Void::Storage::OpenOptions sopt;
sopt.directory = tmp.path() / "db";
auto eng = Void::Storage::Engine::open(sopt);
Void::Testing::require(eng.has_value());
auto shared_eng =
std::make_shared<Void::Storage::Engine>(std::move(*eng));
// Tight disk quota test on separate small repo instance check below,
// first verify normal recovery.
auto repo = std::make_shared<StorageLinkRepository>(shared_eng);
LocalProvider::Options lopt;
lopt.public_base_url = "https://sho.rt";
LocalProvider provider{repo, lopt, clock,
std::make_shared<SecurityRandomBytesPort>()};
auto res = provider.resolve(generated_key);
Void::Testing::require(res.has_value());
Void::Testing::expect_eq(res->target_url,
std::string{"https://example.com/durable"});
// V2 idempotency replay survives restart!
auto replay = provider.shorten(
{.target_url = "https://example.com/durable"},
ShortenOptions{.operation_id = "dur-op-1"});
Void::Testing::require(replay.has_value());
Void::Testing::expect_eq(replay->key, generated_key);
// Tombstone survives restart and blocks reuse!
auto rev = provider.resolve("revokeme");
Void::Testing::expect(!rev.has_value());
Void::Testing::expect(v2_error_code_from(rev.error()) ==
V2ErrorCode::Revoked);
auto reuse = provider.shorten({
.target_url = "https://example.com/new",
.custom_key = "revokeme",
});
Void::Testing::expect(!reuse.has_value());
Void::Testing::expect(v2_error_code_from(reuse.error()) ==
V2ErrorCode::Conflict);
// Quota enforcement rejects insert once quota is exhausted.
auto tiny_repo =
std::make_shared<StorageLinkRepository>(shared_eng, 32ULL);
LocalProvider tight_provider{
tiny_repo, lopt, clock,
std::make_shared<SecurityRandomBytesPort>()};
auto over = tight_provider.shorten(
{.target_url = "https://example.com/too-big",
.custom_key = "quota1"});
Void::Testing::expect(!over.has_value());
Void::Testing::expect(v2_error_code_from(over.error()) ==
V2ErrorCode::QuotaExceeded);
Void::Testing::require(shared_eng->close().has_value());
}
}