Files
faumaray 39aff68d8d Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:49:57 +03:00

76 lines
2.5 KiB
C++

#pragma once
#include "TrackSource.hpp"
#include <chrono>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace Echoion::Core
{
// Ordered chain of track sources with per-source failure cooldown and a
// stream-URL cache. Resolution walks the configured order and takes the
// first source that canHandle() the query, is available, and succeeds;
// failures put a source on cooldown (skipped unless it is the last
// candidate) and fall through to the next.
class SourceRouter
{
public:
void setSources(std::vector<std::shared_ptr<ITrackSource>> sources);
void addSource(std::shared_ptr<ITrackSource> source);
// Reorder/enable per config; names not found are ignored, sources
// not named are dropped from the chain.
void setOrder(const std::vector<std::string>& order);
void setFailureCooldown(std::chrono::milliseconds cooldown);
// Hedged getStream: when the first candidate hasn't answered
// within this delay, race the second one (first success wins).
// 0 disables hedging.
void setHedgeDelay(std::chrono::milliseconds delay);
// Text search across the first searching source that succeeds.
[[nodiscard]] Api::Result<Api::SearchResult>
search(std::string_view query);
// URL/id/text -> track metadata.
[[nodiscard]] Api::Result<Api::TrackInfo>
resolve(const std::string& query);
// Track -> playable stream handle (cached).
[[nodiscard]] Api::Result<StreamHandle>
getStream(const Api::TrackInfo& track);
// A cached/served handle failed to open: evict it and demote the
// producing source so the next resolve tries elsewhere.
void invalidate(const std::string& trackId);
private:
struct CachedStream {
StreamHandle handle;
std::chrono::steady_clock::time_point expiry;
};
struct SourceState {
std::shared_ptr<ITrackSource> source;
std::chrono::steady_clock::time_point cooldownUntil{};
};
[[nodiscard]] std::vector<std::shared_ptr<ITrackSource>>
candidatesFor(const std::string& query, bool needSearch);
void reportFailure(const std::shared_ptr<ITrackSource>& source);
mutable std::mutex mutex_;
std::vector<std::shared_ptr<ITrackSource>> allSources_;
std::vector<SourceState> chain_;
std::chrono::milliseconds cooldown_{std::chrono::minutes(5)};
std::chrono::milliseconds hedgeDelay_{std::chrono::milliseconds(300)};
std::unordered_map<std::string, CachedStream> streamCache_;
};
} // namespace Echoion::Core