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 resolveABTestURL

Kiran K6779e6b59a18
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
index 18386f0a9b..e612a11899 100644
--- a/apps/web/lib/api/links/process-link.ts
+++ b/apps/web/lib/api/links/process-link.ts
@@ -4,7 +4,6 @@ import { getPangeaDomainIntel } from "@/lib/pangea";
import { checkIfUserExists, getRandomKey } from "@/lib/planetscale";
import { isStored } from "@/lib/storage";
import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";
-import { ABTestVariantsSchema } from "@/lib/zod/schemas/links";
import { prisma } from "@dub/prisma";
import {
DUB_DOMAINS,
@@ -532,6 +531,7 @@ export async function processLink<T extends Record<string, any>>({
// expire date checks
if (expiresAt) {
const datetime = parseDateTime(expiresAt);
+
if (!datetime) {
return {
link: payload,
@@ -539,9 +539,12 @@ export async function processLink<T extends Record<string, any>>({
code: "unprocessable_entity",
};
}
+
expiresAt = datetime;
+
if (expiredUrl) {
expiredUrl = getUrlFromString(expiredUrl);
+
if (!isValidUrl(expiredUrl)) {
return {
link: payload,
@@ -552,9 +555,9 @@ export async function processLink<T extends Record<string, any>>({
}
}
- // A/B testing checks
- if (testVariants && testCompletedAt) {
+ if (testCompletedAt) {
const datetime = parseDateTime(testCompletedAt);
+
if (!datetime) {
return {
link: payload,
@@ -562,17 +565,8 @@ export async function processLink<T extends Record<string, any>>({
code: "unprocessable_entity",
};
}
- testCompletedAt = datetime;
- const parsedTests = ABTestVariantsSchema.safeParse(testVariants);
- if (!parsedTests.success) {
- return {
- link: payload,
- error: "Invalid testVariants.",
- code: "unprocessable_entity",
- };
- }
- testVariants = parsedTests.data;
+ testCompletedAt = datetime;
}
// remove polyfill attributes from payload
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index bdc3daa632..a52523c5b5 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -30,8 +30,8 @@ import { isCaseSensitiveDomain } from "../api/links/case-sensitivity";
import { clickCache } from "../api/links/click-cache";
import { getLinkViaEdge } from "../planetscale";
import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";
-import { getTestDestinationURL } from "./utils/get-test-destination-url";
import { hasEmptySearchParams } from "./utils/has-empty-search-params";
+import { resolveABTestURL } from "./utils/resolve-ab-test-url";
export default async function LinkMiddleware(
req: NextRequest,
@@ -137,10 +137,11 @@ export default async function LinkMiddleware(
projectId: workspaceId,
} = cachedLink;
- const testUrl = getTestDestinationURL({
+ const testUrl = resolveABTestURL({
testVariants,
testCompletedAt,
});
+
const url = testUrl || cachedLink.url;
// by default, we only index default dub domain links (e.g. dub.sh)
diff --git a/apps/web/lib/middleware/utils/get-test-destination-url.ts b/apps/web/lib/middleware/utils/resolve-ab-test-url.ts
similarity index 76%
rename from apps/web/lib/middleware/utils/get-test-destination-url.ts
rename to apps/web/lib/middleware/utils/resolve-ab-test-url.ts
index d0bfb014cd..38cc3feb35 100644
--- a/apps/web/lib/middleware/utils/get-test-destination-url.ts
+++ b/apps/web/lib/middleware/utils/resolve-ab-test-url.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
/**
* Determines the destination URL for a link with A/B testVariants using weighted random selection
*/
-export const getTestDestinationURL = ({
+export const resolveABTestURL = ({
testVariants,
testCompletedAt,
}: {
@@ -17,31 +17,41 @@ export const getTestDestinationURL = ({
!testVariants ||
!testCompletedAt ||
!(new Date(testCompletedAt) > new Date())
- )
+ ) {
return null;
+ }
- if (testVariants.length < 2 || testVariants.length > MAX_TEST_COUNT)
- throw new Error("Invalid test count: " + testVariants.length);
+ if (testVariants.length < 2 || testVariants.length > MAX_TEST_COUNT) {
+ console.error(`Invalid test count: ${testVariants.length} for link.`);
+ return null;
+ }
const cookieStore = cookies();
const cookieUrl = cookieStore.get("dub_test_url")?.value;
- if (cookieUrl && testVariants.map((t) => t.url).includes(cookieUrl))
+ if (cookieUrl && testVariants.map((t) => t.url).includes(cookieUrl)) {
return cookieUrl;
+ }
let i = 0;
const weights = [testVariants[0].percentage];
// Calculate cumulative weights
- for (i = 1; i < testVariants.length; ++i)
+ for (i = 1; i < testVariants.length; ++i) {
weights[i] = testVariants[i].percentage + weights[i - 1];
+ }
// Generate a random number between 0 and the total cumulative weight
const random = Math.random() * weights[weights.length - 1];
// Loop through cumulative weights and stop when we've found the first one greater than `random`
- for (i = 0; i < weights.length; ++i) if (weights[i] > random) break;
+ for (i = 0; i < weights.length; ++i) {
+ if (weights[i] > random) {
+ break;
+ }
+ }
+
+ console.log("Found test variant", testVariants[i]);
- // Return the corresponding test URL
return testVariants[i].url;
} catch (e) {
console.error("Error getting test destination URL", e);