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.

updated cron jobs implementation

Steven Tey91cc76336f49
diff --git a/pages/api/cron/domains.ts b/app/api/cron/domains/route.ts
similarity index 77%
rename from pages/api/cron/domains.ts
rename to app/api/cron/domains/route.ts
index c140573fbe..727426693c 100644
--- a/pages/api/cron/domains.ts
+++ b/app/api/cron/domains/route.ts
@@ -1,6 +1,6 @@
-import type { NextApiRequest, NextApiResponse } from "next";
-import { verifySignature } from "@upstash/qstash/nextjs";
-import { handleDomainUpdates } from "#/lib/cron/domains";
+import { NextResponse } from "next/server";
+import { receiver } from "#/lib/cron";
+import { handleDomainUpdates } from "./utils";
import {
getConfigResponse,
getDomainResponse,
@@ -17,7 +17,18 @@ import { log } from "#/lib/utils";
* If a domain is invalid for more than 30 days, we delete it from the database.
**/
-async function handler(_req: NextApiRequest, res: NextApiResponse) {
+export async function POST(req: Request) {
+ if (process.env.VERCEL === "1") {
+ const body = await req.json();
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
try {
const domains = await prisma.domain.findMany({
where: {
@@ -107,34 +118,13 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
};
}),
);
- res.status(200).json(results);
+ return NextResponse.json(results);
} catch (error) {
await log({
message: "Domains cron failed. Error: " + error.message,
type: "cron",
mention: true,
});
- res.status(500).json({ error: error.message });
+ return NextResponse.json({ error: error.message });
}
}
-
-/**
- * verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.
-
- * This will only run in production. In development, it will return the handler without verifying the signature.
- */
-const Cron = () => {
- if (process.env.NODE_ENV === "development") {
- return handler;
- } else {
- return verifySignature(handler);
- }
-};
-
-export default Cron();
-
-export const config = {
- api: {
- bodyParser: false,
- },
-};
diff --git a/lib/cron/domains.tsx b/app/api/cron/domains/utils.ts
similarity index 97%
rename from lib/cron/domains.tsx
rename to app/api/cron/domains/utils.ts
index 2c9aaf8a39..a1121190df 100644
--- a/lib/cron/domains.tsx
+++ b/app/api/cron/domains/utils.ts
@@ -4,7 +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";
+import { limiter } from "#/lib/cron";
export const handleDomainUpdates = async ({
domain,
@@ -145,7 +145,6 @@ export const handleDomainUpdates = async ({
);
if (!sentSecondDomainInvalidEmail) {
return sendDomainInvalidEmail({
- projectName,
projectSlug,
domain,
invalidDays,
@@ -161,7 +160,6 @@ export const handleDomainUpdates = async ({
);
if (!sentFirstDomainInvalidEmail) {
return sendDomainInvalidEmail({
- projectName,
projectSlug,
domain,
invalidDays,
@@ -174,14 +172,12 @@ export const handleDomainUpdates = async ({
};
const sendDomainInvalidEmail = async ({
- projectName,
projectSlug,
domain,
invalidDays,
emails,
type,
}: {
- projectName: string;
projectSlug: string;
domain: string;
invalidDays: number;
diff --git a/app/api/cron/import/bitly/route.ts b/app/api/cron/import/bitly/route.ts
index 8cba536333..b547e26178 100644
--- a/app/api/cron/import/bitly/route.ts
+++ b/app/api/cron/import/bitly/route.ts
@@ -4,7 +4,7 @@ import { redis } from "#/lib/upstash";
import { NextResponse } from "next/server";
import prisma from "#/lib/prisma";
import { randomBadgeColor } from "@/components/app/links/tag-badge";
-import { receiver } from "#/lib/cron/utils";
+import { receiver } from "#/lib/cron";
export async function POST(req: Request) {
const body = await req.json();
diff --git a/app/api/cron/import/short/route.ts b/app/api/cron/import/short/route.ts
index 9709787023..63c9d3be37 100644
--- a/app/api/cron/import/short/route.ts
+++ b/app/api/cron/import/short/route.ts
@@ -1,7 +1,7 @@
import { log } from "#/lib/utils";
import { redis } from "#/lib/upstash";
import { NextResponse } from "next/server";
-import { receiver } from "#/lib/cron/utils";
+import { receiver } from "#/lib/cron";
import { importLinksFromShort } from "./utils";
export async function POST(req: Request) {
diff --git a/app/api/cron/usage/route.ts b/app/api/cron/usage/route.ts
new file mode 100644
index 0000000000..71c563ddda
--- /dev/null
+++ b/app/api/cron/usage/route.ts
@@ -0,0 +1,34 @@
+import { log } from "#/lib/utils";
+import { updateUsage } from "./utils";
+import { NextResponse } from "next/server";
+import { receiver } from "#/lib/cron";
+
+/**
+ * Cron to update the usage stats of each project.
+ * Runs once every day at 7AM PST.
+ **/
+
+export async function POST(req: Request) {
+ if (process.env.VERCEL === "1") {
+ const body = await req.json();
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
+ try {
+ const results = await updateUsage();
+ return NextResponse.json(results);
+ } catch (error) {
+ await log({
+ message: "Usage cron failed. Error: " + error.message,
+ type: "cron",
+ mention: true,
+ });
+ return NextResponse.json({ error: error.message });
+ }
+}
diff --git a/lib/cron/usage.tsx b/app/api/cron/usage/utils.ts
similarity index 93%
rename from lib/cron/usage.tsx
rename to app/api/cron/usage/utils.ts
index b78f04b03f..d17ae43c60 100644
--- a/lib/cron/usage.tsx
+++ b/app/api/cron/usage/utils.ts
@@ -5,7 +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";
+import { limiter } from "#/lib/cron";
export const updateUsage = async () => {
const projects = await prisma.project.findMany({
@@ -39,10 +39,14 @@ export const updateUsage = async () => {
},
});
- // Get all paid projects that have billingCycleStart today
+ // Reset billing cycles for projects that:
+ // - Are not on the free plan
+ // - Are on the free plan but have not exceeded usage
+ // - Have billingCycleStart today
const billingReset = projects.filter(
- ({ plan, billingCycleStart }) =>
- plan !== "free" && billingCycleStart === new Date().getDate(),
+ ({ usage, usageLimit, plan, billingCycleStart }) =>
+ !(plan === "free" && usage > usageLimit) &&
+ billingCycleStart === new Date().getDate(),
);
// Get all projects that have exceeded usage
diff --git a/lib/cron/utils.ts b/lib/cron.ts
similarity index 100%
rename from lib/cron/utils.ts
rename to lib/cron.ts
diff --git a/pages/api/cron/usage.ts b/pages/api/cron/usage.ts
deleted file mode 100644
index f10a2f2fe2..0000000000
--- a/pages/api/cron/usage.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { NextApiRequest, NextApiResponse } from "next";
-import { verifySignature } from "@upstash/qstash/nextjs";
-import { updateUsage } from "#/lib/cron/usage";
-import { log } from "#/lib/utils";
-
-/**
- * Cron to update the usage stats of each project.
- * Runs once every day at 7AM PST.
- **/
-
-async function handler(_req: NextApiRequest, res: NextApiResponse) {
- try {
- const results = await updateUsage();
- res.status(200).json(results);
- } catch (error) {
- await log({
- message: "Usage cron failed. Error: " + error.message,
- type: "cron",
- mention: true,
- });
- res.status(500).json({ error: error.message });
- }
-}
-
-/**
- * verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.
-
- * This will only run in production. In development, it will return the handler without verifying the signature.
- */
-const Cron = () => {
- if (process.env.NODE_ENV === "development") {
- return handler;
- } else {
- return verifySignature(handler);
- }
-};
-
-export default Cron();
-
-export const config = {
- api: {
- bodyParser: false,
- },
-};
diff --git a/pages/api/projects/[slug]/import/bitly.ts b/pages/api/projects/[slug]/import/bitly.ts
index 746de8a62c..365e046e9d 100644
--- a/pages/api/projects/[slug]/import/bitly.ts
+++ b/pages/api/projects/[slug]/import/bitly.ts
@@ -1,7 +1,7 @@
import { addDomainToVercel } from "#/lib/api/domains";
import { withProjectAuth } from "#/lib/auth";
import { APP_DOMAIN_WITH_NGROK } from "#/lib/constants";
-import { qstash } from "#/lib/cron/utils";
+import { qstash } from "#/lib/cron";
import prisma from "#/lib/prisma";
import { BitlyGroupProps } from "#/lib/types";
import { redis } from "#/lib/upstash";
diff --git a/pages/api/projects/[slug]/import/short.ts b/pages/api/projects/[slug]/import/short.ts
index d155eebfcc..77ad5a33d4 100644
--- a/pages/api/projects/[slug]/import/short.ts
+++ b/pages/api/projects/[slug]/import/short.ts
@@ -1,7 +1,7 @@
import { addDomainToVercel } from "#/lib/api/domains";
import { withProjectAuth } from "#/lib/auth";
import { APP_DOMAIN_WITH_NGROK } from "#/lib/constants";
-import { qstash } from "#/lib/cron/utils";
+import { qstash } from "#/lib/cron";
import prisma from "#/lib/prisma";
import { ShortioDomainProps } from "#/lib/types";
import { redis } from "#/lib/upstash";