#pragma once
#include "../../common/hex.h"
#include "../storage/data_source.h"
#include "cdn_fetcher.h"
#include "online_index.h"
#include <vector>
namespace whiteout::storages::casc {
class OnlineDataSource : public DataSource {
public:
OnlineDataSource(CdnFetcher* fetcher, const OnlineIndexTable* archiveIndex,
const OnlineIndexTable* looseIndex,
const std::vector<std::array<u8, 16>>* archiveEKeys)
: m_fetcher(fetcher), m_archiveIndex(archiveIndex), m_looseIndex(looseIndex),
m_archiveEKeys(archiveEKeys) {}
std::vector<u8> fetchBlte(const std::array<u8, 16>& eKey) override {
auto keyHex = storages::common::hexEncode16(eKey);
auto data = m_fetcher->fetch("data", keyHex);
return data.value_or(std::vector<u8>{});
}
std::vector<u8> fetchBlte(u32 archiveIndex, u64 offset, u32 encodedSize) override {
if (!m_archiveEKeys || archiveIndex >= m_archiveEKeys->size())
return {};
auto archiveKeyHex = storages::common::hexEncode16((*m_archiveEKeys)[archiveIndex]);
auto data = m_fetcher->fetchRange(archiveKeyHex, offset, encodedSize);
return data.value_or(std::vector<u8>{});
}
std::optional<IndexLocation> findInIndex(std::span<const u8> eKeyPrefix) const override {
auto entry = m_archiveIndex->find(eKeyPrefix);
if (!entry)
return std::nullopt;
return IndexLocation{
entry->archiveIndex,
entry->archiveOffset,
entry->encodedSize,
false, };
}
using FetchCallback = CdnFetcher::FetchCallback;
void fetchBlteAsync(const std::array<u8, 16>& eKey, FetchCallback callback) {
auto keyHex = storages::common::hexEncode16(eKey);
m_fetcher->fetchAsync("data", keyHex, std::move(callback));
}
void fetchBlteAsync(u32 archiveIndex, u64 offset, u32 encodedSize, FetchCallback callback) {
if (!m_archiveEKeys || archiveIndex >= m_archiveEKeys->size()) {
callback(std::nullopt);
return;
}
auto archiveKeyHex = storages::common::hexEncode16((*m_archiveEKeys)[archiveIndex]);
m_fetcher->fetchRangeAsync(archiveKeyHex, offset, encodedSize, std::move(callback));
}
private:
CdnFetcher* m_fetcher;
const OnlineIndexTable* m_archiveIndex;
[[maybe_unused]] const OnlineIndexTable* m_looseIndex;
const std::vector<std::array<u8, 16>>* m_archiveEKeys;
};
}