Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
2
Indexable
Never
#include <deque>
#include <mutex>
#include <unordered_map>
#include <time.h>

using namespace std;

class RequestTimestamp
{
public:
    int request_rate;
    int window_time;
    deque<int> timestamps;
    mutex m;
    RequestTimestamp()
    {
        this->request_rate = 100;
        this->window_time = 60;
    }

    RequestTimestamp(int request_rate, int window_time)
    {
        this->request_rate = request_rate;
        this->window_time = window_time;
    }

    RequestTimestamp(const RequestTimestamp &) = delete;

    void evict_older_timestamps(int current_timestamp)
    {
        while (this->timestamps.size() && (current_timestamp - this->timestamps.front() > this->window_time))
        {
            this->timestamps.pop_front();
        }
    }
};

class RateLimiter
{
private:
    mutex m;
    unordered_map<int, RequestTimestamp> rate_limiter_map;

public:
    void add_user(int user_id, int request_rate, int window_time)
    {
        lock_guard<mutex> lock(this->m);
        if (rate_limiter_map.find(user_id) != rate_limiter_map.end())
        {
            throw "User already present";
            return;
        }
        this->rate_limiter_map[user_id].request_rate = request_rate;
        this->rate_limiter_map[user_id].window_time = window_time;
    }

    void remove_user(int user_id)
    {
        lock_guard<mutex> lock(this->m);
        if (this->rate_limiter_map.find(user_id) != this->rate_limiter_map.end())
        {
            this->rate_limiter_map.erase(user_id);
        }
    }

    bool should_allow_request(int user_id)
    {
        {
            lock_guard<mutex> lock(this->m);
            if (rate_limiter_map.find(user_id) == rate_limiter_map.end())
            {
                throw "User not found";
                return false;
            }
        }
        lock_guard<mutex> lock(rate_limiter_map[user_id].m);
        int current_time_stamp = time(NULL);
        rate_limiter_map[user_id].evict_older_timestamps(current_time_stamp);
        rate_limiter_map[user_id].timestamps.push_back(current_time_stamp);
        if (rate_limiter_map[user_id].timestamps.size() > rate_limiter_map[user_id].request_rate)
        {
            return false;
        }
        return true;
    }
};

int main()
{
    return 0;
}