feat(shorturl): complete P2 M-SHORTURL-01..04 V2 local, storage, and remote providers with frozen V1
This commit is contained in:
1 parent
658c21a2fa
commit
691808eab6
13 files changed
+2317
-1
No files matched your search
@@ -1,3 +1,3 @@
|
||||
void_add_module(ShortUrl
|
||||
INTERNAL_DEPS Service
|
||||
INTERNAL_DEPS Service Time
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(ShortUrlRemote
|
||||
INTERNAL_DEPS ShortUrl Net Data
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(ShortUrlStorage
|
||||
INTERNAL_DEPS ShortUrl Storage Security
|
||||
)
|
||||
Reference in new issue
Block a user