The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
optimize links usage cron
Steven Tey6282cc663d9d
diff --git a/apps/web/app/api/cron/links/usage/route.ts b/apps/web/app/api/cron/links/usage/route.tsindex 843c60ea07..d7169dc4cc 100644--- a/apps/web/app/api/cron/links/usage/route.ts+++ b/apps/web/app/api/cron/links/usage/route.ts@@ -1,13 +1,10 @@-import { sendLimitEmail, verifySignature, qstash } from "@/lib/cron";+import { verifySignature } from "@/lib/cron";import prisma from "@/lib/prisma";-import { WorkspaceProps } from "@/lib/types";-import { Project } from "@prisma/client";-import { APP_DOMAIN_WITH_NGROK, getSearchParams, log } from "@dub/utils";+import { log } from "@dub/utils";+import { sendLinksUsageEmail } from "./utils";// Cron to update the links usage of each workspace.-// Runs once every 5 mins (*/5 * * * *)--const limit = 30;+// Runs once every 10 mins (*/10 * * * *)export async function GET(req: Request) {const validSignature = await verifySignature(req);@@ -16,7 +13,21 @@ export async function GET(req: Request) {return new Response("Unauthorized", { status: 401 });}- const { skip } = getSearchParams(req.url);+ // get links created in the last 5 minutes+ const links = await prisma.link.findMany({+ where: {+ createdAt: {+ gte: new Date(Date.now() - 5 * 60 * 1000),+ },+ },+ select: {+ projectId: true,+ },+ });++ const workspacesToCheck = links+ .map((link) => link.projectId)+ .filter(Boolean) as string[];const workspaces = await prisma.project.findMany({select: {@@ -26,9 +37,13 @@ export async function GET(req: Request) {plan: true,linksUsage: true,linksLimit: true,+ sentEmails: true,+ },+ where: {+ id: {+ in: workspacesToCheck,+ },},- take: limit,- skip: skip ? parseInt(skip) : 0,});if (workspaces.length === 0) {@@ -37,85 +52,16 @@ export async function GET(req: Request) {try {await Promise.allSettled(- workspaces.map((workspace) => sendUsageEmail(workspace)),+ workspaces.map((workspace) => sendLinksUsageEmail(workspace)),);- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/usage?skip=${- skip ? parseInt(skip) + limit : limit- }`,- method: "GET",- });-return new Response("OK");} catch (error) {await log({- message: "Usage cron failed. Error: " + error.message,+ message: "Links usage cron failed. Error: " + error.message,type: "errors",});return new Response(error.message, { status: 500 });}}--// Check if the workspace is close to the limit and send an email to the users-const sendUsageEmail = async (- workspace: Pick<- Project,- "id" | "name" | "slug" | "plan" | "linksUsage" | "linksLimit"- >,-) => {- const percentage = Math.round(- (workspace.linksUsage / workspace.linksLimit) * 100,- );-- // Skip if the workspace is not close to the limit- if (![80, 100].includes(percentage)) {- return;- }-- const sentNotification = await prisma.sentEmail.count({- where: {- projectId: workspace.id,- type:- percentage === 80 ? "firstLinksLimitEmail" : "secondLinksLimitEmail",- },- });-- // Skip if the email has already been sent- if (sentNotification) {- return;- }-- const users = await prisma.user.findMany({- where: {- projects: {- some: {- projectId: workspace.id,- },- },- },- select: {- email: true,- },- });-- const emails = users.map(({ email }) => email) as string[];-- await Promise.allSettled([- sendLimitEmail({- emails,- workspace: workspace as WorkspaceProps,- type:- percentage === 80 ? "firstLinksLimitEmail" : "secondLinksLimitEmail",- }),-- log({- message: `*${- workspace.slug- }* has used ${percentage.toString()}% of its links limit for the month.`,- type: workspace.plan === "free" ? "cron" : "alerts",- mention: workspace.plan !== "free",- }),- ]);-};diff --git a/apps/web/app/api/cron/links/usage/utils.ts b/apps/web/app/api/cron/links/usage/utils.tsnew file mode 100644index 0000000000..4bc6d5aa24--- /dev/null+++ b/apps/web/app/api/cron/links/usage/utils.ts@@ -0,0 +1,73 @@+import { sendLimitEmail } from "@/lib/cron";+import prisma from "@/lib/prisma";+import { WorkspaceProps } from "@/lib/types";+import { Project, SentEmail } from "@prisma/client";+import { log } from "@dub/utils";++// Check if the workspace is close to the links limit and send an email to the users+export const sendLinksUsageEmail = async (+ workspace: Pick<+ Project,+ "id" | "name" | "slug" | "plan" | "linksUsage" | "linksLimit"+ > & {+ sentEmails?: SentEmail[];+ },+) => {+ const percentage = Math.round(+ (workspace.linksUsage / workspace.linksLimit) * 100,+ );++ // Skip if the workspace is below 80% of the limit+ if (percentage < 80) {+ return;+ }++ const sentEmails = workspace.sentEmails || [];++ const sentNotification = sentEmails.some(+ (email) =>+ email.type ===+ (percentage >= 80 && percentage < 100+ ? "firstLinksLimitEmail"+ : "secondLinksLimitEmail"),+ );++ // Skip if the email has already been sent+ if (sentNotification) {+ return;+ }++ const users = await prisma.user.findMany({+ where: {+ projects: {+ some: {+ projectId: workspace.id,+ },+ },+ },+ select: {+ email: true,+ },+ });++ const emails = users.map(({ email }) => email) as string[];++ await Promise.allSettled([+ sendLimitEmail({+ emails,+ workspace: workspace as WorkspaceProps,+ type:+ percentage >= 80 && percentage < 100+ ? "firstLinksLimitEmail"+ : "secondLinksLimitEmail",+ }),++ log({+ message: `*${+ workspace.slug+ }* has used ${percentage.toString()}% of its links limit for the month.`,+ type: workspace.plan === "free" ? "cron" : "alerts",+ mention: workspace.plan !== "free",+ }),+ ]);+};diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 64baec4ef8..f0192aa598 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -10,7 +10,7 @@},{"path": "/api/cron/links/usage",- "schedule": "*/5 * * * *"+ "schedule": "*/10 * * * *"}],"functions": {