Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add rate limiting handling for Bitly link import

Kiran K3d4e02888088
diff --git a/apps/web/app/api/cron/import/bitly/route.ts b/apps/web/app/api/cron/import/bitly/route.ts
index 2b205d5096..5abbbf53cd 100644
--- a/apps/web/app/api/cron/import/bitly/route.ts
+++ b/apps/web/app/api/cron/import/bitly/route.ts
@@ -6,7 +6,7 @@ import { randomBadgeColor } from "@/ui/links/tag-badge";
import { prisma } from "@dub/prisma";
import { log } from "@dub/utils";
import { NextResponse } from "next/server";
-import { importLinksFromBitly } from "./utils";
+import { checkIfRateLimited, importLinksFromBitly } from "./utils";
export const dynamic = "force-dynamic";
@@ -16,11 +16,21 @@ export async function POST(req: Request) {
await verifyQstashSignature({ req, rawBody });
const body = JSON.parse(rawBody);
- const { workspaceId, bitlyGroup, importTags } = body;
+ const { workspaceId, bitlyGroup, importTags, rateLimited = false } = body;
try {
const bitlyApiKey = await redis.get(`import:bitly:${workspaceId}`);
+ if (rateLimited) {
+ const isRateLimited = await checkIfRateLimited(bitlyApiKey, body);
+
+ if (isRateLimited) {
+ return NextResponse.json({
+ response: "rate_limited",
+ });
+ }
+ }
+
let tagsToId: Record<string, string> | null = null;
if (importTags === true) {
const tagsImported = await redis.get(
diff --git a/apps/web/app/api/cron/import/bitly/utils.ts b/apps/web/app/api/cron/import/bitly/utils.ts
index 191d904545..fb50e45ff0 100644
--- a/apps/web/app/api/cron/import/bitly/utils.ts
+++ b/apps/web/app/api/cron/import/bitly/utils.ts
@@ -10,6 +10,17 @@ import {
linkConstructorSimple,
} from "@dub/utils";
+interface RateLimitResponse {
+ platform_limits: {
+ endpoint: string;
+ methods: {
+ name: string;
+ limit: number;
+ count: number;
+ }[];
+ }[];
+}
+
// Note: rate limit for /groups/{group_guid}/bitlinks is 1500 per hour or 150 per minute
export const importLinksFromBitly = async ({
workspaceId,
@@ -32,7 +43,7 @@ export const importLinksFromBitly = async ({
searchAfter?: string | null;
count?: number;
}) => {
- const data = await fetch(
+ const response = await fetch(
`https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/bitlinks?size=100${
searchAfter ? `&search_after=${searchAfter}` : ""
}`,
@@ -42,7 +53,25 @@ export const importLinksFromBitly = async ({
Authorization: `Bearer ${bitlyApiKey}`,
},
},
- ).then((res) => res.json());
+ );
+
+
+ if (!response.ok && response.status === 429) {
+ return await queueBitlyImport({
+ workspaceId,
+ userId,
+ bitlyGroup,
+ domains,
+ folderId,
+ tagsToId,
+ nextSearchAfter: searchAfter,
+ count,
+ rateLimited: true,
+ });
+ }
+
+ const data = await response.json();
+
const { links, pagination } = data;
const nextSearchAfter = pagination.search_after;
@@ -236,18 +265,79 @@ export const importLinksFromBitly = async ({
]);
return count;
} else {
- return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,
- body: {
- workspaceId,
- userId,
- bitlyGroup,
- domains,
- folderId,
- importTags: tagsToId ? true : false,
- searchAfter: nextSearchAfter,
- count,
+ return await queueBitlyImport({
+ workspaceId,
+ userId,
+ bitlyGroup,
+ domains,
+ folderId,
+ tagsToId,
+ nextSearchAfter,
+ count,
+ });
+ }
+};
+
+// Queue a Bitly import
+export const queueBitlyImport = async (payload: {
+ workspaceId: string;
+ userId: string;
+ bitlyGroup: string;
+ domains: string[];
+ folderId?: string;
+ tagsToId?: Record<string, string>;
+ nextSearchAfter?: string | null;
+ count?: number;
+ rateLimited?: boolean;
+ delay?: number;
+}) => {
+ const { tagsToId, nextSearchAfter, delay, ...rest } = payload;
+
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,
+ body: {
+ ...rest,
+ importTags: tagsToId ? true : false,
+ searchAfter: nextSearchAfter,
+ },
+ ...(delay && { delay }),
+ });
+};
+
+// Handle rate limited requests
+export const checkIfRateLimited = async (bitlyApiKey: unknown, body: any) => {
+ const path = "/groups/{group_guid}/bitlinks";
+
+ const response = await fetch(
+ `https://api-ssl.bitly.com/v4/user/platform_limits?path=${path}`,
+ {
+ headers: {
+ Authorization: `Bearer ${bitlyApiKey}`,
+ "Content-Type": "application/json",
},
+ },
+ );
+
+ const data = (await response.json()) as RateLimitResponse;
+
+ const endpoint = data.platform_limits[0].methods.find(
+ (method) => method.name === "GET",
+ )!;
+
+ const limit = endpoint.limit;
+ const currentUsage = endpoint.count;
+
+ console.log("checkIfRateLimited", endpoint);
+
+ const isRateLimited = limit - currentUsage === 0;
+
+ if (isRateLimited) {
+ await queueBitlyImport({
+ ...body,
+ rateLimited: true,
+ delay: 2 * 60, // try again after 2 minutes
});
}
+
+ return isRateLimited;
};
diff --git a/apps/web/lib/middleware/bitly.ts b/apps/web/lib/middleware/bitly.ts
index 5fa1d60b13..72b60c426b 100644
--- a/apps/web/lib/middleware/bitly.ts
+++ b/apps/web/lib/middleware/bitly.ts
@@ -14,6 +14,7 @@ type BitlyLink = {
tags: string[];
};
+// Create a new Bitly link in Dub on-demand
export const createBitlyLink = async (bitlyLink: string) => {
const response = await fetch(
`https://api-ssl.bitly.com/v4/bitlinks/${bitlyLink}`,