Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+13
-7
@@ -21,14 +21,16 @@ export interface FixedWindowDecision {
|
||||
}
|
||||
|
||||
export interface FixedWindowRateLimiter {
|
||||
consume(key: string): Promise<FixedWindowDecision>;
|
||||
/** Atomically reserve one or more actions in the current window. */
|
||||
consume(key: string, weight?: number): Promise<FixedWindowDecision>;
|
||||
/** Test/admin helper: drop the counter for a key. */
|
||||
reset(key: string): Promise<void>;
|
||||
}
|
||||
|
||||
const FIXED_WINDOW_SCRIPT = `
|
||||
local current = redis.call('INCR', KEYS[1])
|
||||
if current == 1 then
|
||||
local weight = tonumber(ARGV[2])
|
||||
local current = redis.call('INCRBY', KEYS[1], weight)
|
||||
if current == weight then
|
||||
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
|
||||
end
|
||||
local ttl = redis.call('TTL', KEYS[1])
|
||||
@@ -41,8 +43,9 @@ return { current, ttl }
|
||||
MemoryAdapter.registerScript(FIXED_WINDOW_SCRIPT, async (adapter, keys, args) => {
|
||||
const [key] = keys;
|
||||
const window = Number.parseInt(args[0] ?? "0", 10);
|
||||
const current = await adapter.incr(key);
|
||||
if (current === 1 && window > 0) {
|
||||
const weight = Number.parseInt(args[1] ?? "1", 10);
|
||||
const current = await adapter.incr(key, weight);
|
||||
if (current === weight && window > 0) {
|
||||
await adapter.expire(key, window);
|
||||
}
|
||||
// We do not implement TTL command on the adapter surface; the helper
|
||||
@@ -68,9 +71,12 @@ export function createFixedWindowRateLimiter(options: FixedWindowRateLimiterOpti
|
||||
const bucketKey = (key: string) => `rl:fixed:${options.prefix}:${key}`;
|
||||
|
||||
return {
|
||||
async consume(key) {
|
||||
async consume(key, weight = 1) {
|
||||
if (!Number.isSafeInteger(weight) || weight <= 0) {
|
||||
throw new Error("fixed-window rate-limit weight must be a positive safe integer");
|
||||
}
|
||||
const fullKey = store.key(bucketKey(key));
|
||||
const result = (await store.adapter.eval(FIXED_WINDOW_SCRIPT, [fullKey], [String(options.windowSeconds)])) as
|
||||
const result = (await store.adapter.eval(FIXED_WINDOW_SCRIPT, [fullKey], [String(options.windowSeconds), String(weight)])) as
|
||||
| [number | string, number | string]
|
||||
| undefined;
|
||||
const current = Number(result?.[0] ?? 0);
|
||||
|
||||
Reference in new issue
Block a user