Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhook cache setup change #1494

Open
wants to merge 3 commits into
base: webhooks-ga
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions apps/web/app/api/webhooks/[webhookId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ export const PATCH = withWorkspace(
},
});

// Cache the existing webhook before updating it
const existingWebhook = await prisma.webhook.findUniqueOrThrow({
where: {
id: webhookId,
projectId: workspace.id,
},
});

const webhook = await prisma.webhook.update({
where: {
id: webhookId,
Expand Down Expand Up @@ -139,13 +147,6 @@ export const PATCH = withWorkspace(

waitUntil(
(async () => {
const existingWebhook = await prisma.webhook.findUniqueOrThrow({
where: {
id: webhookId,
projectId: workspace.id,
},
});

// If the webhook is being changed from link level to workspace level, delete the cache
if (
isLinkLevelWebhook(existingWebhook) &&
Expand Down
36 changes: 19 additions & 17 deletions apps/web/lib/webhook/cache.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,34 @@
import { redis } from "@/lib/upstash";
import { WebhookCacheProps } from "../types";
import { WEBHOOK_REDIS_KEY } from "./constants";
import { isLinkLevelWebhook } from "./utils";

const WEBHOOK_CACHE_KEY_PREFIX = "webhook";

class WebhookCache {
async set(webhook: WebhookCacheProps) {
return await redis.hset(WEBHOOK_REDIS_KEY, {
[webhook.id]: this.format(webhook),
});
}
if (!isLinkLevelWebhook(webhook)) {
return;
}

async get(webhookId: string) {
return await redis.hget<WebhookCacheProps>(WEBHOOK_REDIS_KEY, webhookId);
return await redis.set(
this._getCacheKey(webhook.id),
JSON.stringify(this._format(webhook)),
);
}

async mget(webhookIds: string[]) {
const webhooks = await redis.hmget<Record<string, WebhookCacheProps>>(
WEBHOOK_REDIS_KEY,
...webhookIds,
const webhooks = await redis.mget<WebhookCacheProps[]>(
webhookIds.map(this._getCacheKey),
);

if (!webhooks) {
return [];
}

return Object.values(webhooks);
return webhooks.filter(Boolean);
}

async delete(webhookId: string) {
return await redis.hdel(WEBHOOK_REDIS_KEY, webhookId);
return await redis.del(this._getCacheKey(webhookId));
}

format(webhook: WebhookCacheProps) {
_format(webhook: WebhookCacheProps) {
return {
id: webhook.id,
url: webhook.url,
Expand All @@ -39,6 +37,10 @@ class WebhookCache {
...(webhook.disabledAt && { disabledAt: webhook.disabledAt }),
};
}

_getCacheKey(webhookId: string) {
return `${WEBHOOK_CACHE_KEY_PREFIX}:${webhookId}`;
}
}

export const webhookCache = new WebhookCache();
10 changes: 4 additions & 6 deletions apps/web/lib/webhook/failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,20 @@ export const handleWebhookFailure = async (webhookId: string) => {
webhook.consecutiveFailures >= WEBHOOK_FAILURE_NOTIFY_THRESHOLD;

if (failureThresholdReached) {
const disabledAt = new Date();

// Disable the webhook
await prisma.webhook.update({
const updatedWebhook = await prisma.webhook.update({
where: { id: webhookId },
data: {
disabledAt,
disabledAt: new Date(),
},
});

await Promise.allSettled([
// Notify the user
sendFailureNotification(webhook),
sendFailureNotification(updatedWebhook),

// Update the webhook cache
webhookCache.set({ ...webhook, disabledAt }),
webhookCache.set(updatedWebhook),

// Update the project webhookEnabled flag
updateWebhookStatusForWorkspace({
Expand Down
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"postcss-import": "^15.1.0",
"prisma": "5.18.0",
"tailwindcss": "^3.4.4",
"tsx": "^3.14.0",
"tsx": "^4.19.1",
"turbo": "^1.10.14",
"typescript": "^5.4.4",
"vite": "5.2.9",
Expand Down
29 changes: 29 additions & 0 deletions apps/web/scripts/update-webhook-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { prisma } from "@/lib/prisma";
import { webhookCache } from "@/lib/webhook/cache";
import "dotenv-flow/config";

async function main() {
// Find link level webhooks
const linkLevelWebhooks = await prisma.webhook.findMany({
where: {
triggers: {
array_contains: ["link.clicked"],
},
},
select: {
id: true,
url: true,
secret: true,
triggers: true,
disabledAt: true,
},
});

const result = await Promise.all(
linkLevelWebhooks.map((webhook) => webhookCache.set(webhook)),
);

console.log(`Cache updated for ${result.length} webhooks`);
}

main();
2 changes: 2 additions & 0 deletions apps/web/ui/modals/delete-webhook-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
useState,
} from "react";
import { toast } from "sonner";
import { mutate } from "swr";

function DeleteWebhookModal({
showDeleteWebhookModal,
Expand Down Expand Up @@ -44,6 +45,7 @@ function DeleteWebhookModal({
}

setShowDeleteWebhookModal(false);
mutate(`/api/webhooks?workspaceId=${workspaceId}`);
router.push(`/${workspaceSlug}/settings/webhooks`);
};

Expand Down
Loading
Loading