The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Replace webhookCache with click webhook workspace gate set
Kiran Kbf02b845267b
diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.tsindex e250e1af38..8be2eceaf0 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts@@ -10,7 +10,6 @@ import { wouldLoseAdvancedFeatures } from "@/lib/plans/would-lose-advanced-featuimport { prisma } from "@/lib/prisma";import { stripe } from "@/lib/stripe";import { recordLink } from "@/lib/tinybird";-import { webhookCache } from "@/lib/webhook/cache";import { sendEmail } from "@dub/email";import AdvancedPlanDowngradeNotice from "@dub/email/templates/advanced-plan-downgrade-notice";import { capitalize, FREE_PLAN, log } from "@dub/utils";@@ -215,22 +214,6 @@ export async function customerSubscriptionDeleted(},});- // Update the webhooks cache- const webhooks = await prisma.webhook.findMany({- where: {- projectId: workspace.id,- },- select: {- id: true,- url: true,- secret: true,- triggers: true,- disabledAt: true,- },- });-- await webhookCache.mset(webhooks);-await deleteWorkspaceFolders({workspaceId: workspace.id,defaultProgramId: workspace.defaultProgramId,diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.tsindex 7ef72a8b20..9536723db2 100644--- a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts@@ -17,7 +17,6 @@ import {getSubscriptionTrialEndsAt,} from "@/lib/stripe/workspace-subscription-fields";import { WorkspaceProps } from "@/lib/types";-import { webhookCache } from "@/lib/webhook/cache";import { sendBatchEmail } from "@dub/email";import AdvancedPlanDowngradeNotice from "@dub/email/templates/advanced-plan-downgrade-notice";import UpgradeEmail from "@dub/email/templates/upgrade-email";@@ -192,23 +191,6 @@ export async function updateWorkspacePlan({},}),]);-- // Update the webhooks cache- const webhooks = await prisma.webhook.findMany({- where: {- projectId: workspace.id,- },- select: {- id: true,- url: true,- secret: true,- triggers: true,- disabledAt: true,- },- });-- await webhookCache.mset(webhooks);- console.log(`Updated webhooks cache for workspace ${workspace.id}.`);}// Delete the folders if the new plan does not support foldersdiff --git a/apps/web/app/api/integrations/uninstall/route.ts b/apps/web/app/api/integrations/uninstall/route.tsindex a46ddb7f9b..e83903676c 100644--- a/apps/web/app/api/integrations/uninstall/route.ts+++ b/apps/web/app/api/integrations/uninstall/route.ts@@ -2,8 +2,6 @@ import { DubApiError } from "@/lib/api/errors";import { withWorkspace } from "@/lib/auth";import { slackOAuthProvider } from "@/lib/integrations/slack/oauth";import { prisma } from "@/lib/prisma";-import { webhookCache } from "@/lib/webhook/cache";-import { hasLinkClickTrigger } from "@/lib/webhook/utils";import { SLACK_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -56,10 +54,6 @@ export const DELETE = withWorkspace(...(integrationId === SLACK_INTEGRATION_ID? [slackOAuthProvider.uninstall(installation)]: []),-- ...webhooks.map((webhook) =>- hasLinkClickTrigger(webhook) ? webhookCache.delete(webhook.id) : null,- ),]),);diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.tsindex 3ffd15ae10..a8b72271a6 100644--- a/apps/web/app/api/webhooks/[webhookId]/route.ts+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts@@ -7,7 +7,7 @@ import {LINK_CLICK_WEBHOOK_TRIGGER,WebhookTrigger,} from "@/lib/webhook/constants";-import { syncWorkspaceWebhookStatus } from "@/lib/webhook/update-webhook";+import { syncWorkspaceWebhookStatus } from "@/lib/webhook/sync-webhook";import { validateWebhook } from "@/lib/webhook/validate-webhook";import { updateWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";import { arrayEqual } from "@dub/utils";@@ -117,7 +117,7 @@ export const PATCH = withWorkspace(folderIds !== undefined &&!arrayEqual(existingFolderIds, folderIds ?? []));- const webhook = await prisma.$transaction(async (tx) => {+ const updatedWebhook = await prisma.$transaction(async (tx) => {const updatedWebhook = await tx.webhook.update({where: {id: webhookId,@@ -167,7 +167,9 @@ export const PATCH = withWorkspace(return updatedWebhook;});- return NextResponse.json(WebhookSchema.parse(webhook));+ waitUntil(syncWorkspaceWebhookStatus(workspace.id));++ return NextResponse.json(WebhookSchema.parse(updatedWebhook));},{requiredPermissions: ["webhooks.write"],@@ -187,7 +189,7 @@ export const DELETE = withWorkspace(async ({ workspace, params }) => {const { webhookId } = params;- await prisma.webhook.findUniqueOrThrow({+ const existingWebhook = await prisma.webhook.findUniqueOrThrow({where: {id: webhookId,projectId: workspace.id,@@ -200,11 +202,7 @@ export const DELETE = withWorkspace(},});- waitUntil(- syncWorkspaceWebhookStatus({- workspaceId: workspace.id,- }),- );+ waitUntil(syncWorkspaceWebhookStatus(workspace.id));return NextResponse.json({id: webhookId,diff --git a/apps/web/lib/actions/enable-disable-webhook.ts b/apps/web/lib/actions/enable-disable-webhook.tsindex badcea32f9..7b8b5b7fb4 100644--- a/apps/web/lib/actions/enable-disable-webhook.ts+++ b/apps/web/lib/actions/enable-disable-webhook.ts@@ -3,8 +3,7 @@import { prisma } from "@/lib/prisma";import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";-import { webhookCache } from "../webhook/cache";-import { syncWorkspaceWebhookStatus } from "../webhook/update-webhook";+import { syncWorkspaceWebhookStatus } from "../webhook/sync-webhook";import { authActionClient } from "./safe-action";import { throwIfNoPermission } from "./throw-if-no-permission";@@ -41,7 +40,7 @@ export const enableOrDisableWebhook = authActionClientconst disabledAt = webhook.disabledAt ? null : new Date();- const updatedWebhook = await prisma.webhook.update({+ await prisma.webhook.update({where: {id: webhookId,projectId: workspace.id,@@ -51,17 +50,7 @@ export const enableOrDisableWebhook = authActionClient},});- waitUntil(- (async () => {- await Promise.all([- syncWorkspaceWebhookStatus({- workspaceId: workspace.id,- }),-- webhookCache.set(updatedWebhook),- ]);- })(),- );+ waitUntil(syncWorkspaceWebhookStatus(workspace.id));return {disabledAt,diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex 02d9842cc9..f5b2e9ec57 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -5,7 +5,6 @@ import { isNotHostedImage, storage } from "@/lib/storage";import { recordLink } from "@/lib/tinybird";import { ProcessedLinkProps } from "@/lib/types";import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams/workspace-links-usage";-import { propagateWebhookTriggerChanges } from "@/lib/webhook/update-webhook";import {APP_DOMAIN_WITH_NGROK,R2_URL,@@ -215,12 +214,6 @@ export async function createLink(link: ProcessedLinkProps) {timestamp: new Date().toISOString(),}),- // Propagate webhook trigger changes- webhookIds &&- propagateWebhookTriggerChanges({- webhookIds,- }),-// Schedule AB test completiontestVariants && testCompletedAt && scheduleABTestCompletion(response),]);diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.tsindex c9e6e47e11..6f19f679f8 100644--- a/apps/web/lib/api/links/update-link.ts+++ b/apps/web/lib/api/links/update-link.ts@@ -3,7 +3,6 @@ import { prisma } from "@/lib/prisma";import { isNotHostedImage, storage } from "@/lib/storage";import { recordLink } from "@/lib/tinybird";import { LinkProps, ProcessedLinkProps } from "@/lib/types";-import { propagateWebhookTriggerChanges } from "@/lib/webhook/update-webhook";import {R2_URL,getParamsFromURL,@@ -222,12 +221,6 @@ export async function updateLink({oldLink.image !== image &&storage.delete({ key: oldLink.image.replace(`${R2_URL}/`, "") }),- // Propagate webhook trigger changes- webhookIds != undefined &&- propagateWebhookTriggerChanges({- webhookIds,- }),-// Schedule AB test completionchangedTestCompletedAt &&testVariants &&diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex c1612cc243..c8d2c7d272 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -9,7 +9,6 @@ import { EU_COUNTRY_CODES } from "@dub/utils/src/constants/countries";import { geolocation, ipAddress, waitUntil } from "@vercel/functions";import { userAgent } from "next/server";import { recordClickCache } from "../api/links/record-click-cache";-import { ExpandedLink, transformLink } from "../api/links/utils/transform-link";import { detectBot } from "../middleware/utils/detect-bot";import { detectQr } from "../middleware/utils/detect-qr";import { getIdentityHash } from "../middleware/utils/get-identity-hash";@@ -18,9 +17,6 @@ import { WorkspaceProps } from "../types";import { redis } from "../upstash";import { publishPartnerActivityEvent } from "../upstash/redis-streams/partner-activity";import { publishWorkspaceClicksUsageEvent } from "../upstash/redis-streams/workspace-clicks-usage";-import { webhookCache } from "../webhook/cache";-import { sendWebhooks } from "../webhook/qstash";-import { transformClickEventData } from "../webhook/transform";/*** Recording clicks with geo, ua, referer and timestamp data@@ -281,9 +277,9 @@ export async function recordClick({workspaceData && workspaceData.usage >= workspaceData.usageLimit;// Send webhook events if link has webhooks enabled and the workspace usage has not exceeded the limit- if (!hasExceededUsageLimit) {- await sendLinkClickWebhooks({ webhookIds, linkId, clickData });- }+ // if (!hasExceededUsageLimit) {+ // await sendLinkClickWebhooks({ webhookIds, linkId, clickData });+ // }}})(),);@@ -291,69 +287,69 @@ export async function recordClick({return clickData;}-async function sendLinkClickWebhooks({- webhookIds,- linkId,- clickData,-}: {- webhookIds: string[];- linkId: string;- clickData: any;-}) {- const webhooks = await webhookCache.mget(webhookIds);-- // Couldn't find webhooks in the cache- // TODO: Should we look them up in the database?- if (!webhooks || webhooks.length === 0) {- return;- }-- const activeLinkWebhooks = webhooks.filter((webhook) => {- return (- !webhook.disabledAt &&- webhook.triggers &&- Array.isArray(webhook.triggers) &&- webhook.triggers.includes("link.clicked")- );- });-- if (activeLinkWebhooks.length === 0) {- return;- }-- const link = await conn- .execute(- `- SELECT- l.*,- JSON_ARRAYAGG(- IF(t.id IS NOT NULL,- JSON_OBJECT('tag', JSON_OBJECT('id', t.id, 'name', t.name, 'color', t.color)),- NULL- )- ) as tags- FROM Link l- LEFT JOIN LinkTag lt ON l.id = lt.linkId- LEFT JOIN Tag t ON lt.tagId = t.id- WHERE l.id = ?- GROUP BY l.id- `,- [linkId],- )- .then((res) => {- const row = res.rows[0] as any;- // Handle case where there are no tags (JSON_ARRAYAGG returns [null])- row.tags = row.tags?.[0] === null ? [] : row.tags;- return row;- });-- await sendWebhooks({- trigger: "link.clicked",- webhooks: activeLinkWebhooks,- // @ts-ignore – bot & qr should be boolean- data: transformClickEventData({- ...clickData,- link: transformLink(link as ExpandedLink),- }),- });-}+// async function sendLinkClickWebhooks({+// webhookIds,+// linkId,+// clickData,+// }: {+// webhookIds: string[];+// linkId: string;+// clickData: any;+// }) {+// const webhooks = await webhookCache.mget(webhookIds);++// // Couldn't find webhooks in the cache+// // TODO: Should we look them up in the database?+// if (!webhooks || webhooks.length === 0) {+// return;+// }++// const activeLinkWebhooks = webhooks.filter((webhook) => {+// return (+// !webhook.disabledAt &&+// webhook.triggers &&+// Array.isArray(webhook.triggers) &&+// webhook.triggers.includes("link.clicked")+// );+// });++// if (activeLinkWebhooks.length === 0) {+// return;+// }++// const link = await conn+// .execute(+// `+// SELECT+// l.*,+// JSON_ARRAYAGG(+// IF(t.id IS NOT NULL,+// JSON_OBJECT('tag', JSON_OBJECT('id', t.id, 'name', t.name, 'color', t.color)),+// NULL+// )+// ) as tags+// FROM Link l+// LEFT JOIN LinkTag lt ON l.id = lt.linkId+// LEFT JOIN Tag t ON lt.tagId = t.id+// WHERE l.id = ?+// GROUP BY l.id+// `,+// [linkId],+// )+// .then((res) => {+// const row = res.rows[0] as any;+// // Handle case where there are no tags (JSON_ARRAYAGG returns [null])+// row.tags = row.tags?.[0] === null ? [] : row.tags;+// return row;+// });++// await sendWebhooks({+// trigger: "link.clicked",+// webhooks: activeLinkWebhooks,+// // @ts-ignore – bot & qr should be boolean+// data: transformClickEventData({+// ...clickData,+// link: transformLink(link as ExpandedLink),+// }),+// });+// }diff --git a/apps/web/lib/webhook/cache.ts b/apps/web/lib/webhook/cache.tsindex ececec4731..d0573865b7 100644--- a/apps/web/lib/webhook/cache.ts+++ b/apps/web/lib/webhook/cache.ts@@ -1,72 +1,72 @@-import { redis } from "@/lib/upstash";-import { WebhookCacheProps } from "../types";-import { hasLinkClickTrigger } from "./utils";--const WEBHOOK_CACHE_KEY_PREFIX = "webhook";--class WebhookCache {- async mset(webhooks: WebhookCacheProps[]) {- if (webhooks.length === 0) {- return;- }-- const pipeline = redis.pipeline();-- webhooks.map((webhook) => {- pipeline.set(this._createKey(webhook.id), this._format(webhook));- });-- return await pipeline.exec();- }-- async set(webhook: WebhookCacheProps) {- // We only cache the link level webhooks for now- if (!hasLinkClickTrigger(webhook)) {- return;- }-- return await redis.set(this._createKey(webhook.id), this._format(webhook));- }-- async mget(webhookIds: string[]) {- const webhooks = await redis.mget<WebhookCacheProps[]>(- webhookIds.map(this._createKey),- );-- return webhooks.filter(Boolean);- }-- async delete(webhookId: string) {- return await redis.del(this._createKey(webhookId));- }-- async deleteMany(webhookIds: string[]) {- if (webhookIds.length === 0) {- return;- }-- const pipeline = redis.pipeline();-- webhookIds.map((webhookId) => {- pipeline.del(this._createKey(webhookId));- });-- return await pipeline.exec();- }-- _format(webhook: WebhookCacheProps) {- return {- id: webhook.id,- url: webhook.url,- secret: webhook.secret,- triggers: webhook.triggers,- ...(webhook.disabledAt ? { disabledAt: webhook.disabledAt } : {}),- };- }-- _createKey(webhookId: string) {- return `${WEBHOOK_CACHE_KEY_PREFIX}:${webhookId}`;- }-}--export const webhookCache = new WebhookCache();+// import { redis } from "@/lib/upstash";+// import { WebhookCacheProps } from "../types";+// import { hasLinkClickTrigger } from "./utils";++// const WEBHOOK_CACHE_KEY_PREFIX = "webhook";++// class WebhookCache {+// async mset(webhooks: WebhookCacheProps[]) {+// if (webhooks.length === 0) {+// return;+// }++// const pipeline = redis.pipeline();++// webhooks.map((webhook) => {+// pipeline.set(this._createKey(webhook.id), this._format(webhook));+// });++// return await pipeline.exec();+// }++// async set(webhook: WebhookCacheProps) {+// // We only cache the link level webhooks for now+// if (!hasLinkClickTrigger(webhook)) {+// return;+// }++// return await redis.set(this._createKey(webhook.id), this._format(webhook));+// }++// async mget(webhookIds: string[]) {+// const webhooks = await redis.mget<WebhookCacheProps[]>(+// webhookIds.map(this._createKey),+// );++// return webhooks.filter(Boolean);+// }++// async delete(webhookId: string) {+// return await redis.del(this._createKey(webhookId));+// }++// async deleteMany(webhookIds: string[]) {+// if (webhookIds.length === 0) {+// return;+// }++// const pipeline = redis.pipeline();++// webhookIds.map((webhookId) => {+// pipeline.del(this._createKey(webhookId));+// });++// return await pipeline.exec();+// }++// _format(webhook: WebhookCacheProps) {+// return {+// id: webhook.id,+// url: webhook.url,+// secret: webhook.secret,+// triggers: webhook.triggers,+// ...(webhook.disabledAt ? { disabledAt: webhook.disabledAt } : {}),+// };+// }++// _createKey(webhookId: string) {+// return `${WEBHOOK_CACHE_KEY_PREFIX}:${webhookId}`;+// }+// }++// export const webhookCache = new WebhookCache();diff --git a/apps/web/lib/webhook/click-webhook-workspaces.ts b/apps/web/lib/webhook/click-webhook-workspaces.tsnew file mode 100644index 0000000000..a19a10f4a2--- /dev/null+++ b/apps/web/lib/webhook/click-webhook-workspaces.ts@@ -0,0 +1,15 @@+import { redis } from "@/lib/upstash";++export const REDIS_KEY = "webhookClickWorkspaces";++class ClickWebhookWorkspaces {+ async set(workspaceId: string): Promise<void> {+ await redis.sadd(REDIS_KEY, workspaceId);+ }++ async remove(workspaceId: string): Promise<void> {+ await redis.srem(REDIS_KEY, workspaceId);+ }+}++export const clickWebhookWorkspaces = new ClickWebhookWorkspaces();diff --git a/apps/web/lib/webhook/create-webhook.ts b/apps/web/lib/webhook/create-webhook.tsindex c77d877992..bf682bbf49 100644--- a/apps/web/lib/webhook/create-webhook.ts+++ b/apps/web/lib/webhook/create-webhook.ts@@ -6,6 +6,7 @@ import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { createWebhookSchema } from "../zod/schemas/webhooks";import { createWebhookSecret } from "./secret";+import { syncWorkspaceWebhookStatus } from "./sync-webhook";export async function createWebhook({name,@@ -70,11 +71,7 @@ export async function createWebhook({},});- waitUntil(- (async () => {- //- })(),- );+ waitUntil(syncWorkspaceWebhookStatus(workspace.id));return webhook;}diff --git a/apps/web/lib/webhook/failure.ts b/apps/web/lib/webhook/failure.tsindex a653c8d4c9..073266c33b 100644--- a/apps/web/lib/webhook/failure.ts+++ b/apps/web/lib/webhook/failure.ts@@ -3,12 +3,11 @@ import { sendEmail } from "@dub/email";import WebhookDisabled from "@dub/email/templates/webhook-disabled";import WebhookFailed from "@dub/email/templates/webhook-failed";import { Webhook } from "@prisma/client";-import { webhookCache } from "./cache";import {WEBHOOK_FAILURE_DISABLE_THRESHOLD,WEBHOOK_FAILURE_NOTIFY_THRESHOLDS,} from "./constants";-import { syncWorkspaceWebhookStatus } from "./update-webhook";+import { syncWorkspaceWebhookStatus } from "./sync-webhook";export const handleWebhookFailure = async (webhookId: string) => {const webhook = await prisma.webhook.update({@@ -57,13 +56,8 @@ export const handleWebhookFailure = async (webhookId: string) => {// Notify the usernotifyWebhookDisabled(updatedWebhook),- // Update the webhook cache- webhookCache.set(updatedWebhook),-// Update the project webhookEnabled flag- syncWorkspaceWebhookStatus({- workspaceId: webhook.projectId,- }),+ syncWorkspaceWebhookStatus(webhook.projectId),]);}};diff --git a/apps/web/lib/webhook/sync-webhook.ts b/apps/web/lib/webhook/sync-webhook.tsnew file mode 100644index 0000000000..03f6fd4466--- /dev/null+++ b/apps/web/lib/webhook/sync-webhook.ts@@ -0,0 +1,37 @@+import { prisma } from "@/lib/prisma";+import { clickWebhookWorkspaces } from "./click-webhook-workspaces";+import { LINK_CLICK_WEBHOOK_TRIGGER, WebhookTrigger } from "./constants";++// Synchronize the workspace's webhook status with its active webhooks.+export const syncWorkspaceWebhookStatus = async (workspaceId: string) => {+ const activeWebhooks = await prisma.webhook.findMany({+ where: {+ projectId: workspaceId,+ disabledAt: null,+ },+ select: {+ triggers: true,+ },+ });++ await prisma.project.update({+ where: {+ id: workspaceId,+ },+ data: {+ webhookEnabled: activeWebhooks.length > 0,+ },+ });++ const linkClickWebhooks = activeWebhooks.filter((webhook) =>+ (webhook.triggers as WebhookTrigger[])?.includes(+ LINK_CLICK_WEBHOOK_TRIGGER,+ ),+ );++ if (linkClickWebhooks.length > 0) {+ await clickWebhookWorkspaces.set(workspaceId);+ } else {+ await clickWebhookWorkspaces.remove(workspaceId);+ }+};diff --git a/apps/web/lib/webhook/update-webhook.ts b/apps/web/lib/webhook/update-webhook.tsdeleted file mode 100644index a3dc5a80d5..0000000000--- a/apps/web/lib/webhook/update-webhook.ts+++ /dev/null@@ -1,118 +0,0 @@-import { prisma } from "@/lib/prisma";-import { webhookCache } from "./cache";--// Synchronize the workspace's webhook status with its active webhooks.-export const syncWorkspaceWebhookStatus = async ({- workspaceId,-}: {- workspaceId: string;-}) => {- const activeWebhooksCount = await prisma.webhook.count({- where: {- projectId: workspaceId,- disabledAt: null,- },- });-- await prisma.project.update({- where: {- id: workspaceId,- },- data: {- webhookEnabled: activeWebhooksCount > 0,- },- });-};--// Propagate webhook trigger changes to the webhook cache-export const propagateWebhookTriggerChanges = async ({- webhookIds,-}: {- webhookIds: string[] | undefined;-}) => {- if (!webhookIds) {- return;- }-- const webhooks = await prisma.webhook.findMany({- where: {- id: {- in: webhookIds,- },- },- select: {- id: true,- triggers: true,- linkScope: true,- url: true,- secret: true,- disabledAt: true,- _count: {- select: {- links: true,- },- },- },- });-- // Promote to "links" scope: a webhook that now has links but isn't a link.clicked webhook yet- const promotedWebhooks = webhooks.filter(- (webhook) =>- webhook._count.links > 0 &&- !(webhook.triggers as string[])?.includes("link.clicked"),- );-- // Add the link.clicked trigger + links scope to the webhook and cache it- if (promotedWebhooks.length > 0) {- const toUpdate = promotedWebhooks.map((webhook) => ({- ...webhook,- triggers: [...(webhook.triggers as string[]), "link.clicked"],- }));-- await Promise.all([- ...promotedWebhooks.map((webhook) =>- prisma.webhook.update({- where: {- id: webhook.id,- },- data: {- triggers: [...(webhook.triggers as string[]), "link.clicked"],- linkScope: "links",- },- }),- ),-- webhookCache.mset(toUpdate),- ]);- }-- // Demote to workspace level: a "links" scope webhook that no longer has any links.- // "all" / "folders" scope webhooks intentionally have no links, so they're never demoted.- const demotedWebhooks = webhooks.filter(- (webhook) =>- webhook._count.links === 0 &&- webhook.linkScope !== "all" &&- webhook.linkScope !== "folders" &&- (webhook.triggers as string[])?.includes("link.clicked"),- );-- if (demotedWebhooks.length > 0) {- await Promise.all([- ...demotedWebhooks.map((webhook) =>- prisma.webhook.update({- where: {- id: webhook.id,- },- data: {- triggers: (webhook.triggers as string[]).filter(- (trigger) => trigger !== "link.clicked",- ),- linkScope: null,- },- }),- ),-- webhookCache.deleteMany(demotedWebhooks.map((webhook) => webhook.id)),- ]);- }-};diff --git a/apps/web/scripts/migrations/backfill-click-webhook-workspaces.ts b/apps/web/scripts/migrations/backfill-click-webhook-workspaces.tsnew file mode 100644index 0000000000..2bdd345e25--- /dev/null+++ b/apps/web/scripts/migrations/backfill-click-webhook-workspaces.ts@@ -0,0 +1,32 @@+import { prisma } from "@/lib/prisma";+import { redis } from "@/lib/upstash";+import { REDIS_KEY } from "@/lib/webhook/click-webhook-workspaces";+import { LINK_CLICK_WEBHOOK_TRIGGER } from "@/lib/webhook/constants";+import "dotenv-flow/config";++async function main() {+ const webhooks = await prisma.webhook.findMany({+ where: {+ triggers: {+ array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],+ },+ },+ select: {+ projectId: true,+ },+ distinct: ["projectId"],+ });++ const workspaceIds = webhooks.map((webhook) => webhook.projectId);++ if (workspaceIds.length === 0) {+ console.log("No workspaces with link.clicked webhooks found.");+ return;+ }++ await redis.sadd(REDIS_KEY, ...(workspaceIds as [string, ...string[]]));++ console.log(`Added ${workspaceIds.length} workspace(s) to ${REDIS_KEY}.`);+}++main();