@railzai/bottleneck
Version:
Distributed task scheduler and rate limiter
81 lines (68 loc) • 2.44 kB
text/coffeescript
parser = require "./parser"
Events = require "./Events"
RedisConnection = require "./RedisConnection"
IORedisConnection = require "./IORedisConnection"
Scripts = require "./Scripts"
class Group
defaults:
timeout: 1000 * 60 * 5
connection: null
Promise: Promise
id: "group-key"
constructor: ( ={}) ->
parser.load , , @
= new Events @
= {}
= require "./Bottleneck"
()
= ?
if ! ?
if .datastore == "redis"
= new RedisConnection Object.assign {}, , { }
else if .datastore == "ioredis"
= new IORedisConnection Object.assign {}, , { }
key: (key="") -> [key] ? do =>
limiter = [key] = new Object.assign , {
id: "#{@id}-#{key}",
,
}
.trigger "created", limiter, key
limiter
deleteKey: (key="") =>
instance = [key]
if
deleted = await .__runCommand__ ['del', Scripts.allKeys("#{@id}-#{key}")...]
if instance?
delete [key]
await instance.disconnect()
instance? or deleted > 0
limiters: -> { key: k, limiter: v } for k, v of
keys: -> Object.keys
clusterKeys: ->
if ! ? then return .resolve ()
keys = []
cursor = null
start = "b_#{@id}-".length
end = "_settings".length
until cursor == 0
[next, found] = await .__runCommand__ ["scan", (cursor ? 0), "match", "b_#{@id}-*_settings", "count", 10000]
cursor = ~~next
keys.push(k.slice(start, -end)) for k in found
keys
_startAutoCleanup: ->
clearInterval
( = setInterval =>
time = Date.now()
for k, v of
try if await v._store.__groupCheck__(time) then k
catch e then v.Events.trigger "error", e
, ( / 2)).unref?()
updateSettings: (options={}) ->
parser.overwrite options, , @
parser.overwrite options, options,
() if options.timeout?
disconnect: (flush=true) ->
if !
?.disconnect flush
module.exports = Group