The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added rate limits, handle edge cases, fix cron error, etc.
Steven Tey2a7364965660
diff --git a/emails/clicks-summary.tsx b/emails/clicks-summary.tsxindex a71a102479..642751fe9f 100644--- a/emails/clicks-summary.tsx+++ b/emails/clicks-summary.tsx@@ -19,7 +19,6 @@ import { DUB_LOGO } from "../lib/constants";import { nFormatter, truncate } from "../lib/utils";export default function ClicksSummary({- email = "[email protected]",projectName = "Acme",projectSlug = "acme",totalClicks = 63689,@@ -47,7 +46,6 @@ export default function ClicksSummary({},],}: {- email: string;projectName: string;projectSlug: string;totalClicks: number;@@ -60,7 +58,7 @@ export default function ClicksSummary({return (<Html><Head />- <Preview>Your 30-day Dub summary</Preview>+ <Preview>Your 30-day Dub summary for {projectName}</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">@@ -74,7 +72,7 @@ export default function ClicksSummary({/></Section><Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">- Your 30-day Dub summary+ Your 30-day Dub summary for {projectName}</Heading><Text className="text-sm leading-6 text-black">In the last 30 days, your Dub project,{" "}@@ -141,18 +139,18 @@ export default function ClicksSummary({<Section className="my-8 text-center"><LinkclassName="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"- href={`https://app.dub.sh/${projectSlug}/settings/billing`}+ href={`https://app.dub.sh/${projectSlug}`}>View my stats</Link></Section><Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}- <span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are- concerned about your account's safety, please reply to this email- to get in touch with us.+ This email was intended for members of the{" "}+ <span className="text-black">{projectName}</span> project on Dub.+ If you were not expecting this email, you can ignore this email.+ If you are concerned about your account's safety, please reply to+ this email to get in touch with us.</Text></Container></Body>diff --git a/emails/domain-deleted.tsx b/emails/domain-deleted.tsxindex eea3fc58d7..8ceee4f281 100644--- a/emails/domain-deleted.tsx+++ b/emails/domain-deleted.tsx@@ -72,9 +72,9 @@ export default function DomainDeleted({</Text><Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}+ This email was intended for{" "}<span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are+ expecting this email, you can ignore this email. If you areconcerned about your account's safety, please reply to this emailto get in touch with us.</Text>diff --git a/emails/index.ts b/emails/index.tsindex 1ab6c817f1..e40f60ee1f 100644--- a/emails/index.ts+++ b/emails/index.ts@@ -8,20 +8,22 @@ export const sendEmail = async ({subject,react,marketing,+ test,}: {- email: string;+ email: string | string[];subject: string;react:| ReactElement<any, string | JSXElementConstructor<any>>| null| undefined;marketing?: boolean;+ test?: boolean;}) => {return resend.emails.send({from: marketing? "Steven from Dub <[email protected]>": "Dub <[email protected]>",- to: [email],+ to: test ? "[email protected]" : email,subject,react,});diff --git a/emails/invalid-domain.tsx b/emails/invalid-domain.tsxindex f293246ce7..1d54852f81 100644--- a/emails/invalid-domain.tsx+++ b/emails/invalid-domain.tsx@@ -85,9 +85,9 @@ export default function InvalidDomain({</Text><Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}+ This email was intended for{" "}<span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are+ expecting this email, you can ignore this email. If you areconcerned about your account's safety, please reply to this emailto get in touch with us.</Text>diff --git a/emails/login-link.tsx b/emails/login-link.tsxindex 696e98b190..afd4b5471c 100644--- a/emails/login-link.tsx+++ b/emails/login-link.tsx@@ -62,9 +62,9 @@ export default function LoginLink({</Text><Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}+ This email was intended for{" "}<span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are+ expecting this email, you can ignore this email. If you areconcerned about your account's safety, please reply to this emailto get in touch with us.</Text>diff --git a/emails/upgrade-email.tsx b/emails/upgrade-email.tsxindex 7ea76ab959..923d8d9a31 100644--- a/emails/upgrade-email.tsx+++ b/emails/upgrade-email.tsx@@ -114,9 +114,9 @@ export default function UpgradeEmail({<Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}+ This email was intended for{" "}<span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are+ expecting this email, you can ignore this email. If you areconcerned about your account's safety, please reply to this emailto get in touch with us.</Text>diff --git a/emails/usage-exceeded.tsx b/emails/usage-exceeded.tsxindex 4d62d7c4b0..b32705dfbe 100644--- a/emails/usage-exceeded.tsx+++ b/emails/usage-exceeded.tsx@@ -17,7 +17,6 @@ import { ProjectProps } from "../lib/types";import { capitalize, nFormatter } from "../lib/utils";export default function UsageExceeded({- email = "[email protected]",project = {id: "ckqf1q3xw0000gk5u2q1q2q1q",name: "Acme",@@ -28,7 +27,6 @@ export default function UsageExceeded({},type = "first",}: {- email: string;project: ProjectProps;type: "first" | "second";}) {@@ -82,11 +80,11 @@ export default function UsageExceeded({</Text><Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}- <span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are- concerned about your account's safety, please reply to this email- to get in touch with us.+ This email was intended for members of the{" "}+ <span className="text-black">{project.name}</span> project on Dub.+ If you were not expecting this email, you can ignore this email.+ If you are concerned about your account's safety, please reply to+ this email to get in touch with us.</Text></Container></Body>diff --git a/emails/welcome-email.tsx b/emails/welcome-email.tsxindex 5f2f11f08b..d2fb19c8ca 100644--- a/emails/welcome-email.tsx+++ b/emails/welcome-email.tsx@@ -92,9 +92,9 @@ export default function WelcomeEmail({<Hr className="mx-0 my-6 w-full border border-gray-200" /><Text className="text-[12px] leading-6 text-gray-500">- This invitation was intended for{" "}+ This email was intended for{" "}<span className="text-black">{email}</span>. If you were not- expecting this invitation, you can ignore this email. If you are+ expecting this email, you can ignore this email. If you areconcerned about your account's safety, please reply to this emailto get in touch with us.</Text>diff --git a/lib/cron/domains.tsx b/lib/cron/domains.tsxindex 5187e08402..3b09e715c2 100644--- a/lib/cron/domains.tsx+++ b/lib/cron/domains.tsx@@ -4,6 +4,7 @@ import { deleteDomainAndLinks } from "#/lib/api/domains";import prisma from "#/lib/prisma";import InvalidDomain from "emails/invalid-domain";import DomainDeleted from "emails/domain-deleted";+import { limiter } from "./utils";export const handleDomainUpdates = async ({domain,@@ -122,15 +123,17 @@ export const handleDomainUpdates = async ({}`,type: "cron",}),- sendEmail({- subject: `Your domain ${domain} has been deleted`,- email: ownerEmail,- react: DomainDeleted({+ limiter.schedule(() =>+ sendEmail({+ subject: `Your domain ${domain} has been deleted`,email: ownerEmail,- projectSlug,- domain,+ react: DomainDeleted({+ email: ownerEmail,+ projectSlug,+ domain,+ }),}),- }),+ ),]);}@@ -186,16 +189,18 @@ const sendDomainInvalidEmail = async ({message: `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,type: "cron",}),- sendEmail({- subject: `Your domain ${domain} needs to be configured`,- email: ownerEmail,- react: InvalidDomain({+ limiter.schedule(() =>+ sendEmail({+ subject: `Your domain ${domain} needs to be configured`,email: ownerEmail,- domain,- projectSlug,- invalidDays,+ react: InvalidDomain({+ email: ownerEmail,+ domain,+ projectSlug,+ invalidDays,+ }),}),- }),+ ),prisma.sentEmail.create({data: {project: {diff --git a/lib/cron/usage.tsx b/lib/cron/usage.tsxindex fb450832e7..20af23cc7e 100644--- a/lib/cron/usage.tsx+++ b/lib/cron/usage.tsx@@ -5,6 +5,7 @@ import { log } from "#/lib/utils";import { ProjectProps } from "#/lib/types";import { getTopLinks } from "#/lib/tinybird";import ClicksSummary from "emails/clicks-summary";+import { limiter } from "./utils";export const updateUsage = async () => {const projects = await prisma.project.findMany({@@ -24,12 +25,10 @@ export const updateUsage = async () => {plan: true,billingCycleStart: true,users: {- where: {- role: "owner",- },select: {user: true,},+ take: 50,},domains: {where: {@@ -55,10 +54,12 @@ export const updateUsage = async () => {const notifyOveragesResponse = await Promise.allSettled(exceedingUsage.map(async (project) => {const { name, usage, usageLimit, users, sentEmails } = project;- const email = users[0].user.email;+ const emails = users.map((user) => user.user.email) as string[];await log({- message: `${name} is over usage limit. Usage: ${usage}, Limit: ${usageLimit}, Email: ${email}`,+ message: `${name} is over usage limit. Usage: ${usage}, Limit: ${usageLimit}, Email: ${emails.join(+ ", ",+ )}`,type: "cron",mention: true,});@@ -67,7 +68,7 @@ export const updateUsage = async () => {);if (!sentFirstUsageLimitEmail) {// @ts-ignore- sendUsageLimitEmail(email, project, "first");+ sendUsageLimitEmail(emails, project, "first");} else {const sentSecondUsageLimitEmail = sentEmails.some((email) => email.type === "secondUsageLimitEmail",@@ -80,7 +81,7 @@ export const updateUsage = async () => {);if (daysSinceFirstEmail >= 3) {// @ts-ignore- sendUsageLimitEmail(email, project, "second");+ sendUsageLimitEmail(emails, project, "second");}}}@@ -111,21 +112,22 @@ export const updateUsage = async () => {getTopLinks(project.domains.map((domain) => domain.slug)),]);- const email = project.users[0].user.email as string;+ const emails = project.users.map((user) => user.user.email) as string[];- await sendEmail({- subject: `Your 30-day Dub summary`,- email,- react: ClicksSummary({- email,- projectName: project.name,- projectSlug: project.slug,- totalClicks: project.usage,- createdLinks:- createdLinks.status === "fulfilled" ? createdLinks.value : 0,- topLinks: topLinks.status === "fulfilled" ? topLinks.value : [],+ limiter.schedule(() =>+ sendEmail({+ subject: `Your 30-day Dub summary for ${project.name}`,+ email: emails,+ react: ClicksSummary({+ projectName: project.name,+ projectSlug: project.slug,+ totalClicks: project.usage,+ createdLinks:+ createdLinks.status === "fulfilled" ? createdLinks.value : 0,+ topLinks: topLinks.status === "fulfilled" ? topLinks.value : [],+ }),}),- });+ );return await prisma.project.update({where: {@@ -154,25 +156,26 @@ export const updateUsage = async () => {};const sendUsageLimitEmail = async (- email: string,+ emails: string[],project: ProjectProps,type: "first" | "second",) => {- return await Promise.all([- sendEmail({- subject: `You have exceeded your Dub usage limit`,- email,- react: UsageExceeded({- email,- project,- type,+ return await Promise.allSettled([+ limiter.schedule(() =>+ sendEmail({+ subject: `You have exceeded your Dub usage limit`,+ email: emails,+ react: UsageExceeded({+ project,+ type,+ }),}),- }),+ ),prisma.sentEmail.create({data: {- user: {+ project: {connect: {- email,+ slug: project.slug,},},type: `${type}UsageLimitEmail`,diff --git a/lib/cron/utils.ts b/lib/cron/utils.tsnew file mode 100644index 0000000000..e8fd8eef81--- /dev/null+++ b/lib/cron/utils.ts@@ -0,0 +1,7 @@+import Bottleneck from "bottleneck";++// we're using Bottleneck to avoid running into Resend's rate limit of 10 req/s+export const limiter = new Bottleneck({+ maxConcurrent: 1, // maximum concurrent requests+ minTime: 100, // minimum time between requests in ms+});diff --git a/lib/utils.ts b/lib/utils.tsindex df40e4eafb..c05befde6c 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -402,7 +402,6 @@ export async function generateMD5Hash(message) {const logTypeToEnv = {cron: process.env.DUB_SLACK_HOOK_CRON,links: process.env.DUB_SLACK_HOOK_LINKS,- error: process.env.DUB_SLACK_HOOK_ERROR,};export const log = async ({@@ -411,7 +410,7 @@ export const log = async ({mention = false,}: {message: string;- type: "cron" | "links" | "error";+ type: "cron" | "links";mention?: boolean;}) => {/* Log a message to the console */diff --git a/package.json b/package.jsonindex 4ff6c6753f..ad9e89bdce 100644--- a/package.json+++ b/package.json@@ -39,6 +39,7 @@"@visx/responsive": "^2.10.0","@visx/shape": "^2.12.2","@visx/tooltip": "^2.16.0",+ "bottleneck": "^2.19.5","cloudinary": "^1.36.4","clsx": "^1.2.1","cmdk": "^0.2.0",diff --git a/yarn.lock b/yarn.lockindex 84e39cefda..69491e3d89 100644--- a/yarn.lock+++ b/yarn.lock@@ -3079,6 +3079,11 @@ boolbase@^1.0.0:resolved "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz"integrity sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==+bottleneck@^2.19.5:+ version "2.19.5"+ resolved "https://registry.yarnpkg.com/bottleneck/-/bottleneck-2.19.5.tgz#5df0b90f59fd47656ebe63c78a98419205cadd91"+ integrity sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==+brace-expansion@^1.1.7:version "1.1.11"resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz"