1 parent
639362fbf5
commit
bdd69f0aad
101 files changed
+22691
-531
No files matched your search
@@ -0,0 +1,17 @@
|
||||
set(ECHOION_URL_SHORTENER_INTERNAL_VERSION "1.0.0")
|
||||
set(ECHOION_URL_SHORTENER_EXTERNAL_VERSION "1.0.0")
|
||||
|
||||
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
|
||||
find_package(Boost REQUIRED COMPONENTS url)
|
||||
|
||||
if(NOT TARGET EchoionApiPlugin)
|
||||
message(FATAL_ERROR
|
||||
"First-party plugins require BUILD_API=ON and Echoion::ApiPlugin")
|
||||
endif()
|
||||
if(NOT TARGET Void::ShortUrl)
|
||||
message(FATAL_ERROR
|
||||
"First-party URL shorteners require a VoidLibrary revision with Void::ShortUrl")
|
||||
endif()
|
||||
|
||||
add_subdirectory(url-shortener-internal)
|
||||
add_subdirectory(url-shortener-external)
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
template <typename T> using Result = std::expected<T, std::string>;
|
||||
|
||||
[[nodiscard]] Result<Void::Json::Value>
|
||||
parseConfigObject(const char* config);
|
||||
[[nodiscard]] Result<std::string>
|
||||
requireString(const Void::Json::Value& object, std::string_view key);
|
||||
[[nodiscard]] Result<std::string>
|
||||
optionalString(const Void::Json::Value& object, std::string_view key,
|
||||
std::string_view fallback = {});
|
||||
[[nodiscard]] Result<bool> optionalBool(const Void::Json::Value& object,
|
||||
std::string_view key,
|
||||
bool fallback);
|
||||
[[nodiscard]] Result<std::int64_t>
|
||||
optionalInteger(const Void::Json::Value& object, std::string_view key,
|
||||
std::int64_t fallback, std::int64_t minimum,
|
||||
std::int64_t maximum);
|
||||
|
||||
[[nodiscard]] bool
|
||||
containsControlCharacters(std::string_view value) noexcept;
|
||||
[[nodiscard]] std::string trimAscii(std::string_view value);
|
||||
[[nodiscard]] bool isHeaderName(std::string_view value) noexcept;
|
||||
[[nodiscard]] bool isBase62(std::string_view value) noexcept;
|
||||
|
||||
/// Validate an absolute HTTP(S) URL without making a network request.
|
||||
[[nodiscard]] Result<void>
|
||||
validateHttpUrl(std::string_view value, bool requireHttps,
|
||||
std::size_t maximumLength = 8192);
|
||||
|
||||
/// Reject address literals and well-known hostnames that are not publicly
|
||||
/// routable. DNS-backed validation lives in the external provider because
|
||||
/// only it opens outbound connections.
|
||||
[[nodiscard]] bool isObviouslyPrivateHost(std::string_view host) noexcept;
|
||||
|
||||
/// Expand ${url} and ${env:NAME}. Environment variables are read without
|
||||
/// being copied into diagnostics; a missing variable reports only its name.
|
||||
[[nodiscard]] Result<std::string>
|
||||
expandTemplate(std::string_view input, std::string_view url,
|
||||
bool encodeSubstitutions = false);
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
@@ -0,0 +1,319 @@
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
|
||||
#include <Void/Net/Url.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept
|
||||
{
|
||||
if (name.empty() ||
|
||||
!(std::isalpha(static_cast<unsigned char>(name.front())) != 0 ||
|
||||
name.front() == '_')) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(
|
||||
name.substr(1), [](const char character) {
|
||||
const auto value = static_cast<unsigned char>(character);
|
||||
return std::isalnum(value) != 0 || character == '_';
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
isPrivateV4(const boost::asio::ip::address_v4 address) noexcept
|
||||
{
|
||||
const auto value = address.to_uint();
|
||||
const auto first = static_cast<unsigned>((value >> 24U) & 0xffU);
|
||||
const auto second = static_cast<unsigned>((value >> 16U) & 0xffU);
|
||||
const auto third = static_cast<unsigned>((value >> 8U) & 0xffU);
|
||||
|
||||
return first == 0U || first == 10U || first == 127U ||
|
||||
(first == 100U && second >= 64U && second <= 127U) ||
|
||||
(first == 169U && second == 254U) ||
|
||||
(first == 172U && second >= 16U && second <= 31U) ||
|
||||
(first == 192U && second == 168U) ||
|
||||
(first == 192U && second == 0U && third <= 2U) ||
|
||||
(first == 198U && (second == 18U || second == 19U)) ||
|
||||
(first == 198U && second == 51U && third == 100U) ||
|
||||
(first == 203U && second == 0U && third == 113U) ||
|
||||
first >= 224U;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
isPrivateV6(const boost::asio::ip::address_v6 address) noexcept
|
||||
{
|
||||
const auto bytes = address.to_bytes();
|
||||
if (address.is_unspecified() || address.is_loopback() ||
|
||||
address.is_link_local() || address.is_multicast()) {
|
||||
return true;
|
||||
}
|
||||
if (address.is_v4_mapped()) {
|
||||
const boost::asio::ip::address_v4::bytes_type mapped{
|
||||
bytes[12], bytes[13], bytes[14], bytes[15]};
|
||||
return isPrivateV4(boost::asio::ip::address_v4{mapped});
|
||||
}
|
||||
|
||||
const bool uniqueLocal = (bytes[0] & 0xfeU) == 0xfcU;
|
||||
const bool documentation = bytes[0] == 0x20U && bytes[1] == 0x01U &&
|
||||
bytes[2] == 0x0dU && bytes[3] == 0xb8U;
|
||||
return uniqueLocal || documentation;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Result<Void::Json::Value> parseConfigObject(const char* config)
|
||||
{
|
||||
if (config == nullptr || *config == '\0') {
|
||||
return std::unexpected{"plugin configuration is required"};
|
||||
}
|
||||
auto parsed = Void::Json::parse(config);
|
||||
if (!parsed) {
|
||||
return std::unexpected{
|
||||
std::format("invalid plugin configuration at {}:{}: {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message)};
|
||||
}
|
||||
if (!parsed->is_object()) {
|
||||
return std::unexpected{
|
||||
"plugin configuration must be a JSON object"};
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
Result<std::string> requireString(const Void::Json::Value& object,
|
||||
const std::string_view key)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr || !value->is_string() ||
|
||||
value->as_string().empty()) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be a non-empty string", key)};
|
||||
}
|
||||
return value->as_string();
|
||||
}
|
||||
|
||||
Result<std::string> optionalString(const Void::Json::Value& object,
|
||||
const std::string_view key,
|
||||
const std::string_view fallback)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return std::string{fallback};
|
||||
}
|
||||
if (!value->is_string()) {
|
||||
return std::unexpected{
|
||||
std::format("configuration field '{}' must be a string", key)};
|
||||
}
|
||||
return value->as_string();
|
||||
}
|
||||
|
||||
Result<bool> optionalBool(const Void::Json::Value& object,
|
||||
const std::string_view key, const bool fallback)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return fallback;
|
||||
}
|
||||
if (!value->is_bool()) {
|
||||
return std::unexpected{
|
||||
std::format("configuration field '{}' must be a boolean", key)};
|
||||
}
|
||||
return value->as_bool();
|
||||
}
|
||||
|
||||
Result<std::int64_t> optionalInteger(const Void::Json::Value& object,
|
||||
const std::string_view key,
|
||||
const std::int64_t fallback,
|
||||
const std::int64_t minimum,
|
||||
const std::int64_t maximum)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return fallback;
|
||||
}
|
||||
if (!value->is_number()) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be an integer", key)};
|
||||
}
|
||||
const auto number = value->as_number();
|
||||
if (!std::isfinite(number) || std::floor(number) != number ||
|
||||
number < static_cast<double>(minimum) ||
|
||||
number > static_cast<double>(maximum)) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be between {} and {}", key,
|
||||
minimum, maximum)};
|
||||
}
|
||||
return static_cast<std::int64_t>(number);
|
||||
}
|
||||
|
||||
bool containsControlCharacters(const std::string_view value) noexcept
|
||||
{
|
||||
return std::ranges::any_of(value, [](const char character) {
|
||||
const auto byte = static_cast<unsigned char>(character);
|
||||
return byte < 0x20U || byte == 0x7fU;
|
||||
});
|
||||
}
|
||||
|
||||
std::string trimAscii(const std::string_view value)
|
||||
{
|
||||
const auto isSpace = [](const char character) {
|
||||
return std::isspace(static_cast<unsigned char>(character)) != 0;
|
||||
};
|
||||
const auto first = std::ranges::find_if_not(value, isSpace);
|
||||
const auto last =
|
||||
std::find_if_not(value.rbegin(), value.rend(), isSpace).base();
|
||||
if (first >= last) {
|
||||
return {};
|
||||
}
|
||||
return {first, last};
|
||||
}
|
||||
|
||||
bool isHeaderName(const std::string_view value) noexcept
|
||||
{
|
||||
if (value.empty()) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view separators{"()<>@,;:\\\"/[]?={} \t"};
|
||||
return std::ranges::all_of(value, [separators](const char character) {
|
||||
const auto byte = static_cast<unsigned char>(character);
|
||||
return byte > 0x20U && byte < 0x7fU &&
|
||||
separators.find(character) == std::string_view::npos;
|
||||
});
|
||||
}
|
||||
|
||||
bool isBase62(const std::string_view value) noexcept
|
||||
{
|
||||
return !value.empty() && std::ranges::all_of(value, [](const char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= 'a' && c <= 'z');
|
||||
});
|
||||
}
|
||||
|
||||
Result<void> validateHttpUrl(const std::string_view value,
|
||||
const bool requireHttps,
|
||||
const std::size_t maximumLength)
|
||||
{
|
||||
if (value.empty() || value.size() > maximumLength ||
|
||||
containsControlCharacters(value) ||
|
||||
std::ranges::any_of(value, [](const char c) {
|
||||
return std::isspace(static_cast<unsigned char>(c)) != 0;
|
||||
})) {
|
||||
return std::unexpected{
|
||||
"URL is empty, too long, or contains whitespace"};
|
||||
}
|
||||
const auto parsed = Void::Net::Url::parse(value);
|
||||
if (!parsed || parsed->host.empty() ||
|
||||
(parsed->scheme != "http" && parsed->scheme != "https")) {
|
||||
return std::unexpected{"URL must be an absolute HTTP(S) URL"};
|
||||
}
|
||||
if (requireHttps && parsed->scheme != "https") {
|
||||
return std::unexpected{"URL must use HTTPS"};
|
||||
}
|
||||
|
||||
const auto schemeEnd = value.find("://");
|
||||
const auto authorityEnd = value.find_first_of("/?#", schemeEnd + 3U);
|
||||
const auto authority =
|
||||
value.substr(schemeEnd + 3U, authorityEnd == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: authorityEnd - schemeEnd - 3U);
|
||||
if (authority.find('@') != std::string_view::npos) {
|
||||
return std::unexpected{"URL userinfo is not allowed"};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool isObviouslyPrivateHost(const std::string_view host) noexcept
|
||||
{
|
||||
std::string lower;
|
||||
lower.reserve(host.size());
|
||||
std::ranges::transform(
|
||||
host, std::back_inserter(lower), [](const char c) {
|
||||
return static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
});
|
||||
while (!lower.empty() && lower.back() == '.') {
|
||||
lower.pop_back();
|
||||
}
|
||||
if (lower == "localhost" || lower.ends_with(".localhost") ||
|
||||
lower.ends_with(".local") || lower.ends_with(".internal")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boost::system::error_code error;
|
||||
const auto address = boost::asio::ip::make_address(lower, error);
|
||||
if (error) {
|
||||
return false;
|
||||
}
|
||||
return address.is_v4() ? isPrivateV4(address.to_v4())
|
||||
: isPrivateV6(address.to_v6());
|
||||
}
|
||||
|
||||
Result<std::string> expandTemplate(const std::string_view input,
|
||||
const std::string_view url,
|
||||
const bool encodeSubstitutions)
|
||||
{
|
||||
const auto appendReplacement =
|
||||
[encodeSubstitutions](std::string& destination,
|
||||
const std::string_view replacement) {
|
||||
if (encodeSubstitutions) {
|
||||
destination.append(
|
||||
Void::Encoding::Url::query_encode(replacement));
|
||||
} else {
|
||||
destination.append(replacement);
|
||||
}
|
||||
};
|
||||
std::string output;
|
||||
output.reserve(input.size() + url.size());
|
||||
std::size_t position{};
|
||||
while (position < input.size()) {
|
||||
const auto marker = input.find("${", position);
|
||||
if (marker == std::string_view::npos) {
|
||||
output.append(input.substr(position));
|
||||
break;
|
||||
}
|
||||
output.append(input.substr(position, marker - position));
|
||||
const auto end = input.find('}', marker + 2U);
|
||||
if (end == std::string_view::npos) {
|
||||
return std::unexpected{"unterminated template placeholder"};
|
||||
}
|
||||
const auto token = input.substr(marker + 2U, end - marker - 2U);
|
||||
if (token == "url") {
|
||||
appendReplacement(output, url);
|
||||
} else if (token.starts_with("env:")) {
|
||||
const auto name = token.substr(4U);
|
||||
if (!validEnvironmentName(name)) {
|
||||
return std::unexpected{
|
||||
"invalid environment placeholder name"};
|
||||
}
|
||||
const std::string ownedName{name};
|
||||
const char* value = std::getenv(ownedName.c_str());
|
||||
if (value == nullptr) {
|
||||
return std::unexpected{std::format(
|
||||
"required environment variable '{}' is not set", name)};
|
||||
}
|
||||
if (containsControlCharacters(value)) {
|
||||
return std::unexpected{std::format(
|
||||
"environment variable '{}' contains control characters",
|
||||
name)};
|
||||
}
|
||||
appendReplacement(output, value);
|
||||
} else {
|
||||
return std::unexpected{std::format(
|
||||
"unsupported template placeholder '${{{}}}'", token)};
|
||||
}
|
||||
position = end + 1U;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
@@ -0,0 +1,60 @@
|
||||
set(_external_sources
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/src/Common.cpp"
|
||||
src/ExternalShortener.cpp)
|
||||
|
||||
add_library(EchoionUrlShortenerExternalPlugin MODULE
|
||||
${_external_sources}
|
||||
src/Plugin.cpp)
|
||||
target_include_directories(EchoionUrlShortenerExternalPlugin PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/include")
|
||||
target_compile_features(EchoionUrlShortenerExternalPlugin PRIVATE cxx_std_26)
|
||||
target_link_libraries(EchoionUrlShortenerExternalPlugin PRIVATE
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiConfig
|
||||
Void::ShortUrl
|
||||
Void::Data
|
||||
Void::Net
|
||||
Void::Text
|
||||
Boost::url
|
||||
Threads::Threads)
|
||||
set_target_properties(EchoionUrlShortenerExternalPlugin PROPERTIES
|
||||
PREFIX ""
|
||||
OUTPUT_NAME "url-shortener-external"
|
||||
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(EchoionUrlShortenerExternalPlugin PRIVATE /W4 /WX-)
|
||||
else()
|
||||
target_compile_options(EchoionUrlShortenerExternalPlugin PRIVATE
|
||||
-Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
install(TARGETS EchoionUrlShortenerExternalPlugin
|
||||
LIBRARY DESTINATION
|
||||
"${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}"
|
||||
COMPONENT Runtime
|
||||
RUNTIME DESTINATION
|
||||
"${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_url_shortener_external_tests
|
||||
${_external_sources}
|
||||
tests/ExternalShortenerTests.cpp)
|
||||
target_include_directories(echoion_url_shortener_external_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../common/include")
|
||||
target_compile_features(echoion_url_shortener_external_tests PRIVATE
|
||||
cxx_std_26)
|
||||
target_link_libraries(echoion_url_shortener_external_tests PRIVATE
|
||||
Void::ShortUrl Void::Data Void::Net Void::Text Boost::url Threads::Threads)
|
||||
add_test(NAME echoion_url_shortener_external_tests
|
||||
COMMAND echoion_url_shortener_external_tests)
|
||||
set_tests_properties(echoion_url_shortener_external_tests PROPERTIES
|
||||
TIMEOUT 20)
|
||||
endif()
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
enum class ExternalEncoding { query, json, form };
|
||||
enum class ExternalResponseKind { plain, header, jsonPointer };
|
||||
|
||||
struct ExternalFieldTemplate {
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct ExternalHeaderTemplate {
|
||||
std::string name;
|
||||
std::string value;
|
||||
bool sensitive{};
|
||||
};
|
||||
|
||||
struct ExternalResponseConfig {
|
||||
ExternalResponseKind kind{ExternalResponseKind::jsonPointer};
|
||||
std::string selector{"/shortUrl"};
|
||||
};
|
||||
|
||||
struct ExternalConfig {
|
||||
std::string endpoint;
|
||||
Void::Net::Method method{Void::Net::Method::Post};
|
||||
ExternalEncoding encoding{ExternalEncoding::json};
|
||||
std::vector<ExternalFieldTemplate> fields;
|
||||
std::vector<ExternalHeaderTemplate> headers;
|
||||
ExternalResponseConfig response;
|
||||
bool allowHttp{};
|
||||
bool allowPrivateHosts{};
|
||||
bool allowPrivateTargets{};
|
||||
bool allowCrossHostRedirects{};
|
||||
int maxRedirects{};
|
||||
std::uint32_t timeoutSeconds{3};
|
||||
std::size_t maximumResponseBytes{64U * 1024U};
|
||||
std::size_t cacheCapacity{512};
|
||||
std::uint32_t cacheTtlSeconds{3600};
|
||||
std::size_t maximumConcurrency{4};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<ExternalConfig, std::string>
|
||||
parseExternalConfig(std::string_view payload);
|
||||
|
||||
class ExternalShortener
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static std::expected<
|
||||
std::unique_ptr<ExternalShortener>, std::string>
|
||||
create(ExternalConfig config);
|
||||
|
||||
~ExternalShortener();
|
||||
ExternalShortener(const ExternalShortener&) = delete;
|
||||
ExternalShortener& operator=(const ExternalShortener&) = delete;
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::Health health() const;
|
||||
[[nodiscard]] Void::ShortUrl::ShortenResult
|
||||
shorten(const Void::ShortUrl::ShortenRequest& request);
|
||||
|
||||
/// Pure request/extraction seams used by focused tests and provider
|
||||
/// configuration diagnostics. They never perform network I/O.
|
||||
[[nodiscard]] std::expected<Void::Net::Request, std::string>
|
||||
previewRequest(std::string_view targetUrl) const;
|
||||
[[nodiscard]] std::expected<std::string, std::string>
|
||||
previewExtract(const Void::Net::Response& response) const;
|
||||
|
||||
private:
|
||||
|
||||
struct ConstructionToken {
|
||||
explicit ConstructionToken() = default;
|
||||
};
|
||||
struct Impl;
|
||||
|
||||
public:
|
||||
|
||||
ExternalShortener(ConstructionToken, ExternalConfig config);
|
||||
|
||||
private:
|
||||
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
#include <echoion/plugins/short_url/ExternalShortener.hpp>
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kPluginId{"url-shortener-external"};
|
||||
}
|
||||
|
||||
class ExternalShortenerPlugin 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;
|
||||
}
|
||||
|
||||
void applyConfig(const char* config)
|
||||
{
|
||||
configPayload_ = config != nullptr ? config : "";
|
||||
}
|
||||
|
||||
void on_load() override
|
||||
{
|
||||
shortener_.reset();
|
||||
activationError_.clear();
|
||||
auto config = parseExternalConfig(configPayload_);
|
||||
if (!config) {
|
||||
activationError_ = std::move(config).error();
|
||||
return;
|
||||
}
|
||||
auto shortener = ExternalShortener::create(std::move(*config));
|
||||
if (!shortener) {
|
||||
activationError_ = std::move(shortener).error();
|
||||
return;
|
||||
}
|
||||
shortener_ = std::move(*shortener);
|
||||
}
|
||||
|
||||
void on_unload() override { shortener_.reset(); }
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::Health health() const override
|
||||
{
|
||||
if (shortener_ != nullptr) {
|
||||
return shortener_->health();
|
||||
}
|
||||
return {
|
||||
.status = Void::ShortUrl::HealthStatus::unhealthy,
|
||||
.message = activationError_.empty()
|
||||
? "plugin is not configured"
|
||||
: activationError_,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::ShortenResult
|
||||
shorten(const Void::ShortUrl::ShortenRequest& request) override
|
||||
{
|
||||
if (shortener_ == nullptr) {
|
||||
return {.error = {
|
||||
.code = Void::ShortUrl::ErrorCode::unavailable,
|
||||
.message = "external shortener is unavailable",
|
||||
}};
|
||||
}
|
||||
return shortener_->shorten(request);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string configPayload_;
|
||||
std::string activationError_;
|
||||
std::unique_ptr<ExternalShortener> shortener_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
|
||||
extern "C" {
|
||||
|
||||
void* void_plugin_create()
|
||||
{
|
||||
return std::make_unique<
|
||||
Echoion::Plugins::ShortUrl::ExternalShortenerPlugin>()
|
||||
.release();
|
||||
}
|
||||
|
||||
void void_plugin_destroy(void* instance)
|
||||
{
|
||||
std::unique_ptr<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin>{
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
instance)};
|
||||
}
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return {
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "url-shortener-external",
|
||||
.plugin_version = "1.0.0",
|
||||
.description = "Configurable external URL-shortening adapter",
|
||||
};
|
||||
}
|
||||
|
||||
void void_plugin_configure(void* instance, const char* config)
|
||||
{
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(instance)
|
||||
->applyConfig(config);
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
const auto health =
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
instance)
|
||||
->health();
|
||||
return health.status == Void::ShortUrl::HealthStatus::healthy ? 0 : 1;
|
||||
}
|
||||
|
||||
Void::Service::IService* void_plugin_service(void* instance)
|
||||
{
|
||||
auto* plugin =
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
instance);
|
||||
return static_cast<Void::Service::IService*>(
|
||||
static_cast<Void::ShortUrl::IShortener*>(plugin));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,168 @@
|
||||
#include <echoion/plugins/short_url/ExternalShortener.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
class EnvironmentVariable
|
||||
{
|
||||
public:
|
||||
|
||||
EnvironmentVariable(std::string name, std::string value)
|
||||
: name_(std::move(name))
|
||||
{
|
||||
setenv(name_.c_str(), value.c_str(), 1);
|
||||
}
|
||||
|
||||
~EnvironmentVariable() { unsetenv(name_.c_str()); }
|
||||
|
||||
EnvironmentVariable(const EnvironmentVariable&) = delete;
|
||||
EnvironmentVariable& operator=(const EnvironmentVariable&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
std::string name_;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Plugins::ShortUrl::ExternalShortener;
|
||||
using Echoion::Plugins::ShortUrl::parseExternalConfig;
|
||||
|
||||
int failures{};
|
||||
const auto check = [&failures](const bool condition,
|
||||
const std::string_view message) {
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
};
|
||||
|
||||
EnvironmentVariable token{"ECHOION_SHORTENER_TEST_TOKEN", "test secret"};
|
||||
const auto jsonConfig = R"JSON({
|
||||
"endpoint":"https://short.example/api",
|
||||
"method":"POST",
|
||||
"encoding":"json",
|
||||
"fields":{"longUrl":"${url}","tenant":"${env:ECHOION_SHORTENER_TEST_TOKEN}"},
|
||||
"headers":{"Authorization":"Bearer ${env:ECHOION_SHORTENER_TEST_TOKEN}"},
|
||||
"response":{"type":"json","pointer":"/data/short"}
|
||||
})JSON";
|
||||
auto parsed = parseExternalConfig(jsonConfig);
|
||||
check(parsed.has_value(), "JSON provider configuration was rejected");
|
||||
if (!parsed) {
|
||||
return 1;
|
||||
}
|
||||
auto shortener = ExternalShortener::create(std::move(*parsed));
|
||||
check(shortener.has_value(), "external shortener could not be created");
|
||||
if (!shortener) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto request =
|
||||
(*shortener)->previewRequest("https://example.com/a?x=1&y=2");
|
||||
check(request.has_value() && request->body.has_value(),
|
||||
"JSON request was not constructed");
|
||||
if (request && request->body) {
|
||||
auto body = Void::Json::parse(*request->body);
|
||||
check(body &&
|
||||
body->get_str("longUrl") == "https://example.com/a?x=1&y=2",
|
||||
"target URL was not safely represented in JSON");
|
||||
check(body && body->get_str("tenant") == "test secret",
|
||||
"environment template was not expanded in a field");
|
||||
check(request->headers.size() == 2,
|
||||
"configured and automatic Content-Type headers were not emitted");
|
||||
}
|
||||
|
||||
Void::Net::Response jsonResponse{
|
||||
.status = 200,
|
||||
.body = R"({"data":{"short":"https://sho.rt/Ab1"}})",
|
||||
};
|
||||
auto extracted = (*shortener)->previewExtract(jsonResponse);
|
||||
check(extracted && *extracted == "https://sho.rt/Ab1",
|
||||
"JSON Pointer response extraction failed");
|
||||
|
||||
const auto formConfig = R"JSON({
|
||||
"endpoint":"https://short.example/api",
|
||||
"method":"PATCH",
|
||||
"encoding":"form",
|
||||
"fields":{"long url":"${url}"},
|
||||
"response":{"type":"plain"}
|
||||
})JSON";
|
||||
auto form = parseExternalConfig(formConfig);
|
||||
check(form.has_value(), "form provider configuration was rejected");
|
||||
if (form) {
|
||||
auto formShortener = ExternalShortener::create(std::move(*form));
|
||||
auto formRequest =
|
||||
formShortener
|
||||
? (*formShortener)
|
||||
->previewRequest("https://example.com/a?x=1&y=2")
|
||||
: std::expected<Void::Net::Request, std::string>{
|
||||
std::unexpected{"create failed"}};
|
||||
check(formRequest &&
|
||||
formRequest->body ==
|
||||
"long+url=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26y%3D2",
|
||||
"form request was not percent encoded");
|
||||
}
|
||||
|
||||
const auto queryConfig = R"JSON({
|
||||
"endpoint":"https://short.example/api?token=${env:ECHOION_SHORTENER_TEST_TOKEN}",
|
||||
"method":"GET",
|
||||
"encoding":"query",
|
||||
"fields":{"url":"${url}"},
|
||||
"response":{"type":"header","header":"Location"}
|
||||
})JSON";
|
||||
auto query = parseExternalConfig(queryConfig);
|
||||
check(query.has_value(), "query provider configuration was rejected");
|
||||
if (query) {
|
||||
auto queryShortener = ExternalShortener::create(std::move(*query));
|
||||
auto queryRequest =
|
||||
queryShortener
|
||||
? (*queryShortener)->previewRequest("https://example.com/a?x=1")
|
||||
: std::expected<Void::Net::Request, std::string>{
|
||||
std::unexpected{"create failed"}};
|
||||
check(queryRequest &&
|
||||
queryRequest->url.find("token=test+secret") !=
|
||||
std::string::npos &&
|
||||
queryRequest->url.find("url=https%3A%2F%2Fexample.com") !=
|
||||
std::string::npos,
|
||||
"query and environment values were not percent encoded");
|
||||
if (queryShortener) {
|
||||
Void::Net::Response headerResponse{
|
||||
.status = 201,
|
||||
.headers = {{.name = "Location", .value = "https://sho.rt/Q1"}},
|
||||
};
|
||||
auto header = (*queryShortener)->previewExtract(headerResponse);
|
||||
check(header && *header == "https://sho.rt/Q1",
|
||||
"response-header extraction failed");
|
||||
}
|
||||
}
|
||||
|
||||
check(!parseExternalConfig(R"({"endpoint":"http://short.example/api"})"),
|
||||
"plain HTTP endpoint was accepted without opt-in");
|
||||
check(
|
||||
!parseExternalConfig(
|
||||
R"({"endpoint":"https://127.0.0.1/api","fields":{"url":"${url}"}})"),
|
||||
"private endpoint was accepted without opt-in");
|
||||
check(
|
||||
!parseExternalConfig(
|
||||
R"({"endpoint":"https://short.example/api","headers":{"Authorization":"${env:ECHOION_MISSING_SHORTENER_TOKEN}"}})"),
|
||||
"missing environment secret did not reject configuration");
|
||||
|
||||
const Void::ShortUrl::ShortenRequest unsupportedRequest{
|
||||
.target_url = "https://example.com/a",
|
||||
.custom_key = "wanted",
|
||||
};
|
||||
const auto unsupported = (*shortener)->shorten(unsupportedRequest);
|
||||
check(!unsupported &&
|
||||
unsupported.error.code == Void::ShortUrl::ErrorCode::unsupported,
|
||||
"external adapter silently ignored a custom key");
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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