我得到了一个函数,它在我之前的问题中提到过:计算用户按一个按钮的频率的函数
void onNewButtonPress(int64_t nanoseconds_timestamp, int32_t user_id);
这个函数将在具有user_id的用户每次单击按钮时调用。 其中nanoseconds_timestamp参数是自纪元以来的时间(以纳秒为单位)。
我的任务是为每个用户做速率限制检查。 每个用户都有自己的点击率限制。 可以使用以下函数检索每个用户的速率限制:
const struct rate_limit* getLimit(uint32_t userId);
getlimit将返回指向结构Rate_limit的指针
struct rate_limit
{
uint32_t max;
uint32_t milliseconds;
};
其中max是用户在毫秒值的间隔内可以进行的最大点击次数。 例如,如果max=400,milliseconds=200,则用户只能在200 ms间隔内进行400次点击。
当用户违反限制时,函数应该使用report function和一个原型进行报告,如下所示。
void report(uint32_t user_id);
当用户突破限制时,你会如何检测。 下面是我的解决方案和评论。 我仍然相信可能会有更聪明和更好的解决办法,并想听听你的意见。
我的实现细节如下
我创建了一个包含每个用户历史信息的结构。
struct UserTrackingInfo
{
/* Limit which is returned when a user clicks for the first time */
const rate_limit* limit;
/* Variable which will get incremented each time a user is making a click */
uint32_t breachCount{0};
/* Timestamp in nanoseconds of when breachPeriod started. Whenever a user clicks for the first time
* this timestamp will be initialized
* Time will be sliced in breach periods whose duration is equal to the max of the rate_limit */
uint64_t breachPeriodStartTs{0};
};
我创建了一个映射,其中键是user_id,值是UserTrackingInfo
std::map<int32_t, struct UserTrackingInfo > tInfo;
这是我建议的NewButtonPress上函数的实现。
void onNewButtonPress(uint64_t& nanoseconds_timestamp, int32_t user_id)
{
auto &tref = tInfo[user_id];
if (tref.breachPeriodStartTs == 0){
/* if a user hasnt clicked before, get the limit for the user and initialize a breach period start time stamp */
tref.limit = getLimit(user_id);
tref.breachPeriodStartTs = nanoseconds_timestamp;
}
else
{
/* Increment how many times used clicked a button */
tref.breachCount++;
/* Get number of ns passed since the time when last period started */
int64_t passed = nanoseconds_timestamp - tref.breachPeriodStartTs;
/* If we reached a limit, report it */
if (passed < (tref.limit->milliseconds * 1000)){
if (tref.breachCount > tref.limit->max){
report(user_id);
}
/* we dont start a new period yet */
}
else{
/* If the limit hasnt been reached yet */
/* User may have pressed after the end of the breach period. Or he didnt make any clicks for the duration of a couple of breach periods */
/* Find number of breach measure periods that may have been missed */
uint64_t num_periods = passed / (tref.limit->milliseconds * 1000);
/* Get duration of the passed periods in nanoseconds */
uint64_t num_periods_ns = num_periods * (tref.limit->milliseconds * 1000);
/* Set the the start time of the current breach measure period */
/* and reset breachCount */
tref.breachPeriodStartTs = tref.breachPeriodStartTs + num_periods_ns;
tref.breachCount = 1;
}
}
}
我会计算用户每天文秒点击多少次(所以没有存储和检查开始的点击周期)。 优点是简单,但缺点是,如果用户在一秒结束时开始点击,那么他说这一秒剩余的点击1000次加上下一秒的点击1000次(即,他可以做例如每1.1秒2000次点击,但它只在第一秒起作用,下一秒将被适当限制)。 所以:
std::map
中记录点击计数,则需要更新为O(logN),但可以使用std::unordered_map
(要求哈希实现)或std::vector
(要求用户ID连续,但实现简单)std::set
(O(logN)insert and delete)或std::unordered_set
(O(1)insert and delete)在您的click处理程序中,您首先检查是否开始了新的一秒(很容易,检查您的时间戳是否在下一秒的时间戳之后)。 如果是,那么重置所有活动用户的计数(这种活动用户跟踪是为了不浪费时间迭代整个std::map
)。 然后清除活动用户。
接下来处理实际的点击。 从映射中获取记录并更新计数,检查是否超过限制,如果超过则进行报告。
请注意,处理下一秒开始是一个有点繁重的操作,并且在处理下一秒之前不会处理用户单击(如果有许多活动用户,可能会导致延迟)。 为了防止这种情况,您应该创建一个处理新秒的新函数,并为新秒的开始创建一些事件,而不是在单击处理程序中处理所有的事情。
struct ClicksTrackingInfo {
uint32_t clicksCount;
uint32_t clicksQuotaPerSec;
};
using UserId_t = int32_t; // user id type
std::set<UserId_t> activeUsers; // users who ever clicked in this second -- O(logN) to update
std::map<UserId_t, ClicksTrackingInfo> clicksPerCurrentSecond; // clicks counts -- O(logN) to update
uint64_t nextSecondTs; // holds nanosecond for beginning of the next second, e.g. if current 15th second would have currentSecondTs == 16*1000*1000*1000
void onNewButtonPress(uint64_t& nanosecondsTimestamp, UserId_t userId)
{
// first find out if a new second started
if (nanosecondsTimestamp > nextSecondTs) {
nextSecondTs = (nanosecondsTimestamp / 1000000000 + 1) * 1000000000; // leave only seconds part of next second
// clear all records from active users of last second
for (auto userId : activeUsers) {
clicksPerCurrentSecond[userId].clicksCount = 0;
}
activeUsers.clear(); // new second, no users yet
}
// now process current click by the user
auto& [clicksCount, clicksLimit] = clicksPerCurrentSecond[userId]; // C++17 syntax
++clicksCount;
if (clicksCount > clicksLimit) {
report(userId);
// return; // possibly deny this click
}
activeUsers.emplace(userId); // remember this user was active in current second
// doClick(); // do the click action
}