The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Redis + proxy updates
Tim Wilson3c5b42e58be1
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.tsindex adc3821f03..4de70db997 100644--- a/apps/web/lib/api/links/update-link.ts+++ b/apps/web/lib/api/links/update-link.ts@@ -56,6 +56,7 @@ export async function updateLink({tagIds,tagNames,webhookIds,+ tests,...rest} = updatedLink;@@ -93,6 +94,8 @@ export async function updateLink({expiresAt: expiresAt ? new Date(expiresAt) : null,geo: geo || Prisma.JsonNull,+ tests: tests || Prisma.JsonNull,+// Associate tags by tagNames...(tagNames &&updatedLink.projectId && {diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 8a45972866..32d77ca224 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -25,10 +25,12 @@ import {NextResponse,userAgent,} from "next/server";+import { z } from "zod";import { linkCache } from "../api/links/cache";import { isCaseSensitiveDomain } from "../api/links/case-sensitivity";import { getLinkViaEdge } from "../planetscale";import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";+import { LinkTestsSchema, MAX_TEST_COUNT } from "../zod/schemas/links";import { hasEmptySearchParams } from "./utils/has-empty-search-params";export default async function LinkMiddleware(@@ -134,7 +136,6 @@ export default async function LinkMiddleware(const {id: linkId,- url,password,trackConversion,proxy,@@ -146,9 +147,16 @@ export default async function LinkMiddleware(expiredUrl,doIndex,webhookIds,+ tests,+ testsCompleteAt,projectId: workspaceId,} = cachedLink;+ const url =+ tests && testsCompleteAt+ ? getTestDestinationURL({ url: cachedLink.url, tests, testsCompleteAt })+ : cachedLink.url;+// by default, we only index default dub domain links (e.g. dub.sh)// everything else is not indexed by default, unless the user has explicitly set it to be indexedconst shouldIndex = isDubDomain(domain) || doIndex === true;@@ -506,3 +514,45 @@ export default async function LinkMiddleware();}}++/**+ * Determines the destination URL for a link with A/B tests using weighted random selection+ */+const getTestDestinationURL = ({+ url,+ tests,+ testsCompleteAt,+}: {+ url?: string;+ tests: z.infer<typeof LinkTestsSchema>;+ testsCompleteAt: Date;+}) => {+ try {+ if (!tests || !testsCompleteAt || !(new Date(testsCompleteAt) > new Date()))+ return url;++ if (tests.length < 2 || tests.length > MAX_TEST_COUNT) {+ throw new Error("Invalid test count: " + tests.length);+ }++ let i = 0;+ const weights = [tests[0].percentage];++ // Calculate cumulative weights+ for (i = 1; i < tests.length; ++i)+ weights[i] = tests[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;++ // Return the corresponding test URL+ return tests[i].url;+ } catch (e) {+ console.error("Error getting test destination URL", e);+ }++ return url;+};diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex bd025b04b8..cf7c44d4a1 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -39,7 +39,7 @@ import {leadEventResponseSchema,trackLeadResponseSchema,} from "./zod/schemas/leads";-import { createLinkBodySchema } from "./zod/schemas/links";+import { createLinkBodySchema, LinkTestsSchema } from "./zod/schemas/links";import { createOAuthAppSchema, oAuthAppSchema } from "./zod/schemas/oauth";import {createPartnerSchema,@@ -113,6 +113,8 @@ export interface RedisLinkProps {doIndex?: boolean;projectId?: string;webhookIds?: string[];+ tests?: z.infer<typeof LinkTestsSchema>;+ testsCompleteAt?: Date;}export interface TagProps {diff --git a/apps/web/lib/upstash/format-redis-link.ts b/apps/web/lib/upstash/format-redis-link.tsindex 986ba656d7..d78defcca5 100644--- a/apps/web/lib/upstash/format-redis-link.ts+++ b/apps/web/lib/upstash/format-redis-link.ts@@ -1,5 +1,7 @@+import { z } from "zod";import { ExpandedLink } from "../api/links/utils/transform-link";import { RedisLinkProps } from "../types";+import { LinkTestsSchema } from "../zod/schemas/links";export function formatRedisLink(link: ExpandedLink): RedisLinkProps {const {@@ -17,6 +19,8 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {doIndex,projectId,webhooks,+ tests,+ testsCompleteAt,} = link;const webhookIds = webhooks?.map(({ webhookId }) => webhookId) ?? [];@@ -39,5 +43,11 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {...(projectId && { projectId }), // projectId can be undefined for anonymous links...(doIndex && { doIndex: true }),...(webhookIds.length > 0 && { webhookIds }),+ ...(Boolean(+ tests && testsCompleteAt && new Date(testsCompleteAt) > new Date(),+ ) && {+ tests: tests as z.infer<typeof LinkTestsSchema>,+ testsCompleteAt: new Date(testsCompleteAt!),+ }),};}