The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Deliver link.clicked webhooks from Redis stream via cron
Kiran Kb74911e581e2
diff --git a/apps/web/app/(ee)/api/cron/streams/send-link-click-webhooks/route.ts b/apps/web/app/(ee)/api/cron/streams/send-link-click-webhooks/route.tsnew file mode 100644index 0000000000..82dbec848f--- /dev/null+++ b/apps/web/app/(ee)/api/cron/streams/send-link-click-webhooks/route.ts@@ -0,0 +1,283 @@+import { transformLink } from "@/lib/api/links/utils/transform-link";+import { withCron } from "@/lib/cron/with-cron";+import { prisma } from "@/lib/prisma";+import { ClickEventTB } from "@/lib/types";+import { RedisStreamEntry } from "@/lib/upstash/redis-streams/client";+import { workspaceClickEventStream } from "@/lib/upstash/redis-streams/workspace-click-events";+import { LINK_CLICK_WEBHOOK_TRIGGER } from "@/lib/webhook/constants";+import { sendWebhooks } from "@/lib/webhook/qstash";+import { transformClickEventData } from "@/lib/webhook/transform";+import { chunk, groupBy } from "@dub/utils";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++// How many stream entries to drain per run+const BATCH_SIZE = 1000;++// How many webhook deliveries to enqueue to QStash in parallel+const SEND_CONCURRENCY = 50;++// Drains the workspace:click:events stream and delivers link.clicked webhooks.+// Runs every minute (see vercel.json).+export const GET = withCron(async () => {+ const { processed, sent, failed, processedEntryIds } =+ await processStreamBatch();++ const streamInfo = await workspaceClickEventStream.getStreamInfo();++ console.log({+ processed,+ sent,+ failed,+ processedEntryIds,+ streamInfo,+ });++ return NextResponse.json("Finished processing stream.");+});++const processStreamBatch = (): Promise<{+ processed: number;+ sent: number;+ failed: number;+ processedEntryIds: string[];+}> =>+ workspaceClickEventStream.processBatch<ClickEventTB>(+ async (entries) => {+ if (!entries || entries.length === 0) {+ return {+ processed: 0,+ sent: 0,+ failed: 0,+ processedEntryIds: [],+ };+ }++ const workspaceIds = [+ ...new Set(entries.map((e) => e.data.workspace_id).filter(Boolean)),+ ];+ const linkIds = [+ ...new Set(entries.map((e) => e.data.link_id).filter(Boolean)),+ ];++ const [webhooks, projects, links] = await Promise.all([+ prisma.webhook.findMany({+ where: {+ projectId: {+ in: workspaceIds,+ },+ disabledAt: null,+ triggers: {+ array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],+ },+ },+ select: {+ id: true,+ url: true,+ secret: true,+ linkTarget: true,+ projectId: true,+ },+ }),++ prisma.project.findMany({+ where: {+ id: {+ in: workspaceIds,+ },+ },+ select: {+ id: true,+ usage: true,+ usageLimit: true,+ },+ }),++ prisma.link.findMany({+ where: {+ id: {+ in: linkIds,+ },+ },+ include: {+ tags: {+ select: {+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+ },+ }),+ ]);++ const linkTargetWebhookIds = webhooks+ .filter((w) => w.linkTarget === "links")+ .map((w) => w.id);++ const folderTargetWebhookIds = webhooks+ .filter((w) => w.linkTarget === "folders")+ .map((w) => w.id);++ const folderIds = [+ ...new Set(+ links.map((l) => l.folderId).filter((id): id is string => id != null),+ ),+ ];++ const [linkWebhooks, folderWebhooks] = await Promise.all([+ linkTargetWebhookIds.length > 0 && linkIds.length > 0+ ? prisma.linkWebhook.findMany({+ where: {+ webhookId: {+ in: linkTargetWebhookIds,+ },+ linkId: {+ in: linkIds,+ },+ },+ select: {+ webhookId: true,+ linkId: true,+ },+ })+ : Promise.resolve([]),++ folderTargetWebhookIds.length > 0 && folderIds.length > 0+ ? prisma.folderWebhook.findMany({+ where: {+ webhookId: {+ in: folderTargetWebhookIds,+ },+ folderId: {+ in: folderIds,+ },+ },+ select: {+ webhookId: true,+ folderId: true,+ },+ })+ : Promise.resolve([]),+ ]);++ const linkWebhooksByLinkId = groupBy(linkWebhooks, (r) => r.linkId);+ const folderWebhooksByFolderId = groupBy(+ folderWebhooks,+ (r) => r.folderId,+ );+ const webhooksByWorkspace = groupBy(webhooks, (w) => w.projectId);+ const workspaceById = new Map(projects.map((p) => [p.id, p]));+ const linkById = new Map(links.map((l) => [l.id, l]));++ const sendTasks: {+ entryId: string;+ task: () => Promise<boolean>;+ }[] = [];+ const processedEntryIds: string[] = [];++ for (const entry of entries as RedisStreamEntry<ClickEventTB>[]) {+ const event = entry.data;+ const workspaceWebhooks = webhooksByWorkspace[event.workspace_id] ?? [];++ if (workspaceWebhooks.length === 0) {+ processedEntryIds.push(entry.id);+ continue;+ }++ const workspace = workspaceById.get(event.workspace_id);+ if (!workspace || workspace.usage >= workspace.usageLimit) {+ processedEntryIds.push(entry.id);+ continue;+ }++ const link = linkById.get(event.link_id);+ if (!link) {+ processedEntryIds.push(entry.id);+ continue;+ }++ const applicableWebhooks = workspaceWebhooks.filter((webhook) => {+ if (webhook.linkTarget === "workspace") {+ return true;+ }++ if (webhook.linkTarget === "links") {+ return (+ linkWebhooksByLinkId[event.link_id]?.some(+ (r) => r.webhookId === webhook.id,+ ) ?? false+ );+ }++ if (webhook.linkTarget === "folders") {+ return (+ link.folderId != null &&+ folderWebhooksByFolderId[link.folderId]?.some(+ (r) => r.webhookId === webhook.id,+ )+ );+ }++ return false;+ });++ if (applicableWebhooks.length === 0) {+ processedEntryIds.push(entry.id);+ continue;+ }++ sendTasks.push({+ entryId: entry.id,+ task: async () => {+ try {+ const results = await sendWebhooks({+ trigger: LINK_CLICK_WEBHOOK_TRIGGER,+ webhooks: applicableWebhooks,+ data: transformClickEventData({+ ...event,+ link: transformLink(link),+ }),+ });++ return results.every((r) => r.ok);+ } catch (error) {+ return false;+ }+ },+ });+ }++ let sent = 0;+ let failed = 0;++ for (const batch of chunk(sendTasks, SEND_CONCURRENCY)) {+ const results = await Promise.all(batch.map(({ task }) => task()));++ batch.forEach(({ entryId }, i) => {+ if (results[i]) {+ processedEntryIds.push(entryId);+ sent++;+ } else {+ failed++;+ }+ });+ }++ return {+ processed: processedEntryIds.length,+ sent,+ failed,+ processedEntryIds,+ };+ },+ {+ count: BATCH_SIZE,+ deleteAfterRead: true,+ },+ );diff --git a/apps/web/app/api/webhooks/[webhookId]/folders/route.ts b/apps/web/app/api/webhooks/[webhookId]/folders/route.tsindex 0811b789ee..99d82d4946 100644--- a/apps/web/app/api/webhooks/[webhookId]/folders/route.ts+++ b/apps/web/app/api/webhooks/[webhookId]/folders/route.ts@@ -1,5 +1,6 @@import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";+import { MAX_WEBHOOK_FOLDERS } from "@/lib/webhook/constants";import { NextResponse } from "next/server";// GET /api/webhooks/[webhookId]/folders@@ -23,7 +24,7 @@ export const GET = withWorkspace(async ({ workspace, params }) => {select: {folderId: true,},- take: 1000,+ take: MAX_WEBHOOK_FOLDERS,});return NextResponse.json(folders.map(({ folderId }) => folderId));diff --git a/apps/web/lib/webhook/click-webhook-workspaces.ts b/apps/web/lib/webhook/click-webhook-workspaces.tsindex 514186486f..2a4dc7f65c 100644--- a/apps/web/lib/webhook/click-webhook-workspaces.ts+++ b/apps/web/lib/webhook/click-webhook-workspaces.ts@@ -62,6 +62,11 @@ export const syncWorkspaceWebhookStatus = async (workspaceId: string) => {where: {projectId: workspaceId,disabledAt: null,+ project: {+ plan: {+ notIn: ["free", "pro"],+ },+ },},select: {triggers: true,diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.tsindex 3bef55b543..423bfb1b88 100644--- a/apps/web/lib/webhook/constants.ts+++ b/apps/web/lib/webhook/constants.ts@@ -73,3 +73,5 @@ export const WEBHOOK_TRIGGER_DESCRIPTIONS: Record<WebhookTrigger, string> = {export const WEBHOOK_FAILURE_NOTIFY_THRESHOLDS = [5, 10, 15] as const;export const WEBHOOK_FAILURE_DISABLE_THRESHOLD = 20 as const;++export const MAX_WEBHOOK_FOLDERS = 100 as const;diff --git a/apps/web/lib/webhook/create-webhook.ts b/apps/web/lib/webhook/create-webhook.tsindex ab69c700cd..7db85c8829 100644--- a/apps/web/lib/webhook/create-webhook.ts+++ b/apps/web/lib/webhook/create-webhook.ts@@ -4,9 +4,10 @@ import { WEBHOOK_ID_PREFIX } from "@/lib/webhook/constants";import { Project, WebhookReceiver } from "@prisma/client";import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";+import { getPlanCapabilities } from "../plan-capabilities";import { createWebhookSchema } from "../zod/schemas/webhooks";-import { createWebhookSecret } from "./secret";import { syncWorkspaceWebhookStatus } from "./click-webhook-workspaces";+import { createWebhookSecret } from "./secret";export async function createWebhook({name,@@ -26,7 +27,9 @@ export async function createWebhook({secret?: string;}) {// Webhooks are only supported on Business plans and above- if (["free", "pro"].includes(workspace.plan)) {+ const { canCreateWebhooks } = getPlanCapabilities(workspace.plan);++ if (!canCreateWebhooks) {return;}diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.tsindex f246ac75f1..e10de21b0e 100644--- a/apps/web/lib/webhook/qstash.ts+++ b/apps/web/lib/webhook/qstash.ts@@ -6,12 +6,19 @@ import * as z from "zod/v4";import { formatEventForSegment } from "../integrations/segment/transform";import { createSegmentBasicAuthHeader } from "../integrations/segment/utils";import { formatEventForSlack } from "../integrations/slack/transform";-import type { WebhookTrigger } from "./types";import { createWebhookSignature } from "./signature";import { prepareWebhookPayload } from "./transform";+import type { WebhookTrigger } from "./types";import { WebhookEventPayload } from "./types";import { identifyWebhookReceiver } from "./utils";+export type WebhookEnqueueResult = {+ webhookId: string;+ ok: boolean;+ messageId?: string;+ error?: unknown;+};+// Send webhooks to multiple webhooksexport const sendWebhooks = async ({webhooks,@@ -21,18 +28,34 @@ export const sendWebhooks = async ({webhooks: Pick<Webhook, "id" | "url" | "secret">[];trigger: WebhookTrigger;data: WebhookEventPayload;-}) => {+}): Promise<WebhookEnqueueResult[]> => {if (webhooks.length === 0) {- return;+ return [];}const payload = prepareWebhookPayload(trigger, data);- return await Promise.all(+ const results = await Promise.allSettled(webhooks.map((webhook) =>publishWebhookEventToQStash({ webhook, payload }),),);++ return results.map((result, i) => {+ if (result.status === "fulfilled") {+ return {+ webhookId: webhooks[i].id,+ ok: true,+ messageId: result.value.messageId,+ };+ }++ return {+ webhookId: webhooks[i].id,+ ok: false,+ error: result.reason,+ };+ });};// publish webhook event to QStash@@ -89,7 +112,7 @@ const publishWebhookEventToQStash = async ({});if (!response.messageId) {- console.error("Failed to publish webhook event to QStash", response);+ throw new Error("Failed to publish webhook event to QStash");}if (process.env.NODE_ENV === "development") {diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex f9b5366847..17830919b2 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -1,4 +1,4 @@-import { WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";+import { MAX_WEBHOOK_FOLDERS, WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";import { WebhookTrigger } from "@/lib/webhook/types";import { LinkTarget } from "@prisma/client";import * as z from "zod/v4";@@ -80,7 +80,9 @@ export const createWebhookSchemaBase = z.object({.nullish(),folderIds: z.array(z.string())- .max(1000, { error: "You can only select up to 1000 folders." })+ .max(MAX_WEBHOOK_FOLDERS, {+ error: `You can only select up to ${MAX_WEBHOOK_FOLDERS} folders.`,+ }).nullish(),});diff --git a/apps/web/tests/webhooks/index.test.ts b/apps/web/tests/webhooks/index.test.tsindex da49eba255..39864ea072 100644--- a/apps/web/tests/webhooks/index.test.ts+++ b/apps/web/tests/webhooks/index.test.ts@@ -1,5 +1,4 @@import { qstash } from "@/lib/cron";-import type { WebhookTrigger } from "@/lib/webhook/types";import { WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";import { sendWebhooks } from "@/lib/webhook/qstash";import { samplePayload } from "@/lib/webhook/sample-events/payload";@@ -8,6 +7,7 @@ import {leadWebhookEventSchema,saleWebhookEventSchema,} from "@/lib/webhook/schemas";+import type { WebhookTrigger } from "@/lib/webhook/types";import { BountySchema } from "@/lib/zod/schemas/bounties";import { CommissionWebhookSchema } from "@/lib/zod/schemas/commissions";import { CustomerSchema } from "@/lib/zod/schemas/customers";@@ -102,17 +102,18 @@ describe("Webhooks", () => {const testWebhookEvent = async (trigger: WebhookTrigger) => {const data = samplePayload[trigger];- const response = await sendWebhooks({+ const results = await sendWebhooks({webhooks: [webhook],trigger,data,});- if (!response) {+ const result = results[0];+ if (!result?.ok || !result.messageId) {throw new Error("No response from sendWebhooks");}- await assertQstashMessage(response[0].messageId, data, trigger);+ await assertQstashMessage(result.messageId, data, trigger);};const assertQstashMessage = async (diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex a4a0070c35..fb6e395434 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -20,6 +20,10 @@"path": "/api/cron/streams/update-workspace-clicks","schedule": "* * * * *"},+ {+ "path": "/api/cron/streams/send-link-click-webhooks",+ "schedule": "* * * * *"+ },{"path": "/api/cron/streams/update-workspace-links-usage","schedule": "* * * * *"