The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
remove links usage cron – update it in real time
Steven Tey9ea58d84a14f
diff --git a/apps/web/app/api/cron/links/usage/route.ts b/apps/web/app/api/cron/links/usage/route.tsdeleted file mode 100644index 1a7b3617aa..0000000000--- a/apps/web/app/api/cron/links/usage/route.ts+++ /dev/null@@ -1,72 +0,0 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";-import { prisma } from "@/lib/prisma";-import { log } from "@dub/utils";-import { sendLinksUsageEmail } from "./utils";--// Cron to update the links usage of each workspace.-// Runs once every 15 mins (*/15 * * * *)--export const dynamic = "force-dynamic";--export async function GET(req: Request) {- try {- await verifyVercelSignature(req);-- // get links created in the last 15 minutes- const links = await prisma.link.findMany({- where: {- createdAt: {- gte: new Date(Date.now() - 15 * 60 * 1000),- },- },- select: {- projectId: true,- },- });-- const workspacesToCheck = links- .map((link) => link.projectId)- .filter(Boolean) as string[];-- console.log(- "Links created in the last 15 minutes: ",- links.length,- "Workspaces to check: ",- workspacesToCheck,- );-- const workspaces = await prisma.project.findMany({- select: {- id: true,- name: true,- slug: true,- plan: true,- linksUsage: true,- linksLimit: true,- sentEmails: true,- },- where: {- id: {- in: workspacesToCheck,- },- },- });-- if (workspaces.length === 0) {- return new Response("OK");- }-- await Promise.allSettled(- workspaces.map((workspace) => sendLinksUsageEmail(workspace)),- );-- return new Response("OK");- } catch (error) {- await log({- message: "Links usage cron failed. Error: " + error.message,- type: "errors",- });- return handleAndReturnErrorResponse(error);- }-}diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex c750be71b5..525f318dcd 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -3,6 +3,7 @@ import { recordLink } from "@/lib/tinybird";import { LinkProps, ProcessedLinkProps, RedisLinkProps } from "@/lib/types";import { formatRedisLink, redis } from "@/lib/upstash";import { getParamsFromURL, truncate } from "@dub/utils";+import { updateLinksUsage } from "./update-links-usage";import { combineTagIds, transformLink } from "./utils";export async function bulkCreateLinks({@@ -126,16 +127,9 @@ export async function propagateBulkLinkChanges(created_at: link.createdAt,})),),- // update links usage for workspace- prisma.project.update({- where: {- id: links[0].projectId!, // this will always be present- },- data: {- linksUsage: {- increment: links.length,- },- },+ updateLinksUsage({+ workspaceId: links[0].projectId!, // this will always be present+ increment: links.length,}),]);}diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex dbe5e00d0a..2f2c7c2447 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -7,6 +7,7 @@ import { formatRedisLink, redis } from "@/lib/upstash";import { APP_DOMAIN_WITH_NGROK, getParamsFromURL, truncate } from "@dub/utils";import { Prisma } from "@prisma/client";import { waitUntil } from "@vercel/functions";+import { updateLinksUsage } from "./update-links-usage";import { combineTagIds, transformLink } from "./utils";export async function createLink(link: ProcessedLinkProps) {@@ -126,15 +127,9 @@ export async function createLink(link: ProcessedLinkProps) {}),// update links usage for workspacelink.projectId &&- prisma.project.update({- where: {- id: link.projectId,- },- data: {- linksUsage: {- increment: 1,- },- },+ updateLinksUsage({+ workspaceId: link.projectId,+ increment: 1,}),]),);diff --git a/apps/web/app/api/cron/links/usage/utils.ts b/apps/web/lib/api/links/update-links-usage.tssimilarity index 64%rename from apps/web/app/api/cron/links/usage/utils.tsrename to apps/web/lib/api/links/update-links-usage.tsindex 8249f8a5e6..3222020d0f 100644--- a/apps/web/app/api/cron/links/usage/utils.ts+++ b/apps/web/lib/api/links/update-links-usage.ts@@ -2,30 +2,52 @@ import { sendLimitEmail } from "@/lib/cron/send-limit-email";import { prisma } from "@/lib/prisma";import { WorkspaceProps } from "@/lib/types";import { log } from "@dub/utils";-import { Project, SentEmail } from "@prisma/client";-// 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[];- },-) => {+export async function updateLinksUsage({+ workspaceId,+ increment,+}: {+ workspaceId: string;+ increment: number;+}) {+ const workspace = await prisma.project.update({+ where: {+ id: workspaceId,+ },+ data: {+ linksUsage: {+ increment,+ },+ },+ select: {+ id: true,+ name: true,+ slug: true,+ linksUsage: true,+ linksLimit: true,+ plan: true,+ },+ });+const percentage = Math.round((workspace.linksUsage / workspace.linksLimit) * 100,);// Skip if the workspace is below 80% of the limitif (percentage < 80) {- console.log(- `${workspace.slug} is below 80% of the links limit (${percentage}%), skipping...`,- );return;}- const sentNotification = workspace.sentEmails.some(+ const sentEmails = await prisma.sentEmail.findMany({+ where: {+ projectId: workspaceId,+ },+ select: {+ type: true,+ },+ });++ const sentNotification = sentEmails.some((email) =>email.type ===(percentage >= 80 && percentage < 100@@ -43,7 +65,7 @@ export const sendLinksUsageEmail = async (where: {projects: {some: {- projectId: workspace.id,+ projectId: workspaceId,},},},@@ -54,10 +76,10 @@ export const sendLinksUsageEmail = async (const emails = users.map(({ email }) => email) as string[];- await Promise.allSettled([+ return await Promise.allSettled([sendLimitEmail({emails,- workspace: workspace as WorkspaceProps & { sentEmails: SentEmail[] },+ workspace: workspace as WorkspaceProps,type:percentage >= 80 && percentage < 100? "firstLinksLimitEmail"@@ -72,4 +94,4 @@ export const sendLinksUsageEmail = async (mention: workspace.plan !== "free",}),]);-};+}diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex c42971f183..88b6ad0f8c 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -7,10 +7,6 @@{"path": "/api/cron/usage","schedule": "0 12 * * *"- },- {- "path": "/api/cron/links/usage",- "schedule": "*/15 * * * *"}],"functions": {