The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
finalize sync-click-workspaces cron
Steven Tey7768e56449b5
diff --git a/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/route.ts b/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/route.tsindex 22b582ac06..acdf767723 100644--- a/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/route.ts+++ b/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/route.ts@@ -1,9 +1,9 @@import { withCron } from "@/lib/cron/with-cron";+import { logAndRespond } from "../../utils";import {- promoteLinkWebhooksForClick,+ cleanupRedundantLinkWebhookEntries,syncClickWebhookWorkspaceSet,-} from "@/lib/webhook/click-webhook-workspaces";-import { logAndRespond } from "../../utils";+} from "./utils";export const dynamic = "force-dynamic";@@ -11,11 +11,10 @@ export const dynamic = "force-dynamic";// Rebuild the Redis set of workspaces with active link.clicked webhooks.// Runs every minute (* * * * *)export const GET = withCron(async () => {- const promoted = await promoteLinkWebhooksForClick();-const synced = await syncClickWebhookWorkspaceSet();+ const deleted = await cleanupRedundantLinkWebhookEntries();return logAndRespond(- `Synced ${synced} workspace(s) with link.clicked webhooks. Promoted ${promoted} webhooks for click.`,+ `Synced ${synced} workspace(s) with link.clicked webhooks. Deleted ${deleted} redundant LinkWebhook entries.`,);});diff --git a/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/utils.ts b/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/utils.tsnew file mode 100644index 0000000000..d8cdb2c26a--- /dev/null+++ b/apps/web/app/(ee)/api/cron/webhooks/sync-click-workspaces/utils.ts@@ -0,0 +1,75 @@+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";++const TMP_REDIS_KEY = `${REDIS_KEY}:tmp`;++// Rebuild the Redis set of workspaces with active link.clicked webhooks+export const syncClickWebhookWorkspaceSet = async () => {+ const webhooks = await prisma.webhook.findMany({+ where: {+ disabledAt: null,+ triggers: {+ array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],+ },+ project: {+ plan: {+ notIn: ["free", "pro"],+ },+ },+ },+ select: {+ projectId: true,+ },+ distinct: ["projectId"],+ });++ const workspaceIds = webhooks.map((webhook) => webhook.projectId);++ if (workspaceIds.length === 0) {+ await redis.del(REDIS_KEY);+ return 0;+ }++ await redis.del(TMP_REDIS_KEY);+ await redis.sadd(TMP_REDIS_KEY, ...(workspaceIds as [string, ...string[]]));+ await redis.rename(TMP_REDIS_KEY, REDIS_KEY);++ return workspaceIds.length;+};++// periodically remove redundant LinkWebhook entries for webhooks that are not scoped to links (folders, workspace)+// we do this in case clients are still passing webhookIds when creating links, which will create LinkWebhook entries+export const cleanupRedundantLinkWebhookEntries = async () => {+ const nonLinkScopeWebhooks = await prisma.webhook.findMany({+ where: {+ linkScope: {+ not: "links",+ },+ links: {+ some: {},+ },+ },+ });++ let deletedCount = 0;+ while (true) {+ const deleted = await prisma.linkWebhook.deleteMany({+ where: {+ webhookId: {+ in: nonLinkScopeWebhooks.map((webhook) => webhook.id),+ },+ },+ limit: 250,+ });+ deletedCount += deleted.count;+ if (deleted.count === 0) {+ console.log("No more non-link-scoped webhooks to delete");+ break;+ }+ console.log(`Deleted ${deleted.count} non-link-scoped webhooks`);+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ return deletedCount;+};diff --git a/apps/web/lib/webhook/click-webhook-workspaces.ts b/apps/web/lib/webhook/click-webhook-workspaces.tsindex 4a59398d64..07dd3ce512 100644--- a/apps/web/lib/webhook/click-webhook-workspaces.ts+++ b/apps/web/lib/webhook/click-webhook-workspaces.ts@@ -2,10 +2,8 @@ import { prisma } from "@/lib/prisma";import { redis } from "@/lib/upstash";import { LINK_CLICK_WEBHOOK_TRIGGER } from "./constants";import type { WebhookTrigger } from "./types";-import { hasLinkClickTrigger } from "./utils";export const REDIS_KEY = "webhookClickWorkspaces";-const TMP_REDIS_KEY = `${REDIS_KEY}:tmp`;class ClickWebhookWorkspaces {async add(workspaceId: string) {@@ -21,40 +19,6 @@ class ClickWebhookWorkspaces {}}-// Rebuild the Redis set of workspaces with active link.clicked webhooks.-export const syncClickWebhookWorkspaceSet = async () => {- const webhooks = await prisma.webhook.findMany({- where: {- disabledAt: null,- triggers: {- array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],- },- project: {- plan: {- notIn: ["free", "pro"],- },- },- },- select: {- projectId: true,- },- distinct: ["projectId"],- });-- const workspaceIds = webhooks.map((webhook) => webhook.projectId);-- if (workspaceIds.length === 0) {- await redis.del(REDIS_KEY);- return 0;- }-- await redis.del(TMP_REDIS_KEY);- await redis.sadd(TMP_REDIS_KEY, ...(workspaceIds as [string, ...string[]]));- await redis.rename(TMP_REDIS_KEY, REDIS_KEY);-- return workspaceIds.length;-};-export const clickWebhookWorkspaces = new ClickWebhookWorkspaces();// Synchronize the workspace's webhook status with its active webhooks.@@ -95,56 +59,3 @@ export const syncWorkspaceWebhookStatus = async (workspaceId: string) => {await clickWebhookWorkspaces.remove(workspaceId);}};--// Promotes webhooks assigned via the links API to the link.clicked trigger so-// they are picked up by the workspace click event stream delivery path.-export const promoteLinkWebhooksForClick = async () => {- const webhooks = await prisma.webhook.findMany({- where: {- disabledAt: null,- links: {- some: {},- },- NOT: {- triggers: {- array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],- },- },- },- select: {- id: true,- triggers: true,- linkScope: true,- },- take: 100,- });-- const webhooksToPromote = webhooks.filter(- (webhook) => !hasLinkClickTrigger(webhook),- );-- if (webhooksToPromote.length === 0) {- return 0;- }-- console.log(webhooksToPromote);-- await Promise.all(- webhooksToPromote.map((webhook) =>- prisma.webhook.update({- where: {- id: webhook.id,- },- data: {- triggers: [- ...((webhook.triggers as WebhookTrigger[]) ?? []),- LINK_CLICK_WEBHOOK_TRIGGER,- ],- linkScope: webhook.linkScope ?? "links",- },- }),- ),- );-- return webhooksToPromote.length;-};diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prismaindex 6ce1569298..2d311793c5 100644--- a/apps/web/prisma/schema/webhook.prisma+++ b/apps/web/prisma/schema/webhook.prisma@@ -21,7 +21,7 @@ model Webhook {url String @db.LongTextsecret Stringtriggers Json- linkScope LinkScope? // Only set for webhooks with the link.clicked trigger+ linkScope LinkScope? // Only set for webhooks with the link.clicked triggerconsecutiveFailures Int @default(0)lastFailedAt DateTime?disabledAt DateTime?diff --git a/apps/web/scripts/migrations/backfill-click-webhook-workspaces.ts b/apps/web/scripts/migrations/backfill-click-webhook-workspaces.tsdeleted file mode 100644index 02fc01f862..0000000000--- a/apps/web/scripts/migrations/backfill-click-webhook-workspaces.ts+++ /dev/null@@ -1,10 +0,0 @@-import "dotenv-flow/config";--import { syncClickWebhookWorkspaceSet } from "@/lib/webhook/click-webhook-workspaces";--async function main() {- const count = await syncClickWebhookWorkspaceSet();- console.log(`Rebuilt webhookClickWorkspaces with ${count} workspace(s).`);-}--main();diff --git a/apps/web/scripts/migrations/backfill-webhook-link-scope.ts b/apps/web/scripts/migrations/backfill-webhook-link-scope.tsdeleted file mode 100644index 9a58409bfa..0000000000--- a/apps/web/scripts/migrations/backfill-webhook-link-scope.ts+++ /dev/null@@ -1,23 +0,0 @@-import { prisma } from "@/lib/prisma";-import "dotenv-flow/config";--// Existing link.clicked webhooks are always targeted to specific links,-// so backfill their linkScope to "links".--async function main() {- const { count } = await prisma.webhook.updateMany({- where: {- linkScope: null,- triggers: {- array_contains: ["link.clicked"],- },- },- data: {- linkScope: "links",- },- });-- console.log(`Updated ${count} webhooks`);-}--main();