commit
9044e4a9d4
5 files changed
+1215
No files matched your search
@@ -0,0 +1,62 @@
|
||||
set(_internal_sources
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/src/Common.cpp"
|
||||
src/InternalStore.cpp)
|
||||
|
||||
add_library(EchoionUrlShortenerInternalPlugin MODULE
|
||||
${_internal_sources}
|
||||
src/Plugin.cpp)
|
||||
target_include_directories(EchoionUrlShortenerInternalPlugin PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/include")
|
||||
target_compile_features(EchoionUrlShortenerInternalPlugin PRIVATE cxx_std_26)
|
||||
target_link_libraries(EchoionUrlShortenerInternalPlugin PRIVATE
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiConfig
|
||||
Void::ShortUrl
|
||||
Void::Data
|
||||
Void::Net
|
||||
Void::Text
|
||||
Void::Sqlite
|
||||
Void::Crypto
|
||||
OpenSSL::Crypto)
|
||||
set_target_properties(EchoionUrlShortenerInternalPlugin PROPERTIES
|
||||
PREFIX ""
|
||||
OUTPUT_NAME "url-shortener-internal"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
|
||||
BUILD_RPATH_USE_ORIGIN ON
|
||||
INSTALL_RPATH ""
|
||||
INSTALL_RPATH_USE_LINK_PATH FALSE)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(EchoionUrlShortenerInternalPlugin PRIVATE /W4 /WX-)
|
||||
else()
|
||||
target_compile_options(EchoionUrlShortenerInternalPlugin PRIVATE
|
||||
-Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
install(TARGETS EchoionUrlShortenerInternalPlugin
|
||||
LIBRARY DESTINATION
|
||||
"${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-internal/${ECHOION_URL_SHORTENER_INTERNAL_VERSION}"
|
||||
COMPONENT Runtime
|
||||
RUNTIME DESTINATION
|
||||
"${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-internal/${ECHOION_URL_SHORTENER_INTERNAL_VERSION}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_url_shortener_internal_tests
|
||||
${_internal_sources}
|
||||
tests/InternalStoreTests.cpp)
|
||||
target_include_directories(echoion_url_shortener_internal_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/include")
|
||||
target_compile_features(echoion_url_shortener_internal_tests PRIVATE
|
||||
cxx_std_26)
|
||||
target_link_libraries(echoion_url_shortener_internal_tests PRIVATE
|
||||
Void::Data Void::Net Void::Text Void::Sqlite Void::Crypto
|
||||
OpenSSL::Crypto Threads::Threads)
|
||||
add_test(NAME echoion_url_shortener_internal_tests
|
||||
COMMAND echoion_url_shortener_internal_tests)
|
||||
set_tests_properties(echoion_url_shortener_internal_tests PROPERTIES
|
||||
TIMEOUT 20)
|
||||
endif()
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
enum class InternalErrorCode {
|
||||
invalidRequest,
|
||||
notFound,
|
||||
expired,
|
||||
conflict,
|
||||
storage,
|
||||
unavailable,
|
||||
};
|
||||
|
||||
struct InternalError {
|
||||
InternalErrorCode code{InternalErrorCode::unavailable};
|
||||
std::string message;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
using InternalResult = std::expected<T, InternalError>;
|
||||
|
||||
struct InternalConfig {
|
||||
std::filesystem::path databasePath;
|
||||
std::string publicBaseUrl;
|
||||
std::size_t slugLength{10};
|
||||
};
|
||||
|
||||
struct InternalLink {
|
||||
std::string shortUrl;
|
||||
std::string key;
|
||||
std::string targetUrl;
|
||||
std::int64_t expiresAtUnixSeconds{};
|
||||
};
|
||||
|
||||
struct InternalStats {
|
||||
std::uint64_t total{};
|
||||
std::uint64_t active{};
|
||||
std::uint64_t expired{};
|
||||
std::uint64_t revoked{};
|
||||
std::uint64_t hits{};
|
||||
};
|
||||
|
||||
class InternalStore
|
||||
{
|
||||
private:
|
||||
|
||||
struct ConstructionToken {
|
||||
explicit ConstructionToken() = default;
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
[[nodiscard]] static InternalResult<std::unique_ptr<InternalStore>>
|
||||
open(InternalConfig config);
|
||||
|
||||
InternalStore(const InternalStore&) = delete;
|
||||
InternalStore& operator=(const InternalStore&) = delete;
|
||||
|
||||
[[nodiscard]] InternalResult<InternalLink>
|
||||
shorten(std::string_view targetUrl,
|
||||
std::string_view customKey = {},
|
||||
std::int64_t expiresAtUnixSeconds = 0);
|
||||
[[nodiscard]] InternalResult<InternalLink>
|
||||
resolve(std::string_view key);
|
||||
[[nodiscard]] InternalResult<void> revoke(std::string_view key);
|
||||
[[nodiscard]] InternalResult<InternalStats> stats();
|
||||
[[nodiscard]] InternalResult<std::uint64_t>
|
||||
cleanup(bool includeRevoked = false);
|
||||
|
||||
[[nodiscard]] const InternalConfig& config() const noexcept
|
||||
{
|
||||
return config_;
|
||||
}
|
||||
|
||||
InternalStore(ConstructionToken, InternalConfig config,
|
||||
Void::Sqlite::Database database);
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] InternalResult<std::string> generateKey() const;
|
||||
[[nodiscard]] std::string shortUrl(std::string_view key) const;
|
||||
|
||||
InternalConfig config_;
|
||||
Void::Sqlite::Database database_;
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
@@ -0,0 +1,421 @@
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kAlphabet =
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
constexpr std::size_t kMinimumCustomKeyLength = 3;
|
||||
constexpr std::size_t kMaximumKeyLength = 64;
|
||||
constexpr std::size_t kMaximumGenerationAttempts = 32;
|
||||
constexpr unsigned kLargestUnbiasedByte = 248;
|
||||
|
||||
[[nodiscard]] std::int64_t nowUnixSeconds() noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] InternalError
|
||||
storageError(std::string_view operation,
|
||||
const Void::Result::Error& error)
|
||||
{
|
||||
return {
|
||||
.code = InternalErrorCode::storage,
|
||||
.message = std::format("{}: {}", operation, error.message()),
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isCurrent(const std::int64_t expiresAt,
|
||||
const std::int64_t now) noexcept
|
||||
{
|
||||
return expiresAt == 0 || expiresAt > now;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
InternalStore::InternalStore(ConstructionToken, InternalConfig config,
|
||||
Void::Sqlite::Database database)
|
||||
: config_(std::move(config)), database_(std::move(database))
|
||||
{
|
||||
}
|
||||
|
||||
InternalResult<std::unique_ptr<InternalStore>>
|
||||
InternalStore::open(InternalConfig config)
|
||||
{
|
||||
if (config.databasePath.empty()) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "database path is required",
|
||||
}};
|
||||
}
|
||||
if (config.slugLength != 10) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "generated slug length must be exactly 10",
|
||||
}};
|
||||
}
|
||||
if (!config.publicBaseUrl.empty()) {
|
||||
auto valid = validateHttpUrl(config.publicBaseUrl, false);
|
||||
if (!valid) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = std::format("invalid public base URL: {}",
|
||||
valid.error()),
|
||||
}};
|
||||
}
|
||||
}
|
||||
while (config.publicBaseUrl.ends_with('/')) {
|
||||
config.publicBaseUrl.pop_back();
|
||||
}
|
||||
|
||||
std::error_code filesystemError;
|
||||
std::filesystem::create_directories(config.databasePath.parent_path(),
|
||||
filesystemError);
|
||||
if (filesystemError) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::storage,
|
||||
.message = std::format(
|
||||
"cannot create URL shortener data directory: {}",
|
||||
filesystemError.message()),
|
||||
}};
|
||||
}
|
||||
|
||||
auto database = Void::Sqlite::Database::open(config.databasePath);
|
||||
if (!database) {
|
||||
return std::unexpected{
|
||||
storageError("cannot open URL database", database.error())};
|
||||
}
|
||||
constexpr std::array migrations{
|
||||
Void::Sqlite::Migration{
|
||||
.version = 1,
|
||||
.sql = R"SQL(
|
||||
CREATE TABLE IF NOT EXISTS short_links (
|
||||
key TEXT PRIMARY KEY,
|
||||
target_url TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER NOT NULL DEFAULT 0,
|
||||
hit_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_hit_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS short_links_target
|
||||
ON short_links(target_url, expires_at, revoked_at);
|
||||
CREATE INDEX IF NOT EXISTS short_links_expiry
|
||||
ON short_links(expires_at, revoked_at);
|
||||
)SQL",
|
||||
},
|
||||
};
|
||||
if (auto migrated = database->migrate(migrations); !migrated) {
|
||||
return std::unexpected{storageError(
|
||||
"cannot initialize URL database", migrated.error())};
|
||||
}
|
||||
return std::make_unique<InternalStore>(
|
||||
ConstructionToken{}, std::move(config), std::move(*database));
|
||||
}
|
||||
|
||||
InternalResult<std::string> InternalStore::generateKey() const
|
||||
{
|
||||
std::string key;
|
||||
key.reserve(config_.slugLength);
|
||||
std::array<unsigned char, 32> bytes{};
|
||||
while (key.size() < config_.slugLength) {
|
||||
if (RAND_bytes(bytes.data(), static_cast<int>(bytes.size())) != 1) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::unavailable,
|
||||
.message = "cryptographic random generator is unavailable",
|
||||
}};
|
||||
}
|
||||
for (const auto byte : bytes) {
|
||||
if (byte >= kLargestUnbiasedByte) {
|
||||
continue;
|
||||
}
|
||||
key.push_back(kAlphabet[byte % kAlphabet.size()]);
|
||||
if (key.size() == config_.slugLength) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
std::string InternalStore::shortUrl(const std::string_view key) const
|
||||
{
|
||||
return std::format("{}/{}", config_.publicBaseUrl, key);
|
||||
}
|
||||
|
||||
InternalResult<InternalLink>
|
||||
InternalStore::shorten(const std::string_view targetUrl,
|
||||
const std::string_view customKey,
|
||||
const std::int64_t expiresAtUnixSeconds)
|
||||
{
|
||||
if (config_.publicBaseUrl.empty()) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::unavailable,
|
||||
.message = "public base URL is not configured",
|
||||
}};
|
||||
}
|
||||
if (auto valid = validateHttpUrl(targetUrl, false); !valid) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = valid.error(),
|
||||
}};
|
||||
}
|
||||
if (targetUrl == config_.publicBaseUrl ||
|
||||
targetUrl.starts_with(config_.publicBaseUrl + "/")) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "refusing to shorten a URL from this shortener",
|
||||
}};
|
||||
}
|
||||
const auto now = nowUnixSeconds();
|
||||
if (expiresAtUnixSeconds < 0 ||
|
||||
(expiresAtUnixSeconds != 0 && expiresAtUnixSeconds <= now)) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "expiration must be zero or a future Unix timestamp",
|
||||
}};
|
||||
}
|
||||
if (!customKey.empty() &&
|
||||
(customKey.size() < kMinimumCustomKeyLength ||
|
||||
customKey.size() > kMaximumKeyLength || !isBase62(customKey))) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "custom key must be 3-64 base62 characters",
|
||||
}};
|
||||
}
|
||||
|
||||
const std::scoped_lock lock{mutex_};
|
||||
auto existing = database_.prepare(
|
||||
"SELECT key, expires_at FROM short_links "
|
||||
"WHERE target_url = ? AND expires_at = ? AND revoked_at = 0 "
|
||||
"AND (expires_at = 0 OR expires_at > ?) "
|
||||
"ORDER BY created_at LIMIT 1");
|
||||
if (!existing) {
|
||||
return std::unexpected{
|
||||
storageError("cannot query existing link", existing.error())};
|
||||
}
|
||||
existing->bind(1, targetUrl).bind(2, expiresAtUnixSeconds).bind(3, now);
|
||||
auto row = existing->step();
|
||||
if (!row) {
|
||||
return std::unexpected{
|
||||
storageError("cannot query existing link", row.error())};
|
||||
}
|
||||
if (*row) {
|
||||
const auto key = existing->column_text(0);
|
||||
if (!customKey.empty() && key != customKey) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::conflict,
|
||||
.message =
|
||||
"the URL already has a different key for this expiry",
|
||||
}};
|
||||
}
|
||||
return InternalLink{
|
||||
.shortUrl = shortUrl(key),
|
||||
.key = key,
|
||||
.targetUrl = std::string{targetUrl},
|
||||
.expiresAtUnixSeconds = existing->column_int(1),
|
||||
};
|
||||
}
|
||||
|
||||
auto insert = database_.prepare(
|
||||
"INSERT INTO short_links"
|
||||
"(key, target_url, expires_at, created_at) VALUES(?, ?, ?, ?)");
|
||||
if (!insert) {
|
||||
return std::unexpected{
|
||||
storageError("cannot prepare link insertion", insert.error())};
|
||||
}
|
||||
|
||||
const auto attempts =
|
||||
customKey.empty() ? kMaximumGenerationAttempts : 1U;
|
||||
for (std::size_t attempt{}; attempt < attempts; ++attempt) {
|
||||
auto keyResult =
|
||||
customKey.empty()
|
||||
? generateKey()
|
||||
: InternalResult<std::string>{std::string{customKey}};
|
||||
if (!keyResult) {
|
||||
return std::unexpected{std::move(keyResult).error()};
|
||||
}
|
||||
insert->reset();
|
||||
insert->clear_bindings();
|
||||
insert->bind(1, *keyResult)
|
||||
.bind(2, targetUrl)
|
||||
.bind(3, expiresAtUnixSeconds)
|
||||
.bind(4, now);
|
||||
if (auto inserted = insert->step(); inserted) {
|
||||
return InternalLink{
|
||||
.shortUrl = shortUrl(*keyResult),
|
||||
.key = std::move(*keyResult),
|
||||
.targetUrl = std::string{targetUrl},
|
||||
.expiresAtUnixSeconds = expiresAtUnixSeconds,
|
||||
};
|
||||
} else if (!customKey.empty()) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::conflict,
|
||||
.message = "custom key is already in use",
|
||||
}};
|
||||
}
|
||||
}
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::unavailable,
|
||||
.message = "could not allocate a unique short-link key",
|
||||
}};
|
||||
}
|
||||
|
||||
InternalResult<InternalLink>
|
||||
InternalStore::resolve(const std::string_view key)
|
||||
{
|
||||
if (key.size() < kMinimumCustomKeyLength ||
|
||||
key.size() > kMaximumKeyLength || !isBase62(key)) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "invalid short-link key",
|
||||
}};
|
||||
}
|
||||
|
||||
const std::scoped_lock lock{mutex_};
|
||||
auto select =
|
||||
database_.prepare("SELECT target_url, expires_at, revoked_at FROM "
|
||||
"short_links WHERE key = ?");
|
||||
if (!select) {
|
||||
return std::unexpected{
|
||||
storageError("cannot query short link", select.error())};
|
||||
}
|
||||
select->bind(1, key);
|
||||
auto row = select->step();
|
||||
if (!row) {
|
||||
return std::unexpected{
|
||||
storageError("cannot query short link", row.error())};
|
||||
}
|
||||
if (!*row || select->column_int(2) != 0) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::notFound,
|
||||
.message = "short link was not found",
|
||||
}};
|
||||
}
|
||||
const auto expiresAt = select->column_int(1);
|
||||
const auto now = nowUnixSeconds();
|
||||
if (!isCurrent(expiresAt, now)) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::expired,
|
||||
.message = "short link has expired",
|
||||
}};
|
||||
}
|
||||
const auto target = select->column_text(0);
|
||||
|
||||
auto update = database_.prepare(
|
||||
"UPDATE short_links SET hit_count = hit_count + 1, last_hit_at = ? "
|
||||
"WHERE key = ? AND revoked_at = 0");
|
||||
if (!update) {
|
||||
return std::unexpected{
|
||||
storageError("cannot prepare hit update", update.error())};
|
||||
}
|
||||
update->bind(1, now).bind(2, key);
|
||||
if (auto updated = update->step(); !updated) {
|
||||
return std::unexpected{
|
||||
storageError("cannot update hit statistics", updated.error())};
|
||||
}
|
||||
return InternalLink{
|
||||
.shortUrl = shortUrl(key),
|
||||
.key = std::string{key},
|
||||
.targetUrl = target,
|
||||
.expiresAtUnixSeconds = expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
InternalResult<void> InternalStore::revoke(const std::string_view key)
|
||||
{
|
||||
if (key.empty() || key.size() > kMaximumKeyLength || !isBase62(key)) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::invalidRequest,
|
||||
.message = "invalid short-link key",
|
||||
}};
|
||||
}
|
||||
const std::scoped_lock lock{mutex_};
|
||||
auto statement =
|
||||
database_.prepare("UPDATE short_links SET revoked_at = ? WHERE key "
|
||||
"= ? AND revoked_at = 0");
|
||||
if (!statement) {
|
||||
return std::unexpected{
|
||||
storageError("cannot prepare revocation", statement.error())};
|
||||
}
|
||||
statement->bind(1, nowUnixSeconds()).bind(2, key);
|
||||
if (auto updated = statement->step(); !updated) {
|
||||
return std::unexpected{
|
||||
storageError("cannot revoke short link", updated.error())};
|
||||
}
|
||||
if (database_.changes() == 0) {
|
||||
return std::unexpected{InternalError{
|
||||
.code = InternalErrorCode::notFound,
|
||||
.message = "short link was not found",
|
||||
}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
InternalResult<InternalStats> InternalStore::stats()
|
||||
{
|
||||
const std::scoped_lock lock{mutex_};
|
||||
auto statement = database_.prepare(
|
||||
"SELECT COUNT(*), "
|
||||
"COALESCE(SUM(CASE WHEN revoked_at = 0 AND "
|
||||
"(expires_at = 0 OR expires_at > ?) THEN 1 ELSE 0 END), 0), "
|
||||
"COALESCE(SUM(CASE WHEN revoked_at = 0 AND expires_at > 0 AND "
|
||||
"expires_at <= ? THEN 1 ELSE 0 END), 0), "
|
||||
"COALESCE(SUM(CASE WHEN revoked_at != 0 THEN 1 ELSE 0 END), 0), "
|
||||
"COALESCE(SUM(hit_count), 0) FROM short_links");
|
||||
if (!statement) {
|
||||
return std::unexpected{
|
||||
storageError("cannot prepare statistics", statement.error())};
|
||||
}
|
||||
const auto now = nowUnixSeconds();
|
||||
statement->bind(1, now).bind(2, now);
|
||||
auto row = statement->step();
|
||||
if (!row) {
|
||||
return std::unexpected{
|
||||
storageError("cannot read statistics", row.error())};
|
||||
}
|
||||
return InternalStats{
|
||||
.total = static_cast<std::uint64_t>(statement->column_int(0)),
|
||||
.active = static_cast<std::uint64_t>(statement->column_int(1)),
|
||||
.expired = static_cast<std::uint64_t>(statement->column_int(2)),
|
||||
.revoked = static_cast<std::uint64_t>(statement->column_int(3)),
|
||||
.hits = static_cast<std::uint64_t>(statement->column_int(4)),
|
||||
};
|
||||
}
|
||||
|
||||
InternalResult<std::uint64_t>
|
||||
InternalStore::cleanup(const bool includeRevoked)
|
||||
{
|
||||
const std::scoped_lock lock{mutex_};
|
||||
const auto sql = includeRevoked
|
||||
? "DELETE FROM short_links WHERE (expires_at > 0 "
|
||||
"AND expires_at <= ?) "
|
||||
"OR revoked_at != 0"
|
||||
: "DELETE FROM short_links WHERE expires_at > 0 "
|
||||
"AND expires_at <= ?";
|
||||
auto statement = database_.prepare(sql);
|
||||
if (!statement) {
|
||||
return std::unexpected{
|
||||
storageError("cannot prepare cleanup", statement.error())};
|
||||
}
|
||||
statement->bind(1, nowUnixSeconds());
|
||||
if (auto cleaned = statement->step(); !cleaned) {
|
||||
return std::unexpected{
|
||||
storageError("cannot clean short links", cleaned.error())};
|
||||
}
|
||||
return static_cast<std::uint64_t>(database_.changes());
|
||||
}
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kPluginId{"url-shortener-internal"};
|
||||
constexpr std::string_view kPluginVersion{"1.0.0"};
|
||||
|
||||
[[nodiscard]] const Void::Json::Value&
|
||||
settingsObject(const Void::Json::Value& root) noexcept
|
||||
{
|
||||
if (const auto* settings = root.child_object("settings")) {
|
||||
return *settings;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
[[nodiscard]] const Void::Json::Value*
|
||||
hostObject(const Void::Json::Value& root) noexcept
|
||||
{
|
||||
if (const auto* host = root.child_object("_host")) {
|
||||
return host;
|
||||
}
|
||||
return root.child_object("host");
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<InternalConfig>
|
||||
parseInternalConfig(const std::string& payload)
|
||||
{
|
||||
auto root = parseConfigObject(payload.c_str());
|
||||
if (!root) {
|
||||
return std::unexpected{std::move(root).error()};
|
||||
}
|
||||
const auto& settings = settingsObject(*root);
|
||||
auto publicBaseUrl = optionalString(settings, "publicBaseUrl");
|
||||
if (!publicBaseUrl) {
|
||||
return std::unexpected{std::move(publicBaseUrl).error()};
|
||||
}
|
||||
if (publicBaseUrl->empty()) {
|
||||
if (const auto* host = hostObject(*root)) {
|
||||
publicBaseUrl = optionalString(*host, "publicBaseUrl");
|
||||
}
|
||||
}
|
||||
if (!publicBaseUrl) {
|
||||
return std::unexpected{std::move(publicBaseUrl).error()};
|
||||
}
|
||||
|
||||
auto allowHttp = optionalBool(settings, "allowHttp", false);
|
||||
if (!allowHttp) {
|
||||
return std::unexpected{std::move(allowHttp).error()};
|
||||
}
|
||||
if (!publicBaseUrl->empty()) {
|
||||
auto valid = validateHttpUrl(*publicBaseUrl, !*allowHttp);
|
||||
if (!valid) {
|
||||
return std::unexpected{std::format(
|
||||
"invalid publicBaseUrl: {}", valid.error())};
|
||||
}
|
||||
}
|
||||
|
||||
const Void::Json::Value* host = hostObject(*root);
|
||||
const auto& stateObject = host != nullptr ? *host : settings;
|
||||
auto stateDirectory = requireString(stateObject, "stateDirectory");
|
||||
if (!stateDirectory && host != nullptr) {
|
||||
stateDirectory = requireString(*host, "stateDir");
|
||||
}
|
||||
if (!stateDirectory) {
|
||||
return std::unexpected{"host-provided stateDirectory is "
|
||||
"required for persistent links"};
|
||||
}
|
||||
const std::filesystem::path statePath{*stateDirectory};
|
||||
if (!statePath.is_absolute()) {
|
||||
return std::unexpected{
|
||||
"host-provided stateDirectory must be absolute"};
|
||||
}
|
||||
|
||||
return InternalConfig{
|
||||
.databasePath = statePath / "plugins" / "data" /
|
||||
std::string{kPluginId} / "links.db",
|
||||
.publicBaseUrl = std::move(*publicBaseUrl),
|
||||
.slugLength = 10,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::ErrorCode
|
||||
toServiceError(const InternalErrorCode code) noexcept
|
||||
{
|
||||
switch (code) {
|
||||
case InternalErrorCode::invalidRequest:
|
||||
return Void::ShortUrl::ErrorCode::invalid_request;
|
||||
case InternalErrorCode::notFound:
|
||||
return Void::ShortUrl::ErrorCode::not_found;
|
||||
case InternalErrorCode::expired:
|
||||
return Void::ShortUrl::ErrorCode::expired;
|
||||
case InternalErrorCode::conflict:
|
||||
return Void::ShortUrl::ErrorCode::conflict;
|
||||
case InternalErrorCode::storage:
|
||||
return Void::ShortUrl::ErrorCode::storage;
|
||||
case InternalErrorCode::unavailable:
|
||||
return Void::ShortUrl::ErrorCode::unavailable;
|
||||
}
|
||||
return Void::ShortUrl::ErrorCode::internal_error;
|
||||
}
|
||||
|
||||
[[nodiscard]] Api::ErrorCode
|
||||
toApiError(const InternalErrorCode code) noexcept
|
||||
{
|
||||
switch (code) {
|
||||
case InternalErrorCode::invalidRequest:
|
||||
return Api::ErrorCode::InvalidArgument;
|
||||
case InternalErrorCode::notFound:
|
||||
case InternalErrorCode::expired:
|
||||
return Api::ErrorCode::NotFound;
|
||||
case InternalErrorCode::conflict:
|
||||
return Api::ErrorCode::AlreadyExists;
|
||||
case InternalErrorCode::storage:
|
||||
return Api::ErrorCode::DatabaseError;
|
||||
case InternalErrorCode::unavailable:
|
||||
return Api::ErrorCode::ServiceUnavailable;
|
||||
}
|
||||
return Api::ErrorCode::UnknownError;
|
||||
}
|
||||
|
||||
[[nodiscard]] Api::Result<Void::Json::Value>
|
||||
parseRpcParams(const Api::ExtensionRpcRequest& request)
|
||||
{
|
||||
const auto payload = request.params.empty() ? "{}" : request.params;
|
||||
auto parsed = Void::Json::parse(payload);
|
||||
if (!parsed || !parsed->is_object()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"RPC parameters must be a JSON object",
|
||||
kPluginId);
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class InternalShortenerPlugin final : public Api::IExtensionPlugin,
|
||||
public Void::ShortUrl::IShortener
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return kPluginId;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view provider_id() const noexcept override
|
||||
{
|
||||
return kPluginId;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::Health health() const override
|
||||
{
|
||||
if (store_ != nullptr) {
|
||||
if (store_->config().publicBaseUrl.empty()) {
|
||||
return {
|
||||
.status = Void::ShortUrl::HealthStatus::degraded,
|
||||
.message =
|
||||
"persistent resolver is ready; shortening "
|
||||
"requires web.publicUrl",
|
||||
};
|
||||
}
|
||||
return {
|
||||
.status = Void::ShortUrl::HealthStatus::healthy,
|
||||
.message = "persistent short-link store is ready",
|
||||
};
|
||||
}
|
||||
return {
|
||||
.status = Void::ShortUrl::HealthStatus::unhealthy,
|
||||
.message = activationError_.empty()
|
||||
? "plugin is not configured"
|
||||
: activationError_,
|
||||
};
|
||||
}
|
||||
|
||||
void applyConfig(const char* config)
|
||||
{
|
||||
configPayload_ = config != nullptr ? config : "";
|
||||
}
|
||||
|
||||
void on_load() override
|
||||
{
|
||||
store_.reset();
|
||||
activationError_.clear();
|
||||
auto config = parseInternalConfig(configPayload_);
|
||||
if (!config) {
|
||||
activationError_ = std::move(config).error();
|
||||
return;
|
||||
}
|
||||
auto store = InternalStore::open(std::move(*config));
|
||||
if (!store) {
|
||||
activationError_ = std::move(store).error().message;
|
||||
return;
|
||||
}
|
||||
store_ = std::move(*store);
|
||||
}
|
||||
|
||||
void on_unload() override { store_.reset(); }
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::ShortenResult
|
||||
shorten(const Void::ShortUrl::ShortenRequest& request) override
|
||||
{
|
||||
if (store_ == nullptr) {
|
||||
return {.error = {
|
||||
.code = Void::ShortUrl::ErrorCode::unavailable,
|
||||
.message = "internal shortener is unavailable",
|
||||
}};
|
||||
}
|
||||
auto result =
|
||||
store_->shorten(request.target_url, request.custom_key,
|
||||
request.expires_at_unix_seconds);
|
||||
if (!result) {
|
||||
auto error = std::move(result).error();
|
||||
return {.error = {
|
||||
.code = toServiceError(error.code),
|
||||
.message = std::move(error.message),
|
||||
}};
|
||||
}
|
||||
return {
|
||||
.short_url = std::move(result->shortUrl),
|
||||
.key = std::move(result->key),
|
||||
.expires_at_unix_seconds = result->expiresAtUnixSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool supports_resolve() const noexcept override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::ResolveResult
|
||||
resolve(const Void::ShortUrl::ResolveRequest& request) override
|
||||
{
|
||||
if (store_ == nullptr) {
|
||||
return {.error = {
|
||||
.code = Void::ShortUrl::ErrorCode::unavailable,
|
||||
.message = "internal shortener is unavailable",
|
||||
}};
|
||||
}
|
||||
auto result = store_->resolve(request.key);
|
||||
if (!result) {
|
||||
auto error = std::move(result).error();
|
||||
return {.error = {
|
||||
.code = toServiceError(error.code),
|
||||
.message = std::move(error.message),
|
||||
}};
|
||||
}
|
||||
return {
|
||||
.target_url = std::move(result->targetUrl),
|
||||
.expires_at_unix_seconds = result->expiresAtUnixSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<Api::ExtensionRpc>
|
||||
rpcMethods() const override
|
||||
{
|
||||
return {
|
||||
{.name = "urlShortener.internal.stats", .adminOnly = true},
|
||||
{.name = "urlShortener.internal.revoke", .adminOnly = true},
|
||||
{.name = "urlShortener.internal.cleanup",
|
||||
.adminOnly = true},
|
||||
};
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
callRpc(const Api::ExtensionRpcRequest& request) override
|
||||
{
|
||||
if (store_ == nullptr) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"internal shortener is unavailable",
|
||||
kPluginId);
|
||||
}
|
||||
if (request.method == "urlShortener.internal.stats") {
|
||||
return statsRpc();
|
||||
}
|
||||
if (request.method == "urlShortener.internal.revoke") {
|
||||
return revokeRpc(request);
|
||||
}
|
||||
if (request.method == "urlShortener.internal.cleanup") {
|
||||
return cleanupRpc(request);
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::NotSupported,
|
||||
"unknown internal shortener RPC method",
|
||||
kPluginId);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<std::string> statsRpc()
|
||||
{
|
||||
auto result = store_->stats();
|
||||
if (!result) {
|
||||
auto error = std::move(result).error();
|
||||
return Api::fail(toApiError(error.code), error.message,
|
||||
kPluginId);
|
||||
}
|
||||
return Void::Json::serialize(Void::Json::object({
|
||||
{"total", static_cast<long long>(result->total)},
|
||||
{"active", static_cast<long long>(result->active)},
|
||||
{"expired", static_cast<long long>(result->expired)},
|
||||
{"revoked", static_cast<long long>(result->revoked)},
|
||||
{"hits", static_cast<long long>(result->hits)},
|
||||
}));
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
revokeRpc(const Api::ExtensionRpcRequest& request)
|
||||
{
|
||||
auto params = parseRpcParams(request);
|
||||
if (!params) {
|
||||
return std::unexpected{std::move(params).error()};
|
||||
}
|
||||
auto key = requireString(*params, "key");
|
||||
if (!key) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
key.error(), kPluginId);
|
||||
}
|
||||
auto result = store_->revoke(*key);
|
||||
if (!result) {
|
||||
auto error = std::move(result).error();
|
||||
return Api::fail(toApiError(error.code), error.message,
|
||||
kPluginId);
|
||||
}
|
||||
return R"({"revoked":true})";
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
cleanupRpc(const Api::ExtensionRpcRequest& request)
|
||||
{
|
||||
auto params = parseRpcParams(request);
|
||||
if (!params) {
|
||||
return std::unexpected{std::move(params).error()};
|
||||
}
|
||||
auto includeRevoked =
|
||||
optionalBool(*params, "includeRevoked", false);
|
||||
if (!includeRevoked) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
includeRevoked.error(), kPluginId);
|
||||
}
|
||||
auto result = store_->cleanup(*includeRevoked);
|
||||
if (!result) {
|
||||
auto error = std::move(result).error();
|
||||
return Api::fail(toApiError(error.code), error.message,
|
||||
kPluginId);
|
||||
}
|
||||
return Void::Json::serialize(Void::Json::object({
|
||||
{"removed", static_cast<long long>(*result)},
|
||||
}));
|
||||
}
|
||||
|
||||
std::string configPayload_;
|
||||
std::string activationError_;
|
||||
std::unique_ptr<InternalStore> store_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
|
||||
extern "C" {
|
||||
|
||||
void* void_plugin_create()
|
||||
{
|
||||
return std::make_unique<
|
||||
Echoion::Plugins::ShortUrl::InternalShortenerPlugin>()
|
||||
.release();
|
||||
}
|
||||
|
||||
void void_plugin_destroy(void* instance)
|
||||
{
|
||||
std::unique_ptr<Echoion::Plugins::ShortUrl::InternalShortenerPlugin>{
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
instance)};
|
||||
}
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return {
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "url-shortener-internal",
|
||||
.plugin_version = "1.0.0",
|
||||
.description = "Persistent Echoion-hosted URL shortener",
|
||||
};
|
||||
}
|
||||
|
||||
void void_plugin_configure(void* instance, const char* config)
|
||||
{
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(instance)
|
||||
->applyConfig(config);
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
const auto health =
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
instance)
|
||||
->health();
|
||||
return health.status == Void::ShortUrl::HealthStatus::healthy ||
|
||||
health.status == Void::ShortUrl::HealthStatus::degraded
|
||||
? 0
|
||||
: 1;
|
||||
}
|
||||
|
||||
Void::Service::IService* void_plugin_service(void* instance)
|
||||
{
|
||||
auto* plugin =
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
instance);
|
||||
return static_cast<Void::Service::IService*>(
|
||||
static_cast<Void::ShortUrl::IShortener*>(plugin));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryDirectory
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryDirectory()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-shortener-internal-" +
|
||||
std::to_string(static_cast<unsigned long long>(random())));
|
||||
std::filesystem::create_directories(path_);
|
||||
}
|
||||
|
||||
~TemporaryDirectory()
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(path_, error);
|
||||
}
|
||||
|
||||
TemporaryDirectory(const TemporaryDirectory&) = delete;
|
||||
TemporaryDirectory& operator=(const TemporaryDirectory&) = delete;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return path_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::filesystem::path path_;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::int64_t nowUnixSeconds()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Plugins::ShortUrl::InternalConfig;
|
||||
using Echoion::Plugins::ShortUrl::InternalErrorCode;
|
||||
using Echoion::Plugins::ShortUrl::InternalStore;
|
||||
|
||||
int failures{};
|
||||
const auto check = [&failures](const bool condition,
|
||||
const std::string_view message) {
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
};
|
||||
|
||||
TemporaryDirectory temporary;
|
||||
const auto databasePath = temporary.path() / "data" / "links.db";
|
||||
const InternalConfig config{
|
||||
.databasePath = databasePath,
|
||||
.publicBaseUrl = "https://short.example/s",
|
||||
};
|
||||
std::string persistentKey;
|
||||
{
|
||||
auto opened = InternalStore::open(config);
|
||||
check(opened.has_value(), "store did not open");
|
||||
if (!opened) {
|
||||
return 1;
|
||||
}
|
||||
auto& store = **opened;
|
||||
|
||||
const auto invalid = store.shorten("file:///etc/passwd");
|
||||
check(!invalid &&
|
||||
invalid.error().code == InternalErrorCode::invalidRequest,
|
||||
"non-HTTP URL was accepted");
|
||||
|
||||
auto first = store.shorten("https://example.com/a?x=1");
|
||||
auto duplicate = store.shorten("https://example.com/a?x=1");
|
||||
check(first.has_value() && duplicate.has_value(),
|
||||
"valid URL could not be shortened");
|
||||
if (first && duplicate) {
|
||||
persistentKey = first->key;
|
||||
check(first->key == duplicate->key,
|
||||
"identical URL did not deduplicate to the same key");
|
||||
check(first->key.size() == 10,
|
||||
"generated key does not contain exactly ten characters");
|
||||
}
|
||||
|
||||
std::vector<std::future<std::string>> concurrent;
|
||||
for (int index{}; index < 8; ++index) {
|
||||
concurrent.push_back(std::async(std::launch::async, [&store] {
|
||||
auto result = store.shorten("https://example.com/concurrent");
|
||||
return result ? result->key : std::string{};
|
||||
}));
|
||||
}
|
||||
std::string concurrentKey;
|
||||
for (auto& future : concurrent) {
|
||||
const auto key = future.get();
|
||||
check(!key.empty(), "concurrent shorten request failed");
|
||||
if (concurrentKey.empty()) {
|
||||
concurrentKey = key;
|
||||
}
|
||||
check(key == concurrentKey,
|
||||
"concurrent identical requests produced different keys");
|
||||
}
|
||||
|
||||
auto custom = store.shorten("https://example.com/custom", "AbC123");
|
||||
check(custom && custom->key == "AbC123", "custom key was not honored");
|
||||
auto conflict = store.shorten("https://example.com/other", "AbC123");
|
||||
check(!conflict && conflict.error().code == InternalErrorCode::conflict,
|
||||
"custom-key collision was not reported as a conflict");
|
||||
|
||||
if (first) {
|
||||
auto resolved = store.resolve(first->key);
|
||||
check(resolved &&
|
||||
resolved->targetUrl == "https://example.com/a?x=1",
|
||||
"short link did not resolve to its target");
|
||||
}
|
||||
auto statistics = store.stats();
|
||||
check(statistics && statistics->hits == 1,
|
||||
"resolve did not update hit statistics");
|
||||
|
||||
if (custom) {
|
||||
auto revoked = store.revoke(custom->key);
|
||||
check(revoked.has_value(), "short link could not be revoked");
|
||||
auto hidden = store.resolve(custom->key);
|
||||
check(!hidden && hidden.error().code == InternalErrorCode::notFound,
|
||||
"revoked short link remained resolvable");
|
||||
}
|
||||
|
||||
auto expiring = store.shorten("https://example.com/expiring", "Expire1",
|
||||
nowUnixSeconds() + 3600);
|
||||
check(expiring.has_value(), "expiring short link could not be created");
|
||||
if (expiring) {
|
||||
auto database = Void::Sqlite::Database::open(databasePath);
|
||||
check(database.has_value(),
|
||||
"test could not reopen SQLite database");
|
||||
if (database) {
|
||||
auto update = database->prepare(
|
||||
"UPDATE short_links SET expires_at = ? WHERE key = ?");
|
||||
check(update.has_value(),
|
||||
"test could not prepare expiry update");
|
||||
if (update) {
|
||||
update->bind(1, nowUnixSeconds() - 1)
|
||||
.bind(2, expiring->key);
|
||||
check(update->step().has_value(),
|
||||
"test could not force link expiration");
|
||||
}
|
||||
}
|
||||
auto expired = store.resolve(expiring->key);
|
||||
check(!expired &&
|
||||
expired.error().code == InternalErrorCode::expired,
|
||||
"expired short link did not report expiry");
|
||||
}
|
||||
|
||||
auto cleaned = store.cleanup(true);
|
||||
check(cleaned && *cleaned >= 2,
|
||||
"cleanup did not remove expired and revoked links");
|
||||
}
|
||||
|
||||
{
|
||||
auto resolverOnly = InternalStore::open({
|
||||
.databasePath = databasePath,
|
||||
.publicBaseUrl = {},
|
||||
});
|
||||
check(resolverOnly.has_value(),
|
||||
"resolver-only store did not open without a public base URL");
|
||||
if (resolverOnly) {
|
||||
auto resolved = (*resolverOnly)->resolve(persistentKey);
|
||||
check(resolved &&
|
||||
resolved->targetUrl == "https://example.com/a?x=1",
|
||||
"resolver-only store could not read an existing link");
|
||||
auto unavailable =
|
||||
(*resolverOnly)->shorten("https://example.com/new");
|
||||
check(!unavailable && unavailable.error().code ==
|
||||
InternalErrorCode::unavailable,
|
||||
"resolver-only store unexpectedly created a short link");
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
auto reopened = InternalStore::open(config);
|
||||
check(reopened.has_value(), "persistent store did not reopen");
|
||||
if (reopened) {
|
||||
auto persisted = (*reopened)->shorten("https://example.com/a?x=1");
|
||||
check(persisted.has_value(), "persisted link could not be loaded");
|
||||
}
|
||||
}
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
Reference in new issue
Block a user