Comments (2)
Ah, I was able to reproduce it, this answers a puzzle in #3 that'd been bugging me for a while now. Fixed on 1.1.0.
Here's a little rate limiter I whipped up to reproduce:
import TTLCache from './'
import type {Options as TTLCacheOptions} from './'
export interface Options<K> extends TTLCacheOptions<K, number> {
maxHits: number
}
export class RateLimiter<K> extends TTLCache<K, number> {
readonly maxHits: number
constructor (options: Options<K>) {
options.updateAgeOnGet = false
options.noUpdateTTL = true
super(options)
if (!options.maxHits || typeof options.maxHits !== 'number' || options.maxHits <= 0) {
throw new TypeError('must specify a positive number of max hits allowed within the period')
}
this.maxHits = options.maxHits
}
// call limiter.hit(key) and it'll return true if it's allowed,
// or false if it should be rejected.
hit (key:K) {
const value = (this.get(key) || 0) + 1
this.set(key, value)
return value < this.maxHits
}
}
Example:
const rl = new RateLimiter<string>({ ttl: 100, maxHits: 10 })
const run = () => {
const interval = setInterval(() => {
const allowed = rl.hit('test')
console.log(Date.now(), allowed, rl.get('test'))
if (!allowed) {
console.error('> > > > > hit rate limit')
clearInterval(interval)
setTimeout(run, 1)
}
}, 10)
}
run()
from ttlcache.
By the way, though, this isn't a very clever rate limiter, so I wouldn't make it too load-bearing. You could easily do stuff like this, assuming a rate limit of 100 hits every minute:
t=0 hit once (schedule purge for t=60)
...
t=59 send 99 hits
t=60 purge
t=61 send 100 hits (made 199 hits in 2 seconds!)
Here's one that uses the TTLCache's auto-purge to keep a time-series of hits by keeping a TTLCache for each key the limiter knows about. Bit more CPU and memory usage, but probably still not too bad.
import type {Options as TTLCacheOptions} from './'
import TTLCache from './'
export interface Options {
window: number
max: number
}
interface RLEntryOptions extends TTLCacheOptions<number, boolean> {
onEmpty: () => any
}
class RLEntry extends TTLCache<number, boolean> {
onEmpty: () => any
constructor(options: RLEntryOptions) {
super(options)
this.onEmpty = options.onEmpty
}
purgeStale() {
const ret = super.purgeStale()
if (this.size === 0 && ret) {
this.onEmpty()
}
return ret
}
}
class RateLimiter<K> extends Map<K, TTLCache<number, boolean>> {
window: number
max: number
constructor(options: Options) {
super()
this.window = options.window
this.max = options.max
}
hit(key: K) {
const c = super.get(key) || new RLEntry({
ttl: this.window,
onEmpty: () => this.delete(key),
})
this.set(key, c)
if (c.size > this.max) {
// rejected, too many hits within window
return false
}
c.set(performance.now(), true)
return true
}
count (key: K) {
const c = super.get(key)
return c ? c.size : 0
}
}
All these examples licensed under the same ISC license as this repo, but truly don't expect any support if they have bugs, lol
from ttlcache.
Related Issues (18)
- typescript support HOT 1
- Module not found: Can't resolve 'perf_hooks' HOT 4
- TTL = Infinity HOT 4
- Feature request: dispose function should be passed the time when an entry would have naturally expired HOT 2
- Module not found: Can't resolve 'perf_hooks' HOT 2
- Too slow HOT 8
- [BUG] cannot graceful stop due to leaked Timeout HOT 1
- Iterating entries/keys/values in dispose() function results in undefined entry for the stale element HOT 3
- Calling `.clear()` while elements are in the cache causes an exception when they are subsequently attempted to be purged as stale HOT 1
- bug: deleting an immortal entry causes an error HOT 1
- Feature request: Control over stale entries being emitting before or after collection removal HOT 4
- Feature request: Third argument to `set` can be either an object or Number HOT 2
- cache expiration does not work HOT 10
- Potential race condition issues HOT 3
- keys function can't return key of Infinity ttl HOT 2
- Add `maxSize` `maxEntrySize` and `sizeCalculation` options HOT 1
- Potential issues in CI environment HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ttlcache.