896 lines
27 KiB
C++
896 lines
27 KiB
C++
#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
|