From 9ca4a354eede406a4eee5bfbfcf1283a8e6dce90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nils=20O=2E=20Sel=C3=A5sdal?= Date: Thu, 10 Oct 2013 01:06:49 +0200 Subject: [PATCH] Fix calculating available tickets. Help prevent overflow when there's long periods between calls --- src/rate_limit.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/rate_limit.c b/src/rate_limit.c index 3ed94bf..fec4c79 100644 --- a/src/rate_limit.c +++ b/src/rate_limit.c @@ -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 time went backwards, we halt the time for this round - if (diff_period < 0) + 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 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;