|
| 1 | +import { Organization } from "@trigger.dev/database"; |
| 2 | +import { Ratelimit } from "@upstash/ratelimit"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { env } from "~/env.server"; |
| 5 | +import { RateLimiterConfig } from "~/services/authorizationRateLimitMiddleware.server"; |
| 6 | +import { createRedisRateLimitClient, Duration, RateLimiter } from "~/services/rateLimiter.server"; |
| 7 | + |
| 8 | +const BatchLimitsConfig = z.object({ |
| 9 | + processingConcurrency: z.number().int().default(env.BATCH_CONCURRENCY_LIMIT_DEFAULT), |
| 10 | +}); |
| 11 | + |
| 12 | +/** |
| 13 | + * Batch limits configuration for a plan type |
| 14 | + */ |
| 15 | +export type BatchLimitsConfig = z.infer<typeof BatchLimitsConfig>; |
| 16 | + |
| 17 | +function createOrganizationRateLimiter(organization: Organization): RateLimiter { |
| 18 | + const redisClient = createRedisRateLimitClient({ |
| 19 | + port: env.RATE_LIMIT_REDIS_PORT, |
| 20 | + host: env.RATE_LIMIT_REDIS_HOST, |
| 21 | + username: env.RATE_LIMIT_REDIS_USERNAME, |
| 22 | + password: env.RATE_LIMIT_REDIS_PASSWORD, |
| 23 | + tlsDisabled: env.RATE_LIMIT_REDIS_TLS_DISABLED === "true", |
| 24 | + clusterMode: env.RATE_LIMIT_REDIS_CLUSTER_MODE_ENABLED === "1", |
| 25 | + }); |
| 26 | + |
| 27 | + const limiterConfig = resolveBatchRateLimitConfig(organization.batchRateLimitConfig); |
| 28 | + |
| 29 | + const limiter = |
| 30 | + limiterConfig.type === "fixedWindow" |
| 31 | + ? Ratelimit.fixedWindow(limiterConfig.tokens, limiterConfig.window) |
| 32 | + : limiterConfig.type === "tokenBucket" |
| 33 | + ? Ratelimit.tokenBucket( |
| 34 | + limiterConfig.refillRate, |
| 35 | + limiterConfig.interval, |
| 36 | + limiterConfig.maxTokens |
| 37 | + ) |
| 38 | + : Ratelimit.slidingWindow(limiterConfig.tokens, limiterConfig.window); |
| 39 | + |
| 40 | + return new RateLimiter({ |
| 41 | + redisClient, |
| 42 | + keyPrefix: "ratelimit:batch", |
| 43 | + limiter, |
| 44 | + logSuccess: false, |
| 45 | + logFailure: true, |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +function resolveBatchRateLimitConfig(batchRateLimitConfig?: unknown): RateLimiterConfig { |
| 50 | + const defaultRateLimiterConfig: RateLimiterConfig = { |
| 51 | + type: "tokenBucket", |
| 52 | + refillRate: env.BATCH_RATE_LIMIT_REFILL_RATE, |
| 53 | + interval: env.BATCH_RATE_LIMIT_REFILL_INTERVAL as Duration, |
| 54 | + maxTokens: env.BATCH_RATE_LIMIT_MAX, |
| 55 | + }; |
| 56 | + |
| 57 | + if (!batchRateLimitConfig) { |
| 58 | + return defaultRateLimiterConfig; |
| 59 | + } |
| 60 | + |
| 61 | + const parsedBatchRateLimitConfig = RateLimiterConfig.safeParse(batchRateLimitConfig); |
| 62 | + |
| 63 | + if (!parsedBatchRateLimitConfig.success) { |
| 64 | + return defaultRateLimiterConfig; |
| 65 | + } |
| 66 | + |
| 67 | + return parsedBatchRateLimitConfig.data; |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Get the rate limiter and limits for an organization. |
| 72 | + * Internally looks up the plan type, but doesn't expose it to callers. |
| 73 | + */ |
| 74 | +export async function getBatchLimits( |
| 75 | + organization: Organization |
| 76 | +): Promise<{ rateLimiter: RateLimiter; config: BatchLimitsConfig }> { |
| 77 | + const rateLimiter = createOrganizationRateLimiter(organization); |
| 78 | + const config = resolveBatchLimitsConfig(organization.batchQueueConcurrencyConfig); |
| 79 | + return { rateLimiter, config }; |
| 80 | +} |
| 81 | + |
| 82 | +function resolveBatchLimitsConfig(batchLimitsConfig?: unknown): BatchLimitsConfig { |
| 83 | + const defaultLimitsConfig: BatchLimitsConfig = { |
| 84 | + processingConcurrency: env.BATCH_CONCURRENCY_LIMIT_DEFAULT, |
| 85 | + }; |
| 86 | + |
| 87 | + if (!batchLimitsConfig) { |
| 88 | + return defaultLimitsConfig; |
| 89 | + } |
| 90 | + |
| 91 | + const parsedBatchLimitsConfig = BatchLimitsConfig.safeParse(batchLimitsConfig); |
| 92 | + |
| 93 | + if (!parsedBatchLimitsConfig.success) { |
| 94 | + return defaultLimitsConfig; |
| 95 | + } |
| 96 | + |
| 97 | + return parsedBatchLimitsConfig.data; |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * Error thrown when batch rate limit is exceeded. |
| 102 | + * Contains information for constructing a proper 429 response. |
| 103 | + */ |
| 104 | +export class BatchRateLimitExceededError extends Error { |
| 105 | + constructor( |
| 106 | + public readonly limit: number, |
| 107 | + public readonly remaining: number, |
| 108 | + public readonly resetAt: Date, |
| 109 | + public readonly itemCount: number |
| 110 | + ) { |
| 111 | + super( |
| 112 | + `Batch rate limit exceeded. Attempted to submit ${itemCount} items but only ${remaining} remaining. Limit resets at ${resetAt.toISOString()}` |
| 113 | + ); |
| 114 | + this.name = "BatchRateLimitExceededError"; |
| 115 | + } |
| 116 | +} |
0 commit comments