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.

Refactor A/B test completion logic: replace completeTests with completeABTests, introduce scheduling functions, and remove deprecated scheduleTestCompletion. Update relevant API routes and link management functions accordingly.

Kiran K7499bcb9c64d
diff --git a/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts b/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts
index d4f8e7c89f..9ed34e999e 100644
--- a/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts
+++ b/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts
@@ -1,34 +1,31 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { completeTests } from "@/lib/api/links/complete-tests";
+import { completeABTests } from "@/lib/api/links/complete-ab-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
- */
+// POST - /api/cron/links/[linkId]/complete-tests
+// Completes a link's tests if they're ready, scheduled by QStash
export async function POST(
req: Request,
- { params = {} }: { params: Record<string, string> | undefined },
+ {
+ params: { linkId },
+ }: {
+ params: { linkId: string };
+ },
) {
try {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const { linkId } = params;
-
- if (!linkId) return new Response("Link ID is required.", { status: 400 });
-
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) {
+ return new Response(`Link ${linkId} not found. Skipping...`);
+ }
if (
link.testVariants &&
@@ -36,11 +33,12 @@ export async function POST(
link.testCompletedAt < new Date() &&
Date.now() - link.testCompletedAt.getTime() < 2 * 60 * 60 * 1000 // Limit to two hour window
) {
- await completeTests(link as any);
- return new Response("Tests completed.", { status: 200 });
+ await completeABTests(link as any);
+
+ return new Response(`Tests completed for link ${linkId}.`);
}
- return new Response("No test completion necessary.", { status: 200 });
+ return new Response(`No test completion necessary for link ${linkId}.`);
} catch (error) {
return handleAndReturnErrorResponse(error);
}
diff --git a/apps/web/lib/api/links/ab-test-scheduler.ts b/apps/web/lib/api/links/ab-test-scheduler.ts
new file mode 100644
index 0000000000..1eef3cf32c
--- /dev/null
+++ b/apps/web/lib/api/links/ab-test-scheduler.ts
@@ -0,0 +1,52 @@
+import { qstash } from "@/lib/cron";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { ExpandedLink } from "./utils";
+
+// Schedules a job to complete a link's AB test
+export async function scheduleABTestCompletion(
+ link: Pick<ExpandedLink, "id" | "testVariants" | "testCompletedAt">,
+) {
+ await cancelScheduledABTestCompletion(link.id);
+
+ if (!link.testVariants || !link.testCompletedAt) {
+ return;
+ }
+
+ const url = `${APP_DOMAIN_WITH_NGROK}/api/cron/links/${link.id}/complete-tests`;
+ const testCompletedAt = new Date(link.testCompletedAt);
+
+ // Tests are not complete yet, schedule a job for completion
+ if (testCompletedAt > new Date()) {
+ await qstash.publishJSON({
+ url,
+ delay: (testCompletedAt.getTime() - new Date().getTime()) / 1000,
+ deduplicationId: link.id,
+ });
+ }
+}
+
+// Cancels a scheduled AB test completion for a link (Eg: if the link is updated or deleted)
+export async function cancelScheduledABTestCompletion(linkId: string) {
+ const url = `${APP_DOMAIN_WITH_NGROK}/api/cron/links/${linkId}/complete-tests`;
+
+ const response = 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,
+ }),
+ });
+
+ if (!response.ok) {
+ console.error(
+ `Failed to cancel scheduled AB test completion for link ${linkId}`,
+ {
+ status: response.status,
+ statusText: response.statusText,
+ },
+ );
+ }
+}
diff --git a/apps/web/lib/api/links/complete-tests.ts b/apps/web/lib/api/links/complete-ab-tests.ts
similarity index 97%
rename from apps/web/lib/api/links/complete-tests.ts
rename to apps/web/lib/api/links/complete-ab-tests.ts
index cc66112aff..61ef1676fd 100644
--- a/apps/web/lib/api/links/complete-tests.ts
+++ b/apps/web/lib/api/links/complete-ab-tests.ts
@@ -8,7 +8,7 @@ import { DubApiError, ErrorCodes } from "../errors";
import { processLink } from "./process-link";
import { updateLink } from "./update-link";
-export async function completeTests(link: Link & { project: Project }) {
+export async function completeABTests(link: Link & { project: Project }) {
if (!link.testVariants || !link.testCompletedAt || !link.projectId) return;
const testVariants = LinkTestsSchema.parse(link.testVariants);
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index b8af03afb4..b6b80706cf 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -15,10 +15,10 @@ import { linkConstructorSimple } from "@dub/utils/src/functions/link-constructor
import { waitUntil } from "@vercel/functions";
import { createId } from "../create-id";
import { combineTagIds } from "../tags/combine-tag-ids";
+import { scheduleABTestCompletion } from "./ab-test-scheduler";
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";
@@ -181,7 +181,7 @@ export async function createLink(link: ProcessedLinkProps) {
webhookIds,
}),
- testVariants && testCompletedAt && scheduleTestCompletion(response),
+ testVariants && testCompletedAt && scheduleABTestCompletion(response),
]),
);
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 99a60c9a47..3e80ed8f8d 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -3,6 +3,7 @@ import { recordLinkTB, transformLinkTB } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { cancelScheduledABTestCompletion } from "./ab-test-scheduler";
import { linkCache } from "./cache";
import { includeTags } from "./include-tags";
import { transformLink } from "./utils";
@@ -32,6 +33,7 @@ export async function deleteLink(linkId: string) {
...transformLinkTB(link),
deleted: true,
}),
+
link.projectId &&
prisma.project.update({
where: {
@@ -41,6 +43,10 @@ export async function deleteLink(linkId: string) {
totalLinks: { decrement: 1 },
},
}),
+
+ link.testVariants &&
+ link.testCompletedAt &&
+ cancelScheduledABTestCompletion(link.id),
]),
);
diff --git a/apps/web/lib/api/links/schedule-test-completion.ts b/apps/web/lib/api/links/schedule-test-completion.ts
deleted file mode 100644
index d224d8c465..0000000000
--- a/apps/web/lib/api/links/schedule-test-completion.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-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/${link.id}/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.testVariants) return;
-
- const testCompletedAt = link.testCompletedAt
- ? new Date(link.testCompletedAt)
- : null;
-
- if (!testCompletedAt) return;
-
- if (testCompletedAt > new Date()) {
- // Tests are not complete yet, schedule a job for completion
- await qstash.publishJSON({
- url: completionUrl,
- delay: (testCompletedAt.getTime() - new Date().getTime()) / 1000,
- });
- }
-}
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index ca4ab92f19..a3e3b4298a 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -14,10 +14,10 @@ import {
import { waitUntil } from "@vercel/functions";
import { createId } from "../create-id";
import { combineTagIds } from "../tags/combine-tag-ids";
+import { scheduleABTestCompletion } from "./ab-test-scheduler";
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({
@@ -194,7 +194,7 @@ export async function updateLink({
webhookIds,
}),
- testVariants && testCompletedAt && scheduleTestCompletion(response),
+ testVariants && testCompletedAt && scheduleABTestCompletion(response),
]),
);