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.

Move domain renewal processing to a QStash cron after Stripe charge succeeds.

Kiran Ka0ef46e857c8
diff --git a/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts b/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts
new file mode 100644
index 0000000000..d34e34327e
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts
@@ -0,0 +1,188 @@
+import { parseRegisteredDomainSlugs } from "@/lib/api/domains/is-domain-registration-invoice";
+import { withCron } from "@/lib/cron/with-cron";
+import { setRenewOption } from "@/lib/dynadot/set-renew-option";
+import { prisma } from "@/lib/prisma";
+import { sendBatchEmail } from "@dub/email";
+import DomainRenewed from "@dub/email/templates/domain-renewed";
+import { log, pluralize } from "@dub/utils";
+import { addDays, startOfDay } from "date-fns";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const inputSchema = z.object({
+ invoiceId: z.string(),
+});
+
+// POST /api/cron/domains/renewal-succeeded - Renews domains for a given invoice
+export const POST = withCron(async ({ rawBody }) => {
+ const { invoiceId } = inputSchema.parse(JSON.parse(rawBody));
+
+ const invoice = await prisma.invoice.findUnique({
+ where: {
+ id: invoiceId,
+ },
+ select: {
+ id: true,
+ status: true,
+ type: true,
+ paidAt: true,
+ registeredDomains: true,
+ workspaceId: true,
+ },
+ });
+
+ if (!invoice) {
+ return logAndRespond(`Invoice ${invoiceId} not found.`);
+ }
+
+ if (invoice.type !== "domainRenewal") {
+ return logAndRespond(
+ `Invoice ${invoiceId} is not a domain renewal invoice. Skipping...`,
+ );
+ }
+
+ if (invoice.status !== "completed") {
+ return logAndRespond(`Invoice ${invoiceId} is not completed. Skipping...`);
+ }
+
+ const slugs = parseRegisteredDomainSlugs(invoice.registeredDomains);
+
+ const domains = await prisma.registeredDomain.findMany({
+ where: {
+ slug: {
+ in: slugs,
+ },
+ },
+ orderBy: {
+ expiresAt: "asc",
+ },
+ });
+
+ if (domains.length === 0) {
+ return logAndRespond(
+ `No domains found for invoice ${invoiceId}. Skipping...`,
+ );
+ }
+
+ const earliestExpiresAt = domains[0].expiresAt;
+ const paidAtStart = startOfDay(invoice.paidAt!);
+
+ if (earliestExpiresAt >= addDays(paidAtStart, 365)) {
+ return logAndRespond(
+ `Domain renewal for invoice ${invoiceId} already applied. Skipping...`,
+ );
+ }
+
+ // Extend expiration by 1 year from the later of the current expiry or today.
+ // If the domain hasn't expired yet, remaining time is preserved; if it's already
+ // expired, the new term starts from today.
+ const todayStart = startOfDay(new Date());
+ const renewalBase =
+ earliestExpiresAt > todayStart ? earliestExpiresAt : todayStart;
+ const newExpiresAt = addDays(renewalBase, 365);
+
+ const domainsRenewed: typeof domains = [];
+ const domainsToUpdate: typeof domains = [];
+ const domainsFailed: typeof domains = [];
+
+ for (const domain of domains) {
+ // Domain is already renewed, no further action needed
+ if (domain.expiresAt >= newExpiresAt) {
+ domainsRenewed.push(domain);
+ continue;
+ }
+
+ const renewSucceeded = await setRenewOption({
+ domain: domain.slug,
+ autoRenew: true,
+ });
+
+ // Failed to set auto-renew option on Dynadot
+ if (!renewSucceeded) {
+ domainsFailed.push(domain);
+ continue;
+ }
+
+ domainsToUpdate.push(domain);
+ domainsRenewed.push(domain);
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+
+ if (domainsToUpdate.length > 0) {
+ await prisma.registeredDomain.updateMany({
+ where: {
+ id: {
+ in: domainsToUpdate.map(({ id }) => id),
+ },
+ },
+ data: {
+ expiresAt: newExpiresAt,
+ autoRenewalDisabledAt: null,
+ },
+ });
+ }
+
+ if (domainsFailed.length > 0) {
+ console.error(
+ "Failed to set auto-renew option on Dynadot for the following domains:",
+ domainsFailed.map(({ slug }) => slug).join(", "),
+ );
+
+ await log({
+ message: `Domain renewal partially failed for invoice ${invoiceId}. See the logs for more details.`,
+ type: "errors",
+ mention: true,
+ });
+ }
+
+ if (domainsRenewed.length === 0) {
+ return logAndRespond(`No domains were renewed for invoice ${invoiceId}.`);
+ }
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: invoice.workspaceId,
+ },
+ include: {
+ users: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ user: true,
+ },
+ },
+ },
+ });
+
+ const workspaceOwners = workspace.users.filter(({ user }) => user.email);
+
+ if (workspaceOwners.length === 0) {
+ return logAndRespond(
+ "No users found to send domain renewal success email.",
+ );
+ }
+
+ await sendBatchEmail(
+ workspaceOwners.map(({ user }) => ({
+ variant: "notifications",
+ to: user.email!,
+ subject: `Your ${pluralize("domain", domainsRenewed.length)} ${domainsRenewed.length === 1 ? "has" : "have"} been renewed`,
+ react: DomainRenewed({
+ email: user.email!,
+ workspace: {
+ slug: workspace.slug,
+ },
+ domains: domainsRenewed.map(({ slug }) => ({ slug })),
+ expiresAt: newExpiresAt,
+ }),
+ })),
+ );
+
+ return logAndRespond(
+ `Renewed ${domainsRenewed.length}/${domains.length} domains. Domain renewal success email sent to ${workspaceOwners.length} users.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
index 771bf8d20e..274221f147 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
@@ -4,13 +4,9 @@ import {
parseRegisteredDomainSlugs,
} from "@/lib/api/domains/is-domain-registration-invoice";
import { qstash } from "@/lib/cron";
-import { setRenewOption } from "@/lib/dynadot/set-renew-option";
import { prisma } from "@/lib/prisma";
-import { sendBatchEmail } from "@dub/email";
-import DomainRenewed from "@dub/email/templates/domain-renewed";
-import { APP_DOMAIN_WITH_NGROK, pluralize } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { Invoice } from "@prisma/client";
-import { addDays, startOfDay } from "date-fns";
import Stripe from "stripe";
export async function chargeSucceeded(event: Stripe.ChargeSucceededEvent) {
@@ -139,70 +135,17 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {
return `No domains found for invoice ${invoice.id}, skipping...`;
}
- const earliestExpiresAt = domains[0].expiresAt;
- const todayStart = startOfDay(new Date());
- const renewalBase =
- earliestExpiresAt > todayStart ? earliestExpiresAt : todayStart;
- const newExpiresAt = addDays(renewalBase, 365);
-
- await prisma.registeredDomain.updateMany({
- where: {
- id: {
- in: domains.map(({ id }) => id),
- },
- },
- data: {
- expiresAt: newExpiresAt,
- autoRenewalDisabledAt: null,
- },
- });
-
- await Promise.allSettled(
- domains.map((domain) =>
- setRenewOption({
- domain: domain.slug,
- autoRenew: true,
- }),
- ),
- );
-
- const workspace = await prisma.project.findUniqueOrThrow({
- where: {
- id: invoice.workspaceId,
- },
- include: {
- users: {
- where: {
- role: "owner",
- },
- select: {
- user: true,
- },
- },
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/renewal-succeeded`,
+ deduplicationId: `domain-renewal-${invoice.id}`,
+ body: {
+ invoiceId: invoice.id,
},
});
- const workspaceOwners = workspace.users.filter(({ user }) => user.email);
-
- if (workspaceOwners.length === 0) {
- return "No users found to send domain renewal success email.";
+ if (qstashResponse.messageId) {
+ return `Message sent to Qstash with id ${qstashResponse.messageId}`;
+ } else {
+ return `Error sending message to Qstash: ${JSON.stringify(qstashResponse)}`;
}
-
- await sendBatchEmail(
- workspaceOwners.map(({ user }) => ({
- variant: "notifications",
- to: user.email!,
- subject: `Your ${pluralize("domain", domains.length)} ${domains.length === 1 ? "has" : "have"} been renewed`,
- react: DomainRenewed({
- email: user.email!,
- workspace: {
- slug: workspace.slug,
- },
- domains: domains.map(({ slug }) => ({ slug })),
- expiresAt: newExpiresAt,
- }),
- })),
- );
-
- return `Domain renewal success email sent to ${workspaceOwners.length} users.`;
}
diff --git a/apps/web/lib/dynadot/set-renew-option.ts b/apps/web/lib/dynadot/set-renew-option.ts
index 93abccee86..6cca10d896 100644
--- a/apps/web/lib/dynadot/set-renew-option.ts
+++ b/apps/web/lib/dynadot/set-renew-option.ts
@@ -15,7 +15,7 @@ export const setRenewOption = async ({
}: {
domain: string;
autoRenew: boolean;
-}) => {
+}): Promise<boolean> => {
const searchParams = new URLSearchParams({
key: DYNADOT_API_KEY,
command: "set_renew_option",
@@ -34,13 +34,16 @@ export const setRenewOption = async ({
);
if (!response.ok) {
- console.error(response);
throw new Error(`Failed to set renew option: ${response.statusText}`);
}
+ const responseBody = await response.json();
+
+ console.info(responseBody);
+
const {
SetRenewOptionResponse: { Status },
- } = responseSchema.parse(await response.json());
+ } = responseSchema.parse(responseBody);
if (Status !== "success") {
throw new Error(`Failed to set renew option: ${Status}`);
@@ -49,6 +52,8 @@ export const setRenewOption = async ({
console.log(
`Auto-renew for ${domain} is ${autoRenew ? "enabled" : "disabled"}.`,
);
+
+ return true;
} catch (error) {
await log({
message: `Failed to set renew option for ${domain}: ${error instanceof Error ? error.message : String(error)}`,
@@ -57,5 +62,7 @@ export const setRenewOption = async ({
});
console.error(error);
+
+ return false;
}
};
diff --git a/apps/web/scripts/domains/sync-expires-at-from-dynadot.ts b/apps/web/scripts/domains/sync-expires-at-from-dynadot.ts
new file mode 100644
index 0000000000..5ce3da6759
--- /dev/null
+++ b/apps/web/scripts/domains/sync-expires-at-from-dynadot.ts
@@ -0,0 +1,60 @@
+import "dotenv-flow/config";
+
+import { parseRegisteredDomainSlugs } from "@/lib/api/domains/is-domain-registration-invoice";
+import { setRenewOption } from "@/lib/dynadot/set-renew-option";
+import { prisma } from "@/lib/prisma";
+import { chunk } from "@dub/utils";
+
+const invoiceId = "inv_1KXANFCDJ9MEYVQ94EM0VM84N";
+
+async function main() {
+ const invoice = await prisma.invoice.findUniqueOrThrow({
+ where: {
+ id: invoiceId,
+ },
+ select: {
+ id: true,
+ type: true,
+ registeredDomains: true,
+ },
+ });
+
+ const domains = parseRegisteredDomainSlugs(invoice.registeredDomains);
+
+ if (domains.length === 0) {
+ console.error("No domains found for invoice", invoiceId);
+ return;
+ }
+
+ console.log(`Found ${domains.length} domains for invoice`, invoiceId);
+
+ const domainChunks = chunk(domains, 10);
+
+ for (const domainChunk of domainChunks) {
+ await Promise.all(
+ domainChunk.map(async (domain) => {
+ const success = await setRenewOption({
+ domain,
+ autoRenew: true,
+ });
+
+ if (success) {
+ console.log(`✓ ${domain}`);
+ } else {
+ console.error(`✗ ${domain}`);
+ }
+ }),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ }
+}
+
+main()
+ .catch((error) => {
+ console.error(error);
+ process.exit(1);
+ })
+ .finally(async () => {
+ await prisma.$disconnect();
+ });