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.

Close four gaps in search sync coverage

Rafif93d8c1a76a9
diff --git a/apps/web/app/(ee)/api/cron/domains/update/route.ts b/apps/web/app/(ee)/api/cron/domains/update/route.ts
index 651219e652..aede01e279 100644
--- a/apps/web/app/(ee)/api/cron/domains/update/route.ts
+++ b/apps/web/app/(ee)/api/cron/domains/update/route.ts
@@ -6,6 +6,10 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";
import { includeTags } from "@/lib/api/links/include-tags";
+import {
+ PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
+ queuePartnerSearchSyncForLinks,
+} from "@/lib/api/partners/queue-partner-search-sync";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { prisma } from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
@@ -101,6 +105,12 @@ export async function POST(req: Request) {
linkCache.expireMany(linksToUpdate),
]);
+ // Queued after the block above rather than inside it, because
+ // updateShortLinks runs there and the document indexes `shortLink`.
+ await queuePartnerSearchSyncForLinks(updatedLinks, {
+ delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
+ });
+
const response = await queueDomainUpdate({
...payload,
startingAfter: linksToUpdate[linksToUpdate.length - 1].id,
diff --git a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
index 9d30e7c5b7..8ac6bfc4e6 100644
--- a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
+++ b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
@@ -1,5 +1,9 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
+import {
+ PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
+ queuePartnerSearchSync,
+} from "@/lib/api/partners/queue-partner-search-sync";
import { extractUtmParams } from "@/lib/api/utm/extract-utm-params";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
@@ -126,6 +130,14 @@ export async function POST(req: Request) {
const redisRes = await linkCache.expireMany(linksToUpdate);
console.log(`Updated Redis cache: ${JSON.stringify(redisRes, null, 2)}`);
+ // A UTM template rewrites each link's destination URL, which the document
+ // indexes. The enrollments are already in hand, so this passes them
+ // directly rather than resolving them back from the links.
+ await queuePartnerSearchSync({
+ enrollmentIds: programEnrollments.map(({ id }) => id),
+ delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
+ });
+
if (programEnrollments.length === PAGE_SIZE) {
await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/sync-utm`,
diff --git a/apps/web/app/(ee)/api/embed/referrals/links/[linkId]/route.ts b/apps/web/app/(ee)/api/embed/referrals/links/[linkId]/route.ts
index a6340df3fc..6dca41b05e 100644
--- a/apps/web/app/(ee)/api/embed/referrals/links/[linkId]/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/links/[linkId]/route.ts
@@ -99,6 +99,8 @@ export const PATCH = withReferralsEmbedToken(
domain: link.domain,
key: link.key,
image: link.image,
+ programId: link.programId,
+ partnerId: link.partnerId,
},
updatedLink: processedLink,
});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts
index 0fcfafa048..c08562328e 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts
@@ -147,6 +147,8 @@ export const PATCH = withPartnerProfile(
domain: link.domain,
key: link.key,
image: link.image,
+ programId: link.programId,
+ partnerId: link.partnerId,
},
updatedLink: processedLink,
});
diff --git a/apps/web/app/(ee)/api/partners/links/upsert/route.ts b/apps/web/app/(ee)/api/partners/links/upsert/route.ts
index d251d2a19a..19b9e5f352 100644
--- a/apps/web/app/(ee)/api/partners/links/upsert/route.ts
+++ b/apps/web/app/(ee)/api/partners/links/upsert/route.ts
@@ -170,6 +170,8 @@ export const PUT = withWorkspace(
domain: link.domain,
key: link.key,
image: link.image,
+ programId: link.programId,
+ partnerId: link.partnerId,
},
updatedLink: processedLink,
});
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index b30cb32ff3..7ea389b30d 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -175,6 +175,8 @@ export const PATCH = withWorkspace(
domain: link.domain,
key: link.key,
image: link.image,
+ programId: link.programId,
+ partnerId: link.partnerId,
},
updatedLink: processedLink,
});
diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.ts
index febaa1a2dc..22f0a9b406 100644
--- a/apps/web/app/api/links/upsert/route.ts
+++ b/apps/web/app/api/links/upsert/route.ts
@@ -149,6 +149,8 @@ export const PUT = withWorkspace(
domain: link.domain,
key: link.key,
image: link.image,
+ programId: link.programId,
+ partnerId: link.partnerId,
},
updatedLink: processedLink,
});
diff --git a/apps/web/lib/actions/partners/bulk-archive-partners.ts b/apps/web/lib/actions/partners/bulk-archive-partners.ts
index 1b69516998..c8c08d6434 100644
--- a/apps/web/lib/actions/partners/bulk-archive-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-archive-partners.ts
@@ -84,9 +84,12 @@ export const bulkArchivePartnersAction = authActionClient
})),
),
- queuePartnerSearchSync({
- enrollmentIds: programEnrollments.map(({ id }) => id),
- }),
+ // Scoped to match the updateMany above, not the findMany. The select
+ // is narrowed to ACTIVE_ENROLLMENT_STATUSES while the update is not,
+ // so archiving a banned or rejected partner changes a status the
+ // selected rows never carried. Passing the partners re-resolves
+ // exactly the enrollments the update touched.
+ queuePartnerSearchSync({ partnerIds, programId }),
]),
);
});
diff --git a/apps/web/lib/actions/partners/start-partner-platform-verification.ts b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
index 829237a8e2..07479ee041 100644
--- a/apps/web/lib/actions/partners/start-partner-platform-verification.ts
+++ b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
@@ -6,6 +6,7 @@ import {
} from "@/lib/api/oauth/utils";
import { PARTNER_PLATFORMS_PROVIDERS } from "@/lib/api/partner-profile/partner-platforms-providers";
import { upsertPartnerPlatform } from "@/lib/api/partner-profile/upsert-partner-platform";
+import { queuePartnerSearchSync } from "@/lib/api/partners/queue-partner-search-sync";
import { generateOTP } from "@/lib/auth/utils";
import { extractEmailDomain } from "@/lib/email/extract-email-domain";
import { isGenericEmail } from "@/lib/email/is-generic-email";
@@ -22,6 +23,7 @@ import {
PARTNERS_DOMAIN_WITH_NGROK,
} from "@dub/utils";
import { PlatformType } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
import { cookies } from "next/headers";
import { v4 as uuid } from "uuid";
import * as z from "zod/v4";
@@ -77,19 +79,30 @@ export const startPartnerPlatformVerificationAction = authPartnerActionClient
source,
};
- // For website
- if (platform === "website") {
- return startWebsiteVerification(params);
- }
+ const startVerification = async () => {
+ // For website
+ if (platform === "website") {
+ return startWebsiteVerification(params);
+ }
- // For OAuth based verification
- const oauthProvider = PARTNER_PLATFORMS_PROVIDERS[platform];
- if (oauthProvider) {
- return startOAuthVerification(params);
- }
+ // For OAuth based verification
+ const oauthProvider = PARTNER_PLATFORMS_PROVIDERS[platform];
+ if (oauthProvider) {
+ return startOAuthVerification(params);
+ }
+
+ // For code based verification
+ return startCodeVerification(params);
+ };
+
+ const result = await startVerification();
+
+ // All three paths upsert the platform identifier, which is searchable.
+ // Queued here, after the write, rather than at each of the four upserts,
+ // so one verification produces one sync rather than one per platform row.
+ waitUntil(queuePartnerSearchSync({ partnerIds: [partner.id] }));
- // For code based verification
- return startCodeVerification(params);
+ return result;
});
// Start website verification using TXT record (or auto-verify if email domain matches)
diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.ts
index b618f33ef5..6e07851224 100644
--- a/apps/web/lib/api/links/bulk-update-links.ts
+++ b/apps/web/lib/api/links/bulk-update-links.ts
@@ -43,6 +43,20 @@ export async function bulkUpdateLinks(
const imageUrlNonce = nanoid(7);
+ // The bulk payload is createLinkBodySchema minus domain/key/externalId, and
+ // that omit list does not drop `partnerId` or `programId` — so a bulk update
+ // can move links between partners. Read the current owners first, because
+ // after the write they are unrecoverable and syncing only the new owner
+ // would leave the links searchable under a partner who no longer has them.
+ // Only paid for when the payload actually carries an owner.
+ const previousOwners =
+ rest.partnerId !== undefined || rest.programId !== undefined
+ ? await prisma.link.findMany({
+ where: { id: { in: linkIds } },
+ select: { programId: true, partnerId: true },
+ })
+ : [];
+
const updatedLinks = await Promise.all(
linkIds.map((linkId) =>
prisma.link.update({
@@ -122,7 +136,7 @@ export async function bulkUpdateLinks(
// A bulk edit can move the destination URL, and the key or domain behind
// the short link. Queued on the link delay: the job re-reads the whole
// document, so nothing else goes stale by waiting.
- queuePartnerSearchSyncForLinks(updatedLinks, {
+ queuePartnerSearchSyncForLinks([...previousOwners, ...updatedLinks], {
delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
}),
// if proxy is true and image is not stored in R2, upload image to R2
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index 1158eabd65..4c4fad13a4 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -1,6 +1,6 @@
import {
PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
- queuePartnerSearchSync,
+ queuePartnerSearchSyncForLinks,
} from "@/lib/api/partners/queue-partner-search-sync";
import { getPartnerEnrollmentInfo } from "@/lib/planetscale/get-partner-enrollment-info";
import { prisma } from "@/lib/prisma";
@@ -33,6 +33,12 @@ export async function updateLink({
key: string;
image?: string | null;
testCompletedAt?: Date | null;
+ // Required, not optional, because the link body accepts `partnerId` and so
+ // an update can move a link between partners. The former owner has to be
+ // re-serialized without it, and an optional field here would let the next
+ // caller omit it and silently lose that.
+ programId: string | null;
+ partnerId: string | null;
};
updatedLink: ProcessedLinkProps &
Pick<LinkProps, "id" | "clicks" | "lastClicked" | "updatedAt">;
@@ -209,13 +215,15 @@ export async function updateLink({
// Only the short link and destination URL reach the document, and link
// edits are frequent, so this takes the longer link delay. The job
// re-reads the whole document, so nothing else goes stale by waiting.
- response.programId &&
- response.partnerId &&
- queuePartnerSearchSync({
- partnerIds: [response.partnerId],
- programId: response.programId,
- delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
- }),
+ //
+ // Both owners, because `partnerId` and `programId` are not excluded
+ // from the spread above and so can be rewritten. When a link moves
+ // between partners the former owner has to be re-serialized without
+ // it, and syncing only the new one would leave the link searchable
+ // under a partner who no longer has it.
+ queuePartnerSearchSyncForLinks([oldLink, response], {
+ delay: PARTNER_SEARCH_LINK_SYNC_DELAY_SECONDS,
+ }),
// If proxy is true and image is not stored in R2, upload image to R2
proxy &&
diff --git a/apps/web/tests/partners/queue-partner-search-sync.test.ts b/apps/web/tests/partners/queue-partner-search-sync.test.ts
index 4d0676a8b6..4604e6e99e 100644
--- a/apps/web/tests/partners/queue-partner-search-sync.test.ts
+++ b/apps/web/tests/partners/queue-partner-search-sync.test.ts
@@ -266,3 +266,56 @@ describe("queuePartnerSearchSyncForLinks", () => {
expect(mocks.dispatchBatch).not.toHaveBeenCalled();
});
});
+
+describe("queuePartnerSearchSyncForLinks — ownership transfer", () => {
+ beforeEach(() => {
+ mocks.getPartnerSearchProvider
+ .mockReset()
+ .mockReturnValue({ name: "turbopuffer" });
+ mocks.dispatchBatch.mockReset().mockResolvedValue({
+ published: 1,
+ deferred: 0,
+ failed: 0,
+ results: [],
+ });
+ });
+
+ // A link update can rewrite partnerId, so the former owner has to be
+ // re-serialized without the link. Syncing only the new owner would leave it
+ // searchable under a partner who no longer has it.
+ it("syncs both owners when a link moves between partners", async () => {
+ await queuePartnerSearchSyncForLinks([
+ { programId: "prog_1", partnerId: "pn_old" },
+ { programId: "prog_1", partnerId: "pn_new" },
+ ]);
+
+ expect(mocks.dispatchBatch.mock.calls[0][0]).toEqual([
+ {
+ type: "partners",
+ partnerIds: ["pn_old", "pn_new"],
+ programId: "prog_1",
+ },
+ ]);
+ });
+
+ it("syncs both programs when a link moves across programs", async () => {
+ await queuePartnerSearchSyncForLinks([
+ { programId: "prog_old", partnerId: "pn_1" },
+ { programId: "prog_new", partnerId: "pn_1" },
+ ]);
+
+ expect(mocks.dispatchBatch).toHaveBeenCalledTimes(2);
+ });
+
+ // An unowned link gaining a partner has no former owner to re-serialize.
+ it("skips the null side when a link gains its first owner", async () => {
+ await queuePartnerSearchSyncForLinks([
+ { programId: null, partnerId: null },
+ { programId: "prog_1", partnerId: "pn_1" },
+ ]);
+
+ expect(mocks.dispatchBatch.mock.calls[0][0]).toEqual([
+ { type: "partners", partnerIds: ["pn_1"], programId: "prog_1" },
+ ]);
+ });
+});