feat(REST): dynamic rate limit offsets (#10099)

* feat(REST): dynamic rate limit offsets

* chore: update tests

* chore: better doc comment

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* fix: don't overlook globalReset

Co-authored-by: ckohen <chaikohen@gmail.com>

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: ckohen <chaikohen@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
DD
2024-01-30 11:29:42 +02:00
committed by GitHub
parent fc1f8ae374
commit 278396e815
6 changed files with 44 additions and 15 deletions

View File

@@ -90,7 +90,7 @@ export interface RESTOptions {
*
* @defaultValue `50`
*/
offset: number;
offset: GetRateLimitOffsetFunction | number;
/**
* Determines how rate limiting and pre-emptive throttling should be handled.
* When an array of strings, each element is treated as a prefix for the request route
@@ -191,6 +191,11 @@ export interface RateLimitData {
*/
export type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Awaitable<boolean>;
/**
* A function that determines the rate limit offset for a given request.
*/
export type GetRateLimitOffsetFunction = (route: string) => number;
export interface APIRequest {
/**
* The data that was used to form the body of this request

View File

@@ -2,7 +2,8 @@ import type { RESTPatchAPIChannelJSONBody, Snowflake } from 'discord-api-types/v
import type { REST } from '../REST.js';
import { RateLimitError } from '../errors/RateLimitError.js';
import { DEPRECATION_WARNING_PREFIX } from './constants.js';
import { RequestMethod, type RateLimitData, type ResponseLike } from './types.js';
import { RequestMethod } from './types.js';
import type { GetRateLimitOffsetFunction, RateLimitData, ResponseLike } from './types.js';
function serializeSearchParam(value: unknown): string | null {
switch (typeof value) {
@@ -156,3 +157,18 @@ export function deprecationWarning(message: string) {
process.emitWarning(message, DEPRECATION_WARNING_PREFIX);
}
}
/**
* Normalizes the offset for rate limits. Applies a Math.max(0, N) to prevent negative offsets,
* also deals with callbacks.
*
* @internal
*/
export function normalizeRateLimitOffset(offset: GetRateLimitOffsetFunction | number, route: string): number {
if (typeof offset === 'number') {
return Math.max(0, offset);
}
const result = offset(route);
return Math.max(0, result);
}