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.

Webhook delivery failure notification

Kiran K8fb0e786d9f6
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 782dd6802b..3891e1d73f 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -124,6 +124,7 @@ export const PATCH = withWorkspace(
url: true,
secret: true,
triggers: true,
+ disabled: true,
links: {
select: {
linkId: true,
diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.ts
index c630ad2190..55620903f8 100644
--- a/apps/web/app/api/webhooks/callback/route.ts
+++ b/apps/web/app/api/webhooks/callback/route.ts
@@ -1,5 +1,10 @@
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { prisma } from "@/lib/prisma";
import { recordWebhookEvent } from "@/lib/tinybird/record-webhook-event";
+import {
+ handleWebhookFailure,
+ resetWebhookFailureCount,
+} from "@/lib/webhook/failure";
import { webhookPayloadSchema } from "@/lib/webhook/schemas";
import { webhookCallbackSchema } from "@/lib/zod/schemas/webhooks";
import { getSearchParams } from "@dub/utils";
@@ -10,9 +15,20 @@ export const POST = async (req: Request) => {
await verifyQstashSignature(req, rawBody);
- const { url, status, body, sourceBody, sourceMessageId } =
+ const { url, status, body, sourceBody, sourceMessageId, retried } =
webhookCallbackSchema.parse(rawBody);
+ const { webhookId } = getSearchParams(req.url);
+
+ const webhook = await prisma.webhook.findUnique({
+ where: { id: webhookId },
+ });
+
+ if (!webhook) {
+ console.error("Webhook not found", { webhookId });
+ return new Response("Webhook not found");
+ }
+
const request = Buffer.from(sourceBody, "base64").toString("utf-8");
const response = Buffer.from(body, "base64").toString("utf-8");
@@ -20,18 +36,29 @@ export const POST = async (req: Request) => {
JSON.parse(request),
);
- const { webhookId } = getSearchParams(req.url);
+ const isFailed = status >= 400;
- await recordWebhookEvent({
- url,
- event,
- event_id: eventId,
- http_status: status,
- webhook_id: webhookId,
- request_body: request,
- response_body: response,
- message_id: sourceMessageId,
- });
+ await Promise.all([
+ // Record the webhook event
+ recordWebhookEvent({
+ url,
+ event,
+ event_id: eventId,
+ http_status: status,
+ webhook_id: webhookId,
+ request_body: request,
+ response_body: response,
+ message_id: sourceMessageId,
+ }),
+
+ // Handle the webhook delivery failure if it's the last retry
+ ...(isFailed ? [handleWebhookFailure(webhookId)] : []),
+
+ // Only reset if there were previous failures
+ ...(webhook.consecutiveFailures > 0 && !isFailed
+ ? [resetWebhookFailureCount(webhookId)]
+ : []),
+ ]);
return new Response("OK");
};
diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts
index cdd299ee35..8ff0aa4314 100644
--- a/apps/web/app/api/webhooks/route.ts
+++ b/apps/web/app/api/webhooks/route.ts
@@ -115,6 +115,7 @@ export const POST = withWorkspace(
secret: true,
triggers: true,
links: true,
+ disabled: true,
},
});
diff --git a/apps/web/emails/webhook-disabled.tsx b/apps/web/emails/webhook-disabled.tsx
new file mode 100644
index 0000000000..62fb0684f7
--- /dev/null
+++ b/apps/web/emails/webhook-disabled.tsx
@@ -0,0 +1,74 @@
+import { DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import Footer from "./components/footer";
+
+export default function WebhookDisabled({
+ email = "[email protected]",
+ workspace = {
+ name: "Acme, Inc",
+ slug: "acme",
+ },
+ webhook = {
+ id: "wh_tYedrqsWgNJxUwQOaAnupcUJ1",
+ url: "https://example.com/webhook",
+ },
+}: {
+ email: string;
+ workspace: {
+ name: string;
+ slug: string;
+ };
+ webhook: {
+ id: string;
+ url: string;
+ };
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Webhook has been disabled</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={DUB_WORDMARK}
+ height="40"
+ alt="Dub.co"
+ className="mx-auto my-0"
+ />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Webhook has been disabled
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ The webhook <strong>{webhook.url}</strong> has been disabled due
+ to several failed delivery attempts.
+ </Text>
+ <Section className="mb-8 mt-4 text-center">
+ <Link
+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={`https://app.dub.co/${workspace.slug}/settings/webhooks/${webhook.id}/edit`}
+ >
+ Edit Webhook
+ </Link>
+ </Section>
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 75c5dc638a..ea6102f855 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -251,7 +251,7 @@ export type WebhookEventProps = z.infer<typeof webhookEventSchemaTB>;
export type WebhookCacheProps = Pick<
Webhook,
- "id" | "url" | "secret" | "triggers"
+ "id" | "url" | "secret" | "triggers" | "disabled"
>;
export type TrackCustomerResponse = z.infer<typeof trackCustomerResponseSchema>;
diff --git a/apps/web/lib/webhook/cache.ts b/apps/web/lib/webhook/cache.ts
index 410e789997..e91481d6c2 100644
--- a/apps/web/lib/webhook/cache.ts
+++ b/apps/web/lib/webhook/cache.ts
@@ -36,6 +36,7 @@ class WebhookCache {
url: webhook.url,
secret: webhook.secret,
triggers: webhook.triggers,
+ disabled: webhook.disabled,
};
}
}
diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.ts
index b249eeca60..f12a6d9a3d 100644
--- a/apps/web/lib/webhook/constants.ts
+++ b/apps/web/lib/webhook/constants.ts
@@ -31,3 +31,5 @@ export const WEBHOOK_TRIGGER_DESCRIPTIONS = {
"lead.created": "Lead created",
"sale.created": "Sale created",
} as const;
+
+export const WEBHOOK_FAILURE_NOTIFY_THRESHOLD = 20;
diff --git a/apps/web/lib/webhook/failure.ts b/apps/web/lib/webhook/failure.ts
new file mode 100644
index 0000000000..361dd8b7e1
--- /dev/null
+++ b/apps/web/lib/webhook/failure.ts
@@ -0,0 +1,105 @@
+import { Webhook } from "@prisma/client";
+import { sendEmail } from "emails";
+import WebhookDisabled from "emails/webhook-disabled";
+import { prisma } from "../prisma";
+import { webhookCache } from "./cache";
+import { WEBHOOK_FAILURE_NOTIFY_THRESHOLD } from "./constants";
+
+export const handleWebhookFailure = async (webhookId: string) => {
+ const webhook = await prisma.webhook.update({
+ where: { id: webhookId },
+ data: {
+ consecutiveFailures: { increment: 1 },
+ lastFailedAt: new Date(),
+ },
+ select: {
+ id: true,
+ url: true,
+ secret: true,
+ triggers: true,
+ disabled: true,
+ consecutiveFailures: true,
+ lastFailedAt: true,
+ projectId: true,
+ },
+ });
+
+ if (webhook.disabled) {
+ return;
+ }
+
+ const failureThresholdReached =
+ webhook.consecutiveFailures >= WEBHOOK_FAILURE_NOTIFY_THRESHOLD;
+
+ if (failureThresholdReached) {
+ await Promise.allSettled([
+ // Disable the webhook
+ prisma.webhook.update({
+ where: { id: webhookId },
+ data: {
+ disabled: true,
+ },
+ }),
+
+ // Notify the user
+ sendFailureNotification(webhook),
+
+ // Update the webhook cache
+ webhookCache.set({ ...webhook, disabled: true }),
+ ]);
+ }
+};
+
+export const resetWebhookFailureCount = async (webhookId: string) => {
+ await prisma.webhook.update({
+ where: { id: webhookId },
+ data: {
+ consecutiveFailures: 0,
+ lastFailedAt: null,
+ },
+ });
+};
+
+const sendFailureNotification = async (
+ webhook: Pick<Webhook, "id" | "url" | "triggers" | "disabled" | "projectId">,
+) => {
+ const workspaceOwners = await prisma.projectUsers.findFirst({
+ where: { projectId: webhook.projectId, role: "owner" },
+ select: {
+ project: {
+ select: {
+ name: true,
+ slug: true,
+ },
+ },
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (!workspaceOwners) {
+ return;
+ }
+
+ const email = workspaceOwners.user.email!;
+ const workspace = workspaceOwners.project;
+
+ sendEmail({
+ subject: "Webhook has been disabled",
+ email,
+ react: WebhookDisabled({
+ email,
+ workspace: {
+ name: workspace.name,
+ slug: workspace.slug,
+ },
+ webhook: {
+ id: webhook.id,
+ url: webhook.url,
+ },
+ }),
+ });
+};
diff --git a/apps/web/lib/webhook/publish-edge.ts b/apps/web/lib/webhook/publish-edge.ts
index 578b6fa6e2..9d6b374e1c 100644
--- a/apps/web/lib/webhook/publish-edge.ts
+++ b/apps/web/lib/webhook/publish-edge.ts
@@ -28,6 +28,7 @@ export const sendWorkspaceWebhookOnEdge = async ({
id: true,
url: true,
secret: true,
+ disabled: true,
},
});
diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.ts
index 499864052b..7a1e810182 100644
--- a/apps/web/lib/webhook/publish.ts
+++ b/apps/web/lib/webhook/publish.ts
@@ -32,6 +32,7 @@ export const sendWorkspaceWebhook = async ({
id: true,
url: true,
secret: true,
+ disabled: true,
},
});
diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.ts
index a354b41b1e..c97b5eff6b 100644
--- a/apps/web/lib/webhook/qstash.ts
+++ b/apps/web/lib/webhook/qstash.ts
@@ -14,7 +14,7 @@ export const sendWebhooks = async ({
trigger,
data,
}: {
- webhooks: Pick<Webhook, "id" | "url" | "secret">[];
+ webhooks: Pick<Webhook, "id" | "url" | "secret" | "disabled">[];
trigger: WebhookTrigger;
data: EventDataProps;
}) => {
@@ -22,10 +22,16 @@ export const sendWebhooks = async ({
return;
}
+ const activeWebhooks = webhooks.filter((webhook) => !webhook?.disabled);
+
+ if (activeWebhooks.length === 0) {
+ return;
+ }
+
const payload = prepareWebhookPayload(trigger, data);
return await Promise.all(
- webhooks.map((webhook) =>
+ activeWebhooks.map((webhook) =>
publishWebhookEventToQStash({ webhook, payload }),
),
);
diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prisma
index 536c6e9638..9fe59eb081 100644
--- a/apps/web/prisma/schema/webhook.prisma
+++ b/apps/web/prisma/schema/webhook.prisma
@@ -5,15 +5,18 @@ enum WebhookReceiver {
}
model Webhook {
- id String @id @default(cuid())
- receiver WebhookReceiver
- projectId String
- name String
- url String
- secret String
- triggers Json
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ receiver WebhookReceiver
+ projectId String
+ name String
+ url String
+ secret String
+ disabled Boolean @default(false)
+ triggers Json
+ consecutiveFailures Int @default(0)
+ lastFailedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
links LinkWebhook[]