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
+58
-43
@@ -1,14 +1,19 @@
|
||||
import { getPlanFeatureUsage } from "./.server/subscriptionService";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
|
||||
import { cache } from "../cache.server";
|
||||
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
|
||||
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
|
||||
const DEFAULT_RATE_LIMIT_PER_MINUTE = 60;
|
||||
const DEFAULT_RATE_LIMIT_PER_SECOND = 5;
|
||||
|
||||
function getCacheKey(apiKey: string, period: string, timestamp: number): string {
|
||||
return `rateLimit:${apiKey}:${period}:${timestamp}`;
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
function featureLimit(feature: Awaited<ReturnType<typeof getPlanFeatureUsage>> | null, fallback: number): number {
|
||||
if (!feature) return fallback;
|
||||
if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) return 0;
|
||||
return feature.value;
|
||||
}
|
||||
|
||||
export async function rateLimitByKey({
|
||||
@@ -27,52 +32,62 @@ export async function rateLimitByKey({
|
||||
success: boolean;
|
||||
error: string | null;
|
||||
}> {
|
||||
const currentTimestamp = Math.floor(Date.now() / 1000);
|
||||
const minuteTimestamp = Math.floor(currentTimestamp / 60);
|
||||
const secondTimestamp = currentTimestamp;
|
||||
const [minuteFeature, secondFeature] = await Promise.all([
|
||||
limitByMinute === undefined ? getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerMinute, tenantSubscription) : Promise.resolve(null),
|
||||
limitBySecond === undefined ? getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerSecond, tenantSubscription) : Promise.resolve(null),
|
||||
]);
|
||||
const minuteLimit = limitByMinute ?? featureLimit(minuteFeature, DEFAULT_RATE_LIMIT_PER_MINUTE);
|
||||
const secondLimit = limitBySecond ?? featureLimit(secondFeature, DEFAULT_RATE_LIMIT_PER_SECOND);
|
||||
|
||||
const minuteKey = getCacheKey(apiKey, "minute", minuteTimestamp);
|
||||
const secondKey = getCacheKey(apiKey, "second", secondTimestamp);
|
||||
try {
|
||||
const store = storeFactory();
|
||||
const [minuteDecision, secondDecision] = await Promise.all([
|
||||
minuteLimit === 0
|
||||
? Promise.resolve(null)
|
||||
: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "legacy-api-minute",
|
||||
windowSeconds: 60,
|
||||
max: minuteLimit,
|
||||
}).consume(apiKey),
|
||||
secondLimit === 0
|
||||
? Promise.resolve(null)
|
||||
: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "legacy-api-second",
|
||||
windowSeconds: 1,
|
||||
max: secondLimit,
|
||||
}).consume(apiKey),
|
||||
]);
|
||||
|
||||
let minuteCount = (cache.get(minuteKey)?.value as number) || 0;
|
||||
let secondCount = (cache.get(secondKey)?.value as number) || 0;
|
||||
|
||||
if (limitByMinute === undefined) {
|
||||
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerMinute, tenantSubscription);
|
||||
if (!feature) {
|
||||
limitByMinute = DEFAULT_RATE_LIMIT_PER_MINUTE;
|
||||
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
|
||||
limitByMinute = 0;
|
||||
} else {
|
||||
limitByMinute = feature.value;
|
||||
if (minuteDecision && !minuteDecision.allowed) {
|
||||
const retryAfterSeconds = Math.max(1, Math.ceil((minuteDecision.resetAt.getTime() - Date.now()) / 1000));
|
||||
return {
|
||||
success: false,
|
||||
error: `You've exceeded the ${minuteLimit} request/min rate limit, try again in ${retryAfterSeconds} seconds`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (limitBySecond === undefined) {
|
||||
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerSecond, tenantSubscription);
|
||||
if (!feature) {
|
||||
limitBySecond = DEFAULT_RATE_LIMIT_PER_SECOND;
|
||||
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
|
||||
limitBySecond = 0;
|
||||
} else {
|
||||
limitBySecond = feature.value;
|
||||
if (secondDecision && !secondDecision.allowed) {
|
||||
return {
|
||||
success: false,
|
||||
error: `You've exceeded the ${secondLimit} request/sec rate limit`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// A replica-local fallback would make the advertised limit bypassable by
|
||||
// round-robin traffic. Authentication/usage enforcement therefore fails
|
||||
// closed while the shared counter is unavailable.
|
||||
return { success: false, error: "Rate limit service temporarily unavailable" };
|
||||
}
|
||||
|
||||
minuteCount += 1;
|
||||
secondCount += 1;
|
||||
|
||||
if (limitByMinute !== 0 && minuteCount > limitByMinute) {
|
||||
let tryAgainIn = 60 - (currentTimestamp % 60);
|
||||
return { success: false, error: `You've exceeded the ${limitByMinute} request/min rate limit, try again in ${tryAgainIn} seconds` };
|
||||
}
|
||||
|
||||
if (limitBySecond !== 0 && secondCount > limitBySecond) {
|
||||
return { success: false, error: `You've exceeded the ${limitBySecond} request/sec rate limit` };
|
||||
}
|
||||
|
||||
cache.set(minuteKey, { value: minuteCount, metadata: { createdTime: Date.now() } }, { ttl: 60 * 1000 });
|
||||
cache.set(secondKey, { value: secondCount, metadata: { createdTime: Date.now() } }, { ttl: 1000 });
|
||||
|
||||
return { success: true, error: null };
|
||||
}
|
||||
|
||||
export function __setRateLimitStoreForTests(store: SharedStore): void {
|
||||
storeFactory = () => store;
|
||||
}
|
||||
|
||||
export function __resetRateLimitStoreForTests(): void {
|
||||
storeFactory = () => getSharedStore();
|
||||
}
|
||||
Reference in new issue
Block a user