The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Test completion
Tim Wilson6069c1d5462b
diff --git a/apps/web/app/api/cron/links/complete-tests/route.ts b/apps/web/app/api/cron/links/complete-tests/route.tsnew file mode 100644index 0000000000..8196d9679f--- /dev/null+++ b/apps/web/app/api/cron/links/complete-tests/route.ts@@ -0,0 +1,42 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { completeTests } from "@/lib/api/links/complete-tests";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { prisma } from "@dub/prisma";++/**+ * Completes a link's tests if they're ready, scheduled by QStash+ */+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();+ await verifyQstashSignature({ req, rawBody });++ const { linkId } = JSON.parse(rawBody);++ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ include: {+ project: true,+ },+ });++ if (!link || !link.project)+ return new Response("Link not found. Skipping...", { status: 200 });++ if (+ link.tests &&+ link.testsCompleteAt &&+ link.testsCompleteAt < new Date() &&+ Date.now() - link.testsCompleteAt.getTime() < 2 * 60 * 60 * 1000 // Limit to two hour window+ ) {+ await completeTests(link as any);+ return new Response("Tests completed.", { status: 200 });+ }++ return new Response("No test completion necessary.", { status: 200 });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/api/links/complete-tests.ts b/apps/web/lib/api/links/complete-tests.tsnew file mode 100644index 0000000000..1fca7d5675--- /dev/null+++ b/apps/web/lib/api/links/complete-tests.ts@@ -0,0 +1,117 @@+import { getAnalytics } from "@/lib/analytics/get-analytics";+import { NewLinkProps, WorkspaceProps } from "@/lib/types";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";+import { linkEventSchema, LinkTestsSchema } from "@/lib/zod/schemas/links";+import { Link, Project } from "@prisma/client";+import { waitUntil } from "@vercel/functions";+import { DubApiError, ErrorCodes } from "../errors";+import { processLink } from "./process-link";+import { updateLink } from "./update-link";++export async function completeTests(link: Link & { project: Project }) {+ if (!link.tests || !link.testsCompleteAt || !link.projectId) return;++ const tests = LinkTestsSchema.parse(link.tests);++ const analytics = (await getAnalytics({+ event: "leads",+ groupBy: "top_urls",+ linkId: link.id,+ workspaceId: link.projectId,+ dataAvailableFrom: link.project.createdAt,+ end: link.testsCompleteAt,+ })) as { url: string; leads: number }[];++ const max = Math.max(+ ...tests.map(+ (test) => analytics.find(({ url }) => url === test.url)?.leads || 0,+ ),+ );++ if (max === 0) {+ // All results are zero, do nothing+ console.log(+ `completeTests: All results are zero for ${link.id}, doing nothing`,+ );+ return;+ }++ const winners = tests.filter(+ (test) =>+ (analytics.find(({ url }) => url === test.url)?.leads || 0) === max,+ );++ if (winners.length === 0)+ throw new Error(+ `completeTests: Failed to find winners based on max leads for link ${link.id}`,+ );++ const winner = winners[Math.floor(Math.random() * winners.length)];+ console.log(+ `completeTests: Determined A/B tests winner for ${link.id}: ${winner.url}${winners.length > 1 ? ` (${winners.length} tied)` : ""}`,+ );++ if (winner.url === link.url) return;++ // Update the link's URL to the winner++ // Add body onto existing link but maintain NewLinkProps form for processLink+ const { project, ...originalLink } = link;++ const updatedLink = {+ ...originalLink,+ expiresAt:+ link.expiresAt instanceof Date+ ? link.expiresAt.toISOString()+ : link.expiresAt,+ geo: link.geo as NewLinkProps["geo"],++ tests: link.tests as NewLinkProps["tests"],+ testsCompleteAt: new Date(link.testsCompleteAt).toISOString(),++ // Update URL+ url: winner.url,++ // When root domain+ ...(link.key === "_root" && {+ domain: link.domain,+ key: link.key,+ }),+ };++ const {+ link: processedLink,+ error,+ code,+ } = await processLink({+ payload: updatedLink,+ workspace: link.project as WorkspaceProps,+ skipKeyChecks: true,+ skipExternalIdChecks: true,+ skipFolderChecks: true,+ });++ if (error) {+ throw new DubApiError({+ code: code as ErrorCodes,+ message: error,+ });+ }++ const response = await updateLink({+ oldLink: {+ domain: link.domain,+ key: link.key,+ image: link.image,+ },+ updatedLink: processedLink,+ });++ waitUntil(+ sendWorkspaceWebhook({+ trigger: "link.updated",+ workspace: link.project,+ data: linkEventSchema.parse(response),+ }),+ );+}diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex ea5a90a070..cd092707ae 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -18,6 +18,7 @@ import { combineTagIds } from "../tags/combine-tag-ids";import { linkCache } from "./cache";import { encodeKeyIfCaseSensitive } from "./case-sensitivity";import { includeTags } from "./include-tags";+import { scheduleTestCompletion } from "./schedule-test-completion";import { updateLinksUsage } from "./update-links-usage";import { transformLink } from "./utils";@@ -178,6 +179,8 @@ export async function createLink(link: ProcessedLinkProps) {propagateWebhookTriggerChanges({webhookIds,}),++ tests && testsCompleteAt && scheduleTestCompletion(response),]),);diff --git a/apps/web/lib/api/links/schedule-test-completion.ts b/apps/web/lib/api/links/schedule-test-completion.tsnew file mode 100644index 0000000000..63b440d29c--- /dev/null+++ b/apps/web/lib/api/links/schedule-test-completion.ts@@ -0,0 +1,51 @@+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { ExpandedLink } from "./utils";++export async function scheduleTestCompletion(link: ExpandedLink) {+ const completionUrl = `${APP_DOMAIN_WITH_NGROK}/api/cron/links/complete-tests`;++ // Remove any previously scheduled completion jobs+ try {+ const deleteResponse = await fetch(+ "https://qstash.upstash.io/v2/messages",+ {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${process.env.QSTASH_TOKEN}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ url: completionUrl,+ }),+ },+ );+ if (!deleteResponse.ok)+ throw new Error(+ `Fetch failed: ${deleteResponse.status} ${deleteResponse.statusText}`,+ );+ } catch (e) {+ console.error(+ "scheduleTestCompletion: failed to cancel previously scheduled completion messages",+ );+ }++ if (!link.tests) return;++ const testsCompleteAt = link.testsCompleteAt+ ? new Date(link.testsCompleteAt)+ : null;++ if (!testsCompleteAt) return;++ if (testsCompleteAt > new Date()) {+ // Tests are not complete yet, schedule a job for completion+ await qstash.publishJSON({+ url: completionUrl,+ delay: (testsCompleteAt.getTime() - new Date().getTime()) / 1000,+ body: {+ linkId: link.id,+ },+ });+ }+}diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.tsindex 4de70db997..011f8e818c 100644--- a/apps/web/lib/api/links/update-link.ts+++ b/apps/web/lib/api/links/update-link.ts@@ -17,6 +17,7 @@ import { combineTagIds } from "../tags/combine-tag-ids";import { linkCache } from "./cache";import { encodeKeyIfCaseSensitive } from "./case-sensitivity";import { includeTags } from "./include-tags";+import { scheduleTestCompletion } from "./schedule-test-completion";import { transformLink } from "./utils";export async function updateLink({@@ -57,6 +58,7 @@ export async function updateLink({tagNames,webhookIds,tests,+ testsCompleteAt,...rest} = updatedLink;@@ -94,6 +96,7 @@ export async function updateLink({expiresAt: expiresAt ? new Date(expiresAt) : null,geo: geo || Prisma.JsonNull,+ testsCompleteAt: testsCompleteAt ? new Date(testsCompleteAt) : null,tests: tests || Prisma.JsonNull,// Associate tags by tagNames@@ -184,6 +187,8 @@ export async function updateLink({propagateWebhookTriggerChanges({webhookIds,}),++ tests && testsCompleteAt && scheduleTestCompletion(response),]),);