Skip to content

Commit 3460adc

Browse files
committed
added functionality for skipped windows
1 parent 955d0c5 commit 3460adc

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/rateLimiters/slidingWindowCounter.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,21 @@ class SlidingWindowCounter implements RateLimiter {
113113

114114
// if request time is in a new window
115115
if (timestamp >= window.fixedWindowStart + this.windowSize) {
116-
updatedUserWindow.previousTokens = updatedUserWindow.currentTokens;
117-
updatedUserWindow.currentTokens = 0;
118-
updatedUserWindow.fixedWindowStart = window.fixedWindowStart + this.windowSize;
116+
// calculates how many windows may have been skipped since last request
117+
const windowsSkipped = Math.floor(
118+
(timestamp - window.fixedWindowStart) / this.windowSize
119+
);
120+
// if more than one window was skipped
121+
if (windowsSkipped > 1) {
122+
updatedUserWindow.previousTokens = 0;
123+
updatedUserWindow.currentTokens = 0;
124+
updatedUserWindow.fixedWindowStart =
125+
window.fixedWindowStart + this.windowSize * windowsSkipped;
126+
} else {
127+
updatedUserWindow.previousTokens = updatedUserWindow.currentTokens;
128+
updatedUserWindow.currentTokens = 0;
129+
updatedUserWindow.fixedWindowStart = window.fixedWindowStart + this.windowSize;
130+
}
119131
}
120132

121133
// assigned to avoid TS error, this var will never be used as 0

0 commit comments

Comments
 (0)