75 lines
2.1 KiB
C++
75 lines
2.1 KiB
C++
#pragma once
|
|
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <filesystem>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
// Persistent on-disk cache of downloaded audio files, keyed by track id.
|
|
// Survives restarts (lives under XDG_CACHE_HOME/echoion/tracks); evicts
|
|
// least-recently-used files past maxBytes and entries older than the
|
|
// TTL. Honors advanced.cacheEnabled / cacheMaxSize / cacheTTL.
|
|
class TrackCache
|
|
{
|
|
public:
|
|
|
|
struct Config {
|
|
bool enabled = true;
|
|
uint64_t maxBytes = 1ull << 30; // 1 GiB
|
|
std::chrono::seconds ttl{86400};
|
|
};
|
|
|
|
// dirOverride points tests at a temp dir.
|
|
explicit TrackCache(Config config,
|
|
std::filesystem::path dirOverride = {});
|
|
|
|
// Parse "1GB"/"500MB"/"1024" (bytes) size strings; 0 on garbage.
|
|
[[nodiscard]] static uint64_t
|
|
parseSize(const std::string& text);
|
|
|
|
[[nodiscard]] bool enabled() const { return config_.enabled; }
|
|
|
|
// Cached file path for the track id, when present and fresh.
|
|
// Bumps the file's LRU timestamp.
|
|
[[nodiscard]] std::optional<std::string>
|
|
lookup(const std::string& trackId);
|
|
|
|
// Move a downloaded file into the cache; returns the new path
|
|
// (or the original on failure/disabled). Triggers eviction.
|
|
[[nodiscard]] std::string store(const std::string& trackId,
|
|
const std::string& filePath);
|
|
|
|
// True when the path lives inside the cache directory — such
|
|
// files must NOT be deleted after playback.
|
|
[[nodiscard]] bool owns(const std::string& filePath) const;
|
|
|
|
// Drop expired entries and evict LRU past the size budget.
|
|
void sweep();
|
|
|
|
[[nodiscard]] const std::filesystem::path& directory() const
|
|
{
|
|
return dir_;
|
|
}
|
|
|
|
private:
|
|
|
|
[[nodiscard]] std::filesystem::path
|
|
pathFor(const std::string& trackId,
|
|
const std::string& extension) const;
|
|
[[nodiscard]] static std::string
|
|
sanitize(const std::string& trackId);
|
|
// Eviction pass; caller holds mutex_.
|
|
void sweepLocked();
|
|
|
|
Config config_;
|
|
std::filesystem::path dir_;
|
|
mutable std::mutex mutex_;
|
|
};
|
|
|
|
} // namespace Echoion::Core
|