Fix calculating available tickets.

Help prevent overflow when there's long periods between calls
This commit is contained in:
Nils O. Selåsdal
2013-10-10 01:06:49 +02:00
parent 212fecae08
commit 9ca4a354ee
+9 -6
View File
@@ -1,6 +1,6 @@
#include "ucore/rate_limit.h"
#define SCALE_FACTOR 1000
#define SCALE_FACTOR 100
void uc_ratelimit_init(struct RateLimit *r, long tickets, long period, long current_ts)
@@ -28,22 +28,25 @@ int uc_ratelimit_allow(struct RateLimit *r, long current_ts)
//Find elapsed time
diff_period = current_ts - r->last_ts;
if (diff_period > r->period + 1) {
//help prevent overflow when calculating available_tickets below
diff_period = r->period + 1;
} else if (diff_period < 0) {
//If time went backwards, we halt the time for this round
if (diff_period < 0)
diff_period = 0;
}
//Calculate the number of tickets that became available since
//the last time. (+ ScALE_FACTOR/2 is to round up at halfway points for
//integer arithmetics)
//the last time.
r->available_tickets += diff_period *
((r->scaled_tickets + SCALE_FACTOR/2) / r->period);
(r->scaled_tickets / r->period);
//throttle handing out tickets
//
if (r->available_tickets > r->scaled_tickets)
r->available_tickets = r->scaled_tickets;
//If we have at least onen ticket, we can allow
//If we have at least one ticket, we can allow
if (r->available_tickets >= 1 * SCALE_FACTOR) {
r->available_tickets -= 1 * SCALE_FACTOR;
allowed = 1;