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.

improve handling disabled webhooks

Kiran Kfdba44bdfaec
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 6de6d7789a..d1044b14d4 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -3,6 +3,7 @@ import { linkCache } from "@/lib/api/links/cache";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import { updateWebhookStatusForWorkspace } from "@/lib/webhook/api";
import { webhookCache } from "@/lib/webhook/cache";
import { transformWebhook } from "@/lib/webhook/transform";
import { isLinkLevelWebhook } from "@/lib/webhook/utils";
@@ -263,24 +264,6 @@ export const DELETE = withWorkspace(
},
});
- const webhooksCount = await prisma.webhook.count({
- where: {
- projectId: workspace.id,
- },
- });
-
- // Disable webhooks for the workspace if there are no more webhooks
- if (webhooksCount === 0) {
- await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- webhookEnabled: false,
- },
- });
- }
-
waitUntil(
(async () => {
const links = await prisma.link.findMany({
@@ -304,6 +287,7 @@ export const DELETE = withWorkspace(
});
await Promise.all([
+ updateWebhookStatusForWorkspace({ workspace }),
linkCache.mset(formatedLinks),
webhookCache.delete(webhookId),
]);
diff --git a/apps/web/lib/actions/enable-disable-webhook.ts b/apps/web/lib/actions/enable-disable-webhook.ts
new file mode 100644
index 0000000000..ec82278fad
--- /dev/null
+++ b/apps/web/lib/actions/enable-disable-webhook.ts
@@ -0,0 +1,63 @@
+"use server";
+
+import { prisma } from "@/lib/prisma";
+import { waitUntil } from "@vercel/functions";
+import { updateWebhookStatusForWorkspace } from "../webhook/api";
+import { webhookCache } from "../webhook/cache";
+import z from "../zod";
+import { authActionClient } from "./safe-action";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ webhookId: z.string(),
+});
+
+// Enable or disable a webhook
+export const enableOrDisableWebhook = authActionClient
+ .schema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace } = ctx;
+ const { webhookId } = parsedInput;
+
+ const canAccessWebhook = !["free", "pro"].includes(workspace.plan);
+
+ if (!canAccessWebhook) {
+ throw new Error("You must upgrade your plan to enable webhooks.");
+ }
+
+ const webhook = await prisma.webhook.findUniqueOrThrow({
+ where: {
+ id: webhookId,
+ projectId: workspace.id,
+ },
+ select: {
+ disabledAt: true,
+ },
+ });
+
+ const disabledAt = webhook.disabledAt ? null : new Date();
+
+ const updatedWebhook = await prisma.webhook.update({
+ where: {
+ id: webhookId,
+ projectId: workspace.id,
+ },
+ data: {
+ disabledAt,
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ await Promise.all([
+ updateWebhookStatusForWorkspace({ workspace }),
+
+ webhookCache.set(updatedWebhook),
+ ]);
+ })(),
+ );
+
+ return {
+ disabledAt,
+ };
+ });
diff --git a/apps/web/lib/webhook/api.ts b/apps/web/lib/webhook/api.ts
index dde9fa53f8..b275bc4652 100644
--- a/apps/web/lib/webhook/api.ts
+++ b/apps/web/lib/webhook/api.ts
@@ -100,3 +100,25 @@ export async function addWebhook({
return webhook;
}
+
+export const updateWebhookStatusForWorkspace = async ({
+ workspace,
+}: {
+ workspace: Pick<Project, "id">;
+}) => {
+ const activeWebhooksCount = await prisma.webhook.count({
+ where: {
+ projectId: workspace.id,
+ disabledAt: null,
+ },
+ });
+
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ webhookEnabled: activeWebhooksCount > 0,
+ },
+ });
+};
diff --git a/apps/web/lib/webhook/cache.ts b/apps/web/lib/webhook/cache.ts
index cb8070b61d..93959dabb1 100644
--- a/apps/web/lib/webhook/cache.ts
+++ b/apps/web/lib/webhook/cache.ts
@@ -36,7 +36,7 @@ class WebhookCache {
url: webhook.url,
secret: webhook.secret,
triggers: webhook.triggers,
- disabledAt: webhook.disabledAt,
+ ...(webhook.disabledAt && { disabledAt: webhook.disabledAt }),
};
}
}
diff --git a/apps/web/lib/webhook/failure.ts b/apps/web/lib/webhook/failure.ts
index af002fa54b..61ed9cbfb7 100644
--- a/apps/web/lib/webhook/failure.ts
+++ b/apps/web/lib/webhook/failure.ts
@@ -2,6 +2,7 @@ import { Webhook } from "@prisma/client";
import { sendEmail } from "emails";
import WebhookDisabled from "emails/webhook-disabled";
import { prisma } from "../prisma";
+import { updateWebhookStatusForWorkspace } from "./api";
import { webhookCache } from "./cache";
import { WEBHOOK_FAILURE_NOTIFY_THRESHOLD } from "./constants";
@@ -31,23 +32,30 @@ export const handleWebhookFailure = async (webhookId: string) => {
const failureThresholdReached =
webhook.consecutiveFailures >= WEBHOOK_FAILURE_NOTIFY_THRESHOLD;
- const disabledAt = new Date();
-
if (failureThresholdReached) {
- await Promise.allSettled([
- // Disable the webhook
- prisma.webhook.update({
- where: { id: webhookId },
- data: {
- disabledAt,
- },
- }),
+ const disabledAt = new Date();
+
+ // Disable the webhook
+ await prisma.webhook.update({
+ where: { id: webhookId },
+ data: {
+ disabledAt,
+ },
+ });
+ await Promise.allSettled([
// Notify the user
sendFailureNotification(webhook),
// Update the webhook cache
webhookCache.set({ ...webhook, disabledAt }),
+
+ // Update the project webhookEnabled flag
+ updateWebhookStatusForWorkspace({
+ workspace: {
+ id: webhook.projectId,
+ },
+ }),
]);
}
};
diff --git a/apps/web/ui/webhooks/webhook-header.tsx b/apps/web/ui/webhooks/webhook-header.tsx
index dd32a13000..6e8a455e78 100644
--- a/apps/web/ui/webhooks/webhook-header.tsx
+++ b/apps/web/ui/webhooks/webhook-header.tsx
@@ -1,5 +1,6 @@
"use client";
+import { enableOrDisableWebhook } from "@/lib/actions/enable-disable-webhook";
import { clientAccessCheck } from "@/lib/api/tokens/permissions";
import useWorkspace from "@/lib/swr/use-workspace";
import { WebhookProps } from "@/lib/types";
@@ -13,6 +14,7 @@ import {
} from "@dub/ui";
import { fetcher } from "@dub/utils";
import { ChevronLeft, CircleCheck, CircleX, Send, Trash } from "lucide-react";
+import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { notFound, useRouter, useSelectedLayoutSegment } from "next/navigation";
import { useState } from "react";
@@ -54,29 +56,23 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {
role,
});
+ const { execute, isExecuting } = useAction(enableOrDisableWebhook, {
+ onSuccess: async ({ data }) => {
+ toast.success(
+ data?.disabledAt ? "Webhook disabled." : "Webhook enabled.",
+ );
+
+ await mutate();
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError?.serverError);
+ },
+ });
+
if (!isLoading && !webhook) {
return notFound();
}
- const toggleWebhookStatus = async (disabled: boolean) => {
- const response = await fetch(
- `/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,
- {
- method: "PATCH",
- body: JSON.stringify({ disabled }),
- },
- );
-
- if (!response.ok) {
- const error = await response.json();
- toast.error(error.message);
- return;
- }
-
- await mutate();
- toast.success("Webhook updated.");
- };
-
return (
<>
<MaxWidthWrapper className="grid max-w-screen-lg gap-8">
@@ -152,11 +148,16 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {
}
className="h-9 justify-start px-2"
onClick={async () => {
- toggleWebhookStatus(!webhook?.disabledAt);
+ execute({
+ webhookId,
+ workspaceId: workspaceId!,
+ });
+
setOpenPopover(false);
}}
disabled={!!permissionsError}
disabledTooltip={permissionsError}
+ loading={isExecuting}
/>
<Button