139 lines
3.3 KiB
C++

#include "quota_tree.h"
#include <map>
#include <utility>
namespace quotatree {
namespace {
bool identifier(const std::string &id)
{
return !id.empty() && id.size() <= 128;
}
struct Prepared {
std::string id;
bool erase = false;
Node node;
};
bool prepare_edits(const std::vector<Edit> &edits,
std::vector<Prepared> &prepared)
{
if (edits.size() > 512) {
return false;
}
for (const Edit &edit : edits) {
if (!identifier(edit.id)) {
return false;
}
Prepared item;
item.id = edit.id;
if (edit.operation == Operation::erase) {
if (edit.parent.has_value() || !edit.cpu_max.empty()) {
return false;
}
item.erase = true;
} else if (edit.operation == Operation::put) {
if (edit.parent.has_value() && !identifier(*edit.parent)) {
return false;
}
item.node.id = edit.id;
item.node.parent = edit.parent;
if (parse_cpu_max(edit.cpu_max, item.node.limit) != Error::none) {
return false;
}
} else {
return false;
}
prepared.push_back(std::move(item));
}
return true;
}
std::vector<NodeInput> as_inputs(const std::map<std::string, Node> &nodes)
{
std::vector<NodeInput> result;
result.reserve(nodes.size());
for (const auto &entry : nodes) {
const Node &node = entry.second;
NodeInput item;
item.id = node.id;
item.parent = node.parent;
const std::string quota = node.limit.unlimited
? "max" : std::to_string(node.limit.quota);
item.cpu_max = quota + " " + std::to_string(node.limit.period);
result.push_back(std::move(item));
}
return result;
}
std::map<std::string, Node> mutable_nodes(const Tree &tree)
{
std::map<std::string, Node> result;
for (const Node &node : tree.nodes) {
result.emplace(node.id, node);
}
return result;
}
}
struct StoreState {
std::uint64_t revision = 0;
Tree tree;
explicit StoreState(const Tree &initial) : tree(initial)
{
}
};
Store::Store(const Tree &initial) : state_(new StoreState(initial))
{
}
Store::~Store() = default;
Store::Store(Store &&) noexcept = default;
Store &Store::operator=(Store &&) noexcept = default;
Error Store::apply(const std::vector<Edit> &edits)
{
std::vector<Prepared> prepared;
if (!prepare_edits(edits, prepared)) {
return Error::invalid;
}
auto working = mutable_nodes(state_->tree);
for (const Prepared &item : prepared) {
if (item.erase) {
working.erase(item.id);
} else {
working[item.id] = item.node;
}
Tree intermediate;
if (compile_tree(as_inputs(working), intermediate) != Error::none) {
return Error::invalid;
}
}
Tree next;
if (compile_tree(as_inputs(working), next) != Error::none) {
return Error::invalid;
}
state_->tree = std::move(next);
++state_->revision;
return Error::none;
}
Query Store::query(const std::string &target) const
{
return evaluate(state_->tree, target);
}
Snapshot Store::snapshot() const
{
Snapshot result;
result.revision = state_->revision;
result.tree = state_->tree;
return result;
}
}