The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add `fetchWithRetry` for clicks ingestion
Steven Teyacda5dc31f5d
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex 109be2de1b..723bb2636a 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -2,6 +2,7 @@ import {LOCALHOST_GEO_DATA,LOCALHOST_IP,capitalize,+ fetchWithRetry,getDomainWithoutWWW,} from "@dub/utils";import { EU_COUNTRY_CODES } from "@dub/utils/src/constants/countries";@@ -149,7 +150,7 @@ export async function recordClick({const hasWebhooks = webhookIds && webhookIds.length > 0;const [, , , , workspaceRows] = await Promise.allSettled([- fetch(+ fetchWithRetry(`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,{method: "POST",diff --git a/packages/utils/src/functions/fetch-with-retry.ts b/packages/utils/src/functions/fetch-with-retry.tsnew file mode 100644index 0000000000..3c4523d690--- /dev/null+++ b/packages/utils/src/functions/fetch-with-retry.ts@@ -0,0 +1,75 @@+export async function fetchWithRetry(+ input: RequestInfo | URL,+ init?: RequestInit | undefined,+ options: {+ timeout?: number;+ maxRetries?: number;+ retryDelay?: number;+ } = {},+): Promise<Response> {+ const { timeout = 5000, maxRetries = 10, retryDelay = 1000 } = options;++ let lastError: Error | null = null;++ for (let i = 0; i < maxRetries; i++) {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => {+ controller.abort();+ }, timeout);++ try {+ const response = await fetch(input, {+ ...init,+ signal: controller.signal,+ });++ clearTimeout(timeoutId);++ if (response.ok) {+ return response;+ }++ // Handle rate limiting and server errors+ if (response.status === 429 || response.status >= 500) {+ const delay = retryDelay + Math.pow(i, 2) * 50;+ await new Promise((resolve) => setTimeout(resolve, delay));+ continue;+ }++ // Handle unauthorized errors+ if (response.status === 403) {+ throw new Error("Unauthorized");+ }++ // Handle other errors+ if (!response.ok) {+ let errorMessage: string;+ try {+ const error = await response.json();+ errorMessage = error.error || `HTTP error ${response.status}`;+ } catch {+ errorMessage = `HTTP error ${response.status}`;+ }+ throw new Error(errorMessage);+ }+ } catch (error) {+ clearTimeout(timeoutId);+ lastError = error instanceof Error ? error : new Error(String(error));++ // If this is the last retry, throw the error+ if (i === maxRetries - 1) {+ throw new Error(+ `Failed after ${maxRetries} retries. Last error: ${lastError.message}`,+ );+ }++ // For network errors or timeouts, wait and retry+ const delay = retryDelay + Math.pow(i, 2) * 50;+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }++ // This should never be reached due to the throw in the last retry,+ // but TypeScript needs it for type safety+ throw new Error(`Failed after ${maxRetries} retries`);+}diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.tsindex 7de915919a..f2f37b8a15 100644--- a/packages/utils/src/functions/index.ts+++ b/packages/utils/src/functions/index.ts@@ -8,6 +8,7 @@ export * from "./currency-formatter";export * from "./datetime";export * from "./deep-equal";export * from "./domains";+export * from "./fetch-with-retry";export * from "./fetch-with-timeout";export * from "./fetcher";export * from "./format-file-size";