The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve importer efficiency
Steven Tey1f52cb01045a
diff --git a/apps/web/app/api/cron/import/bitly/fetch-utils.ts b/apps/web/app/api/cron/import/bitly/fetch-utils.tsnew file mode 100644index 0000000000..74cf845599--- /dev/null+++ b/apps/web/app/api/cron/import/bitly/fetch-utils.ts@@ -0,0 +1,208 @@+/**+ * Utilities for fetching links from Bitly API+ */++interface FetchBitlyLinksResult {+ links: any[];+ nextSearchAfter: string | null;+ rateLimited: boolean;+ batchStats?: {+ batchCount: number;+ totalLinks: number;+ };+}++/**+ * Fetch links from Bitly with batch support for high rate limit groups+ */+export const fetchBitlyLinks = async ({+ bitlyGroup,+ bitlyApiKey,+ searchAfter = null,+ createdBefore = null,+}: {+ bitlyGroup: string;+ bitlyApiKey: string;+ searchAfter: string | null;+ createdBefore: string | null;+}): Promise<FetchBitlyLinksResult> => {+ // Use batch fetching for high rate limit group+ if (bitlyGroup === "Backg8weUUQ") {+ console.log("Using batch fetching for high rate limit group");+ return fetchBitlyLinksBatch({+ bitlyGroup,+ bitlyApiKey,+ searchAfter,+ createdBefore,+ });+ }++ // Use standard fetching for regular groups+ return fetchBitlyLinksStandard({+ bitlyGroup,+ bitlyApiKey,+ searchAfter,+ createdBefore,+ });+};++/**+ * Standard method to fetch links from Bitly (single request)+ */+const fetchBitlyLinksStandard = async ({+ bitlyGroup,+ bitlyApiKey,+ searchAfter,+ createdBefore,+}: {+ bitlyGroup: string;+ bitlyApiKey: string;+ searchAfter: string | null;+ createdBefore: string | null;+}): Promise<FetchBitlyLinksResult> => {+ const response = await fetch(+ `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/bitlinks?${new URLSearchParams(+ {+ size: "100",+ ...(searchAfter && { search_after: searchAfter }),+ ...(createdBefore && { created_before: createdBefore }),+ },+ )}`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${bitlyApiKey}`,+ },+ },+ );++ if (!response.ok && response.status === 429) {+ return {+ links: [],+ nextSearchAfter: searchAfter,+ rateLimited: true,+ };+ }++ const data = await response.json();++ if (!data.links || !data.pagination) {+ console.log("Unexpected response format:", data);+ return {+ links: [],+ nextSearchAfter: null,+ rateLimited: false,+ };+ }++ const { links, pagination } = data;+ const nextSearchAfter = pagination.search_after;++ return {+ links,+ nextSearchAfter,+ rateLimited: false,+ };+};++/**+ * Batch method to fetch links from Bitly (multiple requests)+ * For use with high rate limit groups+ */+const fetchBitlyLinksBatch = async ({+ bitlyGroup,+ bitlyApiKey,+ searchAfter,+ createdBefore,+}: {+ bitlyGroup: string;+ bitlyApiKey: string;+ searchAfter: string | null;+ createdBefore: string | null;+}): Promise<FetchBitlyLinksResult> => {+ // Array to collect all links from multiple requests+ let allLinks: any[] = [];+ let currentSearchAfter = searchAfter;+ let nextSearchAfter = null;+ const maxRequests = 5; // Number of consecutive requests to make++ // Make multiple requests to fetch up to 1000 links+ for (let i = 0; i < maxRequests; i++) {+ const response = await fetch(+ `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/bitlinks?${new URLSearchParams(+ {+ size: "100",+ ...(currentSearchAfter && { search_after: currentSearchAfter }),+ ...(createdBefore && { created_before: createdBefore }),+ },+ )}`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${bitlyApiKey}`,+ },+ },+ );++ // Check for rate limiting+ if (!response.ok && response.status === 429) {+ // If rate limited on the first request, return with rateLimited flag+ if (i === 0) {+ return {+ links: [],+ nextSearchAfter: searchAfter,+ rateLimited: true,+ };+ } else {+ // If rate limited after collecting some links, process what we have so far+ console.log(+ `Rate limited after ${i} requests. Processing ${allLinks.length} links.`,+ );+ break;+ }+ }++ const data = await response.json();++ // If the response is not as expected, break the loop+ if (!data.links || !data.pagination) {+ console.log("Unexpected response format:", data);+ if (i === 0) {+ return {+ links: [],+ nextSearchAfter: null,+ rateLimited: false,+ };+ }+ break; // Process what we have so far+ }++ const { links, pagination } = data;+ nextSearchAfter = pagination.search_after;++ // Add links to our collection+ allLinks = [...allLinks, ...links];++ // Update search_after for next request+ currentSearchAfter = nextSearchAfter;++ // If there are no more links to fetch, break the loop+ if (!nextSearchAfter || links.length < 100) {+ break;+ }+ }++ console.log(+ `Batch fetched ${allLinks.length} links in ${Math.ceil(allLinks.length / 100)} requests`,+ );++ return {+ links: allLinks,+ nextSearchAfter,+ rateLimited: false,+ batchStats: {+ batchCount: Math.ceil(allLinks.length / 100),+ totalLinks: allLinks.length,+ },+ };+};diff --git a/apps/web/app/api/cron/import/bitly/rate-limit.ts b/apps/web/app/api/cron/import/bitly/rate-limit.tsnew file mode 100644index 0000000000..87e5cfa417--- /dev/null+++ b/apps/web/app/api/cron/import/bitly/rate-limit.ts@@ -0,0 +1,76 @@+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+// Queue a Bitly import+export const queueBitlyImport = async (payload: {+ workspaceId: string;+ userId: string;+ bitlyGroup: string;+ domains: string[];+ folderId?: string;+ tagsToId?: Record<string, string>;+ searchAfter?: string | null;+ count?: number;+ rateLimited?: boolean;+ delay?: number;+}) => {+ const { tagsToId, delay, ...rest } = payload;++ return await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,+ body: {+ ...rest,+ importTags: tagsToId ? true : false,+ },+ ...(delay && { delay }),+ });+};++/**+ * Check if we're rate limited and handle accordingly+ */+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 {+ platform_limits: {+ endpoint: string;+ methods: {+ name: string;+ limit: number;+ count: number;+ }[];+ }[];+ };++ const endpoint = data.platform_limits[0].methods.find(+ (method) => method.name === "GET",+ )!;++ const limit = endpoint.limit;+ const currentUsage = endpoint.count;++ console.log("checkIfRateLimited", endpoint);+ console.log("originalBody", body);++ const isRateLimited = currentUsage >= limit;++ if (isRateLimited) {+ await queueBitlyImport({+ ...body,+ rateLimited: true,+ delay: 2 * 60, // try again after 2 minutes+ });+ }++ return isRateLimited;+};diff --git a/apps/web/app/api/cron/import/bitly/route.ts b/apps/web/app/api/cron/import/bitly/route.tsindex e149b7ea98..9adaaee691 100644--- a/apps/web/app/api/cron/import/bitly/route.ts+++ b/apps/web/app/api/cron/import/bitly/route.ts@@ -6,7 +6,8 @@ import { randomBadgeColor } from "@/ui/links/tag-badge";import { prisma } from "@dub/prisma";import { log } from "@dub/utils";import { NextResponse } from "next/server";-import { checkIfRateLimited, importLinksFromBitly } from "./utils";+import { checkIfRateLimited } from "./rate-limit";+import { importLinksFromBitly } from "./utils";export const dynamic = "force-dynamic";diff --git a/apps/web/app/api/cron/import/bitly/utils.ts b/apps/web/app/api/cron/import/bitly/utils.tsindex 1a81413b69..84ff92dd33 100644--- a/apps/web/app/api/cron/import/bitly/utils.ts+++ b/apps/web/app/api/cron/import/bitly/utils.ts@@ -1,25 +1,11 @@import { bulkCreateLinks } from "@/lib/api/links";-import { qstash } from "@/lib/cron";import { redis } from "@/lib/upstash";import { sendEmail } from "@dub/email";import { LinksImported } from "@dub/email/templates/links-imported";import { prisma } from "@dub/prisma";-import {- APP_DOMAIN_WITH_NGROK,- getUrlFromStringIfValid,- linkConstructorSimple,-} from "@dub/utils";--interface RateLimitResponse {- platform_limits: {- endpoint: string;- methods: {- name: string;- limit: number;- count: number;- }[];- }[];-}+import { getUrlFromStringIfValid, linkConstructorSimple } from "@dub/utils";+import { fetchBitlyLinks } from "./fetch-utils";+import { queueBitlyImport } from "./rate-limit";// Note: rate limit for /groups/{group_guid}/bitlinks is 1500 per hour or 150 per minuteexport const importLinksFromBitly = async ({@@ -45,23 +31,17 @@ export const importLinksFromBitly = async ({createdBefore?: string | null;count?: number;}) => {- const response = await fetch(- `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/bitlinks?${new URLSearchParams(- {- size: "100",- ...(searchAfter && { search_after: searchAfter }),- ...(createdBefore && { created_before: createdBefore }),- },- )}`,- {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${bitlyApiKey}`,- },- },- );+ // Fetch links from Bitly (either standard or batch method based on bitlyGroup)+ const { links, nextSearchAfter, rateLimited, batchStats } =+ await fetchBitlyLinks({+ bitlyGroup,+ bitlyApiKey,+ searchAfter,+ createdBefore,+ });- if (!response.ok && response.status === 429) {+ // If rate limited, queue for later+ if (rateLimited) {return await queueBitlyImport({workspaceId,userId,@@ -75,10 +55,11 @@ export const importLinksFromBitly = async ({});}- const data = await response.json();-- const { links, pagination } = data;- const nextSearchAfter = pagination.search_after;+ // If no links were returned, exit early+ if (!links || links.length === 0) {+ console.log("No links returned from Bitly");+ return count;+ }const invalidLinks: any[] = [];@@ -180,10 +161,12 @@ export const importLinksFromBitly = async ({count += importedLinks.length;+ // Log batch stats if availableconsole.log({importedLinksLength: importedLinks.length,count,nextSearchAfter,+ ...(batchStats && { batchStats }),});console.log(`Invalid links: ${invalidLinks.length}`);@@ -191,7 +174,7 @@ export const importLinksFromBitly = async ({const finalImportedLink = importedLinks[importedLinks.length - 1];console.log(- `Successfully imported ${importedLinks.length} new links! Final imported link: ${finalImportedLink.shortLink} (${new Date(finalImportedLink.createdAt).toISOString()})`,+ `Successfully imported ${importedLinks.length} new links! Final imported link: ${finalImportedLink?.shortLink} (${finalImportedLink ? new Date(finalImportedLink.createdAt).toISOString() : "none"})`,);if (nextSearchAfter === "") {@@ -279,67 +262,3 @@ export const importLinksFromBitly = async ({});}};--// Queue a Bitly import-export const queueBitlyImport = async (payload: {- workspaceId: string;- userId: string;- bitlyGroup: string;- domains: string[];- folderId?: string;- tagsToId?: Record<string, string>;- searchAfter?: string | null;- count?: number;- rateLimited?: boolean;- delay?: number;-}) => {- const { tagsToId, delay, ...rest } = payload;-- return await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/bitly`,- body: {- ...rest,- importTags: tagsToId ? true : false,- },- ...(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);- console.log("originalBody", body);-- const isRateLimited = currentUsage >= limit;-- if (isRateLimited) {- await queueBitlyImport({- ...body,- rateLimited: true,- delay: 2 * 60, // try again after 2 minutes- });- }-- return isRateLimited;-};