Skip to content

Commit

Permalink
[api] Change the current value of a Quota accordingly when its initia…
Browse files Browse the repository at this point in the history
…l value is changed
  • Loading branch information
pajama-coder committed May 7, 2024
1 parent a7e6dcc commit dd74166
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/api/algo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -380,14 +380,31 @@ auto Quota::Counter::get(const std::string &key, double initial_value, double pr
auto i = m_counter_map.find(key);
if (i != m_counter_map.end()) {
auto p = i->second;
p->m_initial_value = initial_value;
p->m_produce_value = produce_value;
p->m_produce_cycle = produce_cycle;
p->init(initial_value, produce_value, produce_cycle);
return p;
}
return new Counter(key, initial_value, produce_value, produce_cycle);
}

void Quota::Counter::init(double initial_value, double produce_value, double produce_cycle) {
auto old_initial_value = m_initial_value.load();
m_initial_value = initial_value;
m_produce_value = produce_value;
m_produce_cycle = produce_cycle;
auto delta = initial_value - old_initial_value;
auto old = m_current_value.load();
for (;;) {
if (delta > 0) {
if (!m_current_value.compare_exchange_weak(old, old + delta)) continue;
on_produce();
} else if (delta < 0) {
if (!m_current_value.compare_exchange_weak(old, std::min(old, initial_value))) continue;
schedule_producing();
}
break;
}
}

void Quota::Counter::produce(double value) {
if (value <= 0) return;
auto old = m_current_value.load();
Expand Down
1 change: 1 addition & 0 deletions src/api/algo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class Quota : public pjs::ObjectTemplate<Quota> {
public:
static auto get(const std::string &key, double initial_value, double produce_value, double produce_cycle) -> Counter*;

void init(double initial_value, double produce_value, double produce_cycle);
auto initial() const -> double { return m_initial_value; }
auto current() const -> double { return m_current_value.load(); }
void produce(double value);
Expand Down

0 comments on commit dd74166

Please sign in to comment.