#include "durable.hpp" namespace durable { void Histories::attach(int id, Number generation, int topic, int durability, int depth) { const Key key{id, generation}; HistoryEntry entry; entry.topic = topic; entry.durability = durability; entry.depth = depth; entries_.emplace(key, std::move(entry)); } void Histories::release(int id, Number generation) { const Key key{id, generation}; auto found = entries_.find(key); if (found != entries_.end()) { entries_.erase(found); } } void Histories::remember(const Sample &sample) { const Key key{static_cast(sample.writer), sample.generation}; auto found = entries_.find(key); if (found == entries_.end()) { return; } HistoryEntry &entry = found->second; if (entry.durability == 0) { return; } entry.samples.push_back(sample); while (entry.samples.size() > static_cast(entry.depth)) { entry.samples.pop_front(); } } void Histories::resize(int id, Number generation, int depth) { const Key key{id, generation}; auto found = entries_.find(key); if (found == entries_.end()) { return; } HistoryEntry &entry = found->second; entry.depth = depth; while (entry.samples.size() > static_cast(depth)) { entry.samples.pop_front(); } } std::vector Histories::read(int id, Number generation) const { const Key key{id, generation}; const auto found = entries_.find(key); if (found == entries_.end()) { return {}; } const auto &samples = found->second.samples; return std::vector(samples.begin(), samples.end()); } std::vector Histories::replay(int topic) const { std::vector result; for (const auto &item : entries_) { const HistoryEntry &entry = item.second; if (entry.topic != topic || entry.durability == 0) { continue; } for (const Sample &stored : entry.samples) { Sample delivered = stored; delivered.replayed = 1; result.push_back(delivered); } } std::sort(result.begin(), result.end(), [](const Sample &left, const Sample &right) { return left.sequence < right.sequence; }); return result; } Number Histories::count() const { Number total = 0; for (const auto &item : entries_) { total += static_cast(item.second.samples.size()); } return total; } void Histories::reset() { entries_.clear(); } }