Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split up basic and param-based rate limits #3145

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 47 additions & 15 deletions packages/xrpc-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export class Server {
middleware: Record<'json' | 'text', RequestHandler>
globalRateLimiters: RateLimiterI[]
sharedRateLimiters: Record<string, RateLimiterI>
routeRateLimiterFns: Record<string, RateLimiterConsume[]>
// these two are treated separately because we do expensive schema validation after req ratelimits
basicRouteRateLimiterFns: Record<string, RateLimiterConsume[]> // limits based on IP
paramRouteRateLimiterFns: Record<string, RateLimiterConsume[]> // limits based on req context

constructor(lexicons?: LexiconDoc[], opts?: Options) {
if (lexicons) {
Expand All @@ -86,7 +88,8 @@ export class Server {
}
this.globalRateLimiters = []
this.sharedRateLimiters = {}
this.routeRateLimiterFns = {}
this.basicRouteRateLimiterFns = {}
this.paramRouteRateLimiterFns = {}
if (opts?.rateLimits?.global) {
for (const limit of opts.rateLimits.global) {
const rateLimiter = opts.rateLimits.creator({
Expand Down Expand Up @@ -250,12 +253,31 @@ export class Server {
validateOutput(nsid, def, output, this.lex)
const assertValidXrpcParams = (params: unknown) =>
this.lex.assertValidXrpcParams(nsid, params)
const rlFns = this.routeRateLimiterFns[nsid] ?? []
const consumeRateLimit = (reqCtx: XRPCReqContext) =>
consumeMany(reqCtx, rlFns)
const basicRlFns = this.basicRouteRateLimiterFns[nsid] ?? []
const consumeBasicRateLimit = (
req: express.Request,
res: express.Response,
) =>
consumeMany(
{ req, res, auth: undefined, input: undefined, params: {} },
basicRlFns,
)
const paramRlFns = this.paramRouteRateLimiterFns[nsid] ?? []
const consumeParamRateLimit = (reqCtx: XRPCReqContext) =>
consumeMany(reqCtx, paramRlFns)

return async function (req, res, next) {
try {
const locals: RequestLocals = req[kRequestLocals]

// handle req rate limits that don't use validated params
if (basicRlFns.length) {
const result = await consumeBasicRateLimit(req, res)
if (result instanceof RateLimitExceededError) {
return next(result)
}
}

// validate request
let params = decodeQueryParams(def, req.query)
try {
Expand All @@ -265,8 +287,6 @@ export class Server {
}
const input = validateReqInput(req)

const locals: RequestLocals = req[kRequestLocals]

const reqCtx: XRPCReqContext = {
params,
input,
Expand All @@ -276,9 +296,11 @@ export class Server {
}

// handle rate limits
const result = await consumeRateLimit(reqCtx)
if (result instanceof RateLimitExceededError) {
return next(result)
if (paramRlFns.length) {
const result = await consumeParamRateLimit(reqCtx)
if (result instanceof RateLimitExceededError) {
return next(result)
}
}

// run the handler
Expand Down Expand Up @@ -422,19 +444,21 @@ export class Server {
}

private setupRouteRateLimits(nsid: string, config: XRPCHandlerConfig) {
this.routeRateLimiterFns[nsid] = []
this.basicRouteRateLimiterFns[nsid] = []
this.paramRouteRateLimiterFns[nsid] = []
for (const limit of this.globalRateLimiters) {
const consumeFn = async (ctx: XRPCReqContext) => {
return limit.consume(ctx)
}
this.routeRateLimiterFns[nsid].push(consumeFn)
this.basicRouteRateLimiterFns[nsid].push(consumeFn)
}

if (config.rateLimit) {
const limits = Array.isArray(config.rateLimit)
? config.rateLimit
: [config.rateLimit]
this.routeRateLimiterFns[nsid] = []
this.basicRouteRateLimiterFns[nsid] ??= []
this.paramRouteRateLimiterFns[nsid] ??= []
for (let i = 0; i < limits.length; i++) {
const limit = limits[i]
const { calcKey, calcPoints } = limit
Expand All @@ -446,7 +470,11 @@ export class Server {
calcKey,
calcPoints,
})
this.routeRateLimiterFns[nsid].push(consumeFn)
if (calcKey === undefined && calcPoints === undefined) {
this.basicRouteRateLimiterFns[nsid].push(consumeFn)
} else {
this.paramRouteRateLimiterFns[nsid].push(consumeFn)
}
}
} else {
const { durationMs, points } = limit
Expand All @@ -464,7 +492,11 @@ export class Server {
calcKey,
calcPoints,
})
this.routeRateLimiterFns[nsid].push(consumeFn)
if (calcKey === undefined && calcPoints === undefined) {
this.basicRouteRateLimiterFns[nsid].push(consumeFn)
} else {
this.paramRouteRateLimiterFns[nsid].push(consumeFn)
}
}
}
}
Expand Down