422 lines
13 KiB
C++
422 lines
13 KiB
C++
#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
|