* Benchmarks rate limiting with different limits
()
| 146 | * Benchmarks rate limiting with different limits |
| 147 | */ |
| 148 | function benchmarkDifferentLimits () { |
| 149 | console.log("\n📊 Rate Limiting with Different Limits"); |
| 150 | console.log("-".repeat(40)); |
| 151 | |
| 152 | const suite = new Benchmark.Suite(); |
| 153 | |
| 154 | // Create different rate limit configurations |
| 155 | const configs = [ |
| 156 | { name: "Low limit (10 req)", limit: 10, reset: 60 }, |
| 157 | { name: "Medium limit (100 req)", limit: 100, reset: 300 }, |
| 158 | { name: "High limit (1000 req)", limit: 1000, reset: 900 }, |
| 159 | { name: "Very high limit (10000 req)", limit: 10000, reset: 3600 } |
| 160 | ]; |
| 161 | |
| 162 | const rateStores = configs.map(() => new Map()); |
| 163 | |
| 164 | const checkRateLimitWithConfig = (req, config, store) => { |
| 165 | const reqId = req.sessionID || req.ip; |
| 166 | const currentTime = Math.floor(Date.now() / 1000); |
| 167 | |
| 168 | if (!store.has(reqId)) { |
| 169 | store.set(reqId, { |
| 170 | remaining: config.limit - 1, |
| 171 | reset: currentTime + config.reset |
| 172 | }); |
| 173 | |
| 174 | return true; |
| 175 | } |
| 176 | |
| 177 | const state = store.get(reqId); |
| 178 | |
| 179 | if (currentTime >= state.reset) { |
| 180 | state.remaining = config.limit - 1; |
| 181 | state.reset = currentTime + config.reset; |
| 182 | |
| 183 | return true; |
| 184 | } |
| 185 | |
| 186 | return state.remaining > 0 ? (state.remaining--, true) : false; |
| 187 | }; |
| 188 | |
| 189 | configs.forEach((config, index) => { |
| 190 | suite.add(`Rate Limit - ${config.name}`, () => { |
| 191 | const req = createMockRequest({ sessionID: "test-client" }); |
| 192 | checkRateLimitWithConfig(req, config, rateStores[index]); |
| 193 | }); |
| 194 | }); |
| 195 | |
| 196 | suite |
| 197 | .on("cycle", event => { |
| 198 | console.log(` ${String(event.target)}`); |
| 199 | }) |
| 200 | .on("complete", function () { |
| 201 | console.log(` Fastest: ${this.filter("fastest").map("name")}`); |
| 202 | }) |
| 203 | .run(); |
| 204 | } |
| 205 |
no test coverage detected