100 lines
2.2 KiB
C++
100 lines
2.2 KiB
C++
#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
|