commit
9044e4a9d4
5 files changed
+1215
No files matched your search
@@ -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"
|
||||
Reference in new issue
Block a user