Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/large-beds-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thirdweb-dev/service-utils": minor
---

pass `team` instead of `project` to `rateLimit`
21 changes: 0 additions & 21 deletions packages/service-utils/src/core/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,24 +164,3 @@ export async function fetchTeamAndProject(
);
}
}

export async function updateRateLimitedAt(
projectId: string,
config: CoreServiceConfig,
): Promise<void> {
const { apiUrl, serviceScope: scope, serviceApiKey } = config;

const url = `${apiUrl}/usage/rateLimit`;

await fetch(url, {
method: "PUT",
headers: {
"x-service-api-key": serviceApiKey,
"content-type": "application/json",
},
body: JSON.stringify({
apiKeyId: projectId, // projectId is the apiKeyId
scope,
}),
});
}
29 changes: 4 additions & 25 deletions packages/service-utils/src/core/rateLimit/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
type CoreServiceConfig,
type ProjectResponse,
updateRateLimitedAt,
} from "../api.js";
import type { CoreServiceConfig, TeamResponse } from "../api.js";
import type { RateLimitResult } from "./types.js";

const RATE_LIMIT_WINDOW_SECONDS = 10;
Expand All @@ -14,7 +10,7 @@ type IRedis = {
};

export async function rateLimit(args: {
project?: ProjectResponse;
team: TeamResponse;
limitPerSecond: number;
serviceConfig: CoreServiceConfig;
redis: IRedis;
Expand All @@ -25,13 +21,7 @@ export async function rateLimit(args: {
*/
sampleRate?: number;
}): Promise<RateLimitResult> {
const {
project,
limitPerSecond,
serviceConfig,
redis,
sampleRate = 1.0,
} = args;
const { team, limitPerSecond, serviceConfig, redis, sampleRate = 1.0 } = args;

const shouldSampleRequest = Math.random() < sampleRate;
if (!shouldSampleRequest) {
Expand All @@ -57,7 +47,7 @@ export async function rateLimit(args: {
const timestampWindow =
Math.floor(Date.now() / (1000 * RATE_LIMIT_WINDOW_SECONDS)) *
RATE_LIMIT_WINDOW_SECONDS;
const key = `rate-limit:${serviceScope}:${project?.id}:${timestampWindow}`;
const key = `rate-limit:${serviceScope}:${team.id}:${timestampWindow}`;

// Increment and get the current request count in this window.
const requestCount = await redis.incr(key);
Expand All @@ -71,17 +61,6 @@ export async function rateLimit(args: {
limitPerSecond * sampleRate * RATE_LIMIT_WINDOW_SECONDS;

if (requestCount > limitPerWindow) {
/**
* Report rate limit hits.
* Only track rate limit when its hit for the first time.
* Not waiting for tracking to complete as user doesn't need to wait.
*/
if (requestCount === limitPerWindow + 1 && project?.id) {
updateRateLimitedAt(project.id, serviceConfig).catch(() => {
// no-op
});
}

return {
rateLimited: true,
requestCount,
Expand Down
24 changes: 9 additions & 15 deletions packages/service-utils/src/core/rateLimit/rateLimit.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { validProjectResponse, validServiceConfig } from "../../mocks.js";
import { updateRateLimitedAt } from "../api.js";
import { validServiceConfig, validTeamResponse } from "../../mocks.js";
import { rateLimit } from "./index.js";

const mockRedis = {
incr: vi.fn(),
expire: vi.fn(),
};

// Mocking the updateRateLimitedAt function
vi.mock("../../../src/core/api", () => ({
updateRateLimitedAt: vi.fn().mockResolvedValue({}),
}));

describe("rateLimit", () => {
beforeEach(() => {
// Clear mock function calls and reset any necessary state.
Expand All @@ -27,7 +21,7 @@ describe("rateLimit", () => {

it("should not rate limit if service scope is not in rate limits", async () => {
const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 0,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand All @@ -44,7 +38,7 @@ describe("rateLimit", () => {
mockRedis.incr.mockResolvedValue(50); // Current count is 50 requests in 10 seconds.

const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 5,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand All @@ -55,15 +49,15 @@ describe("rateLimit", () => {
requestCount: 50,
rateLimit: 50,
});
expect(updateRateLimitedAt).not.toHaveBeenCalled();

expect(mockRedis.expire).not.toHaveBeenCalled();
});

it("should rate limit if exceeded hard limit", async () => {
mockRedis.incr.mockResolvedValue(51);

const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 5,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand All @@ -77,15 +71,15 @@ describe("rateLimit", () => {
errorMessage: `You've exceeded your storage rate limit at 5 reqs/sec. To get higher rate limits, contact us at https://thirdweb.com/contact-us.`,
errorCode: "RATE_LIMIT_EXCEEDED",
});
expect(updateRateLimitedAt).toHaveBeenCalled();

expect(mockRedis.expire).not.toHaveBeenCalled();
});

it("expires on the first incr request only", async () => {
mockRedis.incr.mockResolvedValue(1);

const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 5,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand All @@ -104,7 +98,7 @@ describe("rateLimit", () => {
vi.spyOn(global.Math, "random").mockReturnValue(0.08);

const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 5,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand All @@ -127,7 +121,7 @@ describe("rateLimit", () => {
vi.spyOn(global.Math, "random").mockReturnValue(0.15);

const result = await rateLimit({
project: validProjectResponse,
team: validTeamResponse,
limitPerSecond: 5,
serviceConfig: validServiceConfig,
redis: mockRedis,
Expand Down
2 changes: 1 addition & 1 deletion packages/service-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type {
TeamResponse,
} from "./core/api.js";

export { fetchTeamAndProject, updateRateLimitedAt } from "./core/api.js";
export { fetchTeamAndProject } from "./core/api.js";

export {
authorizeBundleId,
Expand Down
Loading