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.

Record domain clicks, deduplicate clicks

Steven Tey93e1644618fd
diff --git a/apps/web/app/api/cron/domains/route.ts b/apps/web/app/api/cron/domains/route.ts
index 64f8bb7010..aafb52cf16 100644
--- a/apps/web/app/api/cron/domains/route.ts
+++ b/apps/web/app/api/cron/domains/route.ts
@@ -50,6 +50,7 @@ export async function POST(req: Request) {
slug: true,
verified: true,
primary: true,
+ clicks: true,
createdAt: true,
projectId: true,
_count: {
@@ -107,6 +108,7 @@ export async function POST(req: Request) {
verified: newVerified,
primary,
changed,
+ clicks: domain.clicks,
linksCount: _count.links,
});
diff --git a/apps/web/app/api/cron/domains/utils.ts b/apps/web/app/api/cron/domains/utils.ts
index 5f7e2e1155..63e2cb37b9 100644
--- a/apps/web/app/api/cron/domains/utils.ts
+++ b/apps/web/app/api/cron/domains/utils.ts
@@ -12,6 +12,7 @@ export const handleDomainUpdates = async ({
verified,
primary,
changed,
+ clicks,
linksCount,
}: {
domain: string;
@@ -19,6 +20,7 @@ export const handleDomainUpdates = async ({
verified: boolean;
primary: boolean;
changed: boolean;
+ clicks: number;
linksCount: number;
}) => {
if (changed) {
@@ -77,10 +79,15 @@ export const handleDomainUpdates = async ({
// if domain is invalid for more than 30 days, check if we can delete it
if (invalidDays >= 30) {
- // if there are still links associated with the domain,
- // and those links have clicks associated with them,
- // don't delete the domain (manual inspection required)
- if (linksCount > 0) {
+ // Don't delete the domain (manual inspection required) if:
+ // - the domain has clicks
+ // - there are still links associated with the domain and those links have clicks
+ if (clicks > 0) {
+ return await log({
+ message: `Domain *${domain}* has been invalid for > 30 days but has clicks, skipping.`,
+ type: "cron",
+ });
+ } else if (linksCount > 0) {
const linksClicks = await prisma.link.aggregate({
_sum: {
clicks: true,
@@ -91,7 +98,7 @@ export const handleDomainUpdates = async ({
});
if (linksClicks._sum?.clicks) {
return await log({
- message: `Domain *${domain}* has been invalid for > 30 days and has links with clicks, skipping.`,
+ message: `Domain *${domain}* has been invalid for > 30 days but has links with clicks, skipping.`,
type: "cron",
});
}
diff --git a/apps/web/app/api/projects/[slug]/domains/route.ts b/apps/web/app/api/projects/[slug]/domains/route.ts
index fa079deb55..54b7400506 100644
--- a/apps/web/app/api/projects/[slug]/domains/route.ts
+++ b/apps/web/app/api/projects/[slug]/domains/route.ts
@@ -19,6 +19,7 @@ export const GET = withAuth(async ({ project }) => {
primary: true,
target: true,
type: true,
+ clicks: true,
},
});
return NextResponse.json(domains);
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 0bbf494940..dcec598b4f 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -94,7 +94,7 @@ export default async function LinkMiddleware(
// only track the click when there is no `dub-no-track` header
if (!req.headers.get("dub-no-track")) {
- ev.waitUntil(recordClick(domain, req, key));
+ ev.waitUntil(recordClick({ domain, req, key }));
}
const isBot = detectBot(req);
diff --git a/apps/web/lib/middleware/root.ts b/apps/web/lib/middleware/root.ts
index e0897fd9ce..7dd2d742e6 100644
--- a/apps/web/lib/middleware/root.ts
+++ b/apps/web/lib/middleware/root.ts
@@ -15,7 +15,7 @@ export default async function RootMiddleware(
}
// record clicks on root page
- ev.waitUntil(recordClick(domain, req));
+ ev.waitUntil(recordClick({ domain, req }));
const response = await redis.get<{
target: string;
diff --git a/apps/web/lib/stats.ts b/apps/web/lib/stats.ts
index 4d42dbee76..0af503e374 100644
--- a/apps/web/lib/stats.ts
+++ b/apps/web/lib/stats.ts
@@ -129,14 +129,18 @@ export const getStats = async ({
// get all-time clicks count if:
// 1. endpoint is /clicks
- // 2. key is not _root
- // 3. interval is not defined
- // 4. there's a connection to MySQL
- if (endpoint === "clicks" && key !== "_root" && !interval && conn) {
- const response = await conn.execute(
- "SELECT clicks FROM Link WHERE domain = ? AND `key` = ?",
- [domain, decodeURIComponent(key)],
- );
+ // 2. interval is not defined
+ // 3. there's a connection to MySQL
+ if (endpoint === "clicks" && !interval && conn) {
+ const response =
+ key === "_root"
+ ? await conn.execute("SELECT clicks FROM Domain WHERE slug = ?", [
+ domain,
+ ])
+ : await conn.execute(
+ "SELECT clicks FROM Link WHERE domain = ? AND `key` = ?",
+ [domain, decodeURIComponent(key)],
+ );
try {
const clicks = response.rows[0]["clicks"];
return clicks || "0";
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 80793927ba..55520e3178 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -2,22 +2,37 @@ import {
LOCALHOST_GEO_DATA,
capitalize,
getDomainWithoutWWW,
+ LOCALHOST_IP,
} from "@dub/utils";
+import { ipAddress } from "@vercel/edge";
import { NextRequest, userAgent } from "next/server";
import { conn } from "./planetscale";
+import { ratelimit } from "./upstash";
/**
* Recording clicks with geo, ua, referer and timestamp data
* If key is not specified, record click as the root click ("_root", e.g. dub.sh, vercel.fyi)
**/
-export async function recordClick(
- domain: string,
- req: NextRequest,
- key?: string,
-) {
+export async function recordClick({
+ domain,
+ req,
+ key,
+}: {
+ domain: string;
+ req: NextRequest;
+ key?: string;
+}) {
const geo = process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA;
const ua = userAgent(req);
const referer = req.headers.get("referer");
+ const ip = ipAddress(req) || LOCALHOST_IP;
+ // deduplicate clicks from the same IP, domain and key – only record 1 click per hour
+ const { success } = await ratelimit(2, "1 h").limit(
+ `recordClick:${ip}:${domain}:${key}`,
+ );
+ if (!success) {
+ return null;
+ }
return await Promise.allSettled([
fetch(
@@ -56,12 +71,17 @@ export async function recordClick(
// increment the click count for the link if key is specified (not root click)
// also increment the usage count for the project, and then we have a cron that will reset it at the start of new billing cycle
// TODO: might wanna include root clicks in the usage count as well?
- ...(key && conn
+ ...(conn
? [
- conn.execute(
- "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE domain = ? AND `key` = ?",
- [domain, key],
- ),
+ key
+ ? conn.execute(
+ "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE domain = ? AND `key` = ?",
+ [domain, key],
+ )
+ : conn.execute(
+ "UPDATE Domain SET clicks = clicks + 1, lastClicked = NOW() WHERE slug = ?",
+ [domain],
+ ),
conn.execute(
"UPDATE Project p JOIN Domain d ON p.id = d.projectId SET p.usage = p.usage + 1 WHERE d.slug = ?",
[domain],
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 9123d990b5..aa1ce7d11c 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -69,6 +69,7 @@ export interface DomainProps {
primary: boolean;
target?: string;
type: "redirect" | "rewrite";
+ clicks: number;
}
export interface BitlyGroupProps {
diff --git a/apps/web/package.json b/apps/web/package.json
index d60027ef30..f984575dbd 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -98,6 +98,7 @@
"array-to-ndjson": "^1.0.1",
"autoprefixer": "^10.4.16",
"dotenv-flow": "^4.0.0",
+ "papaparse": "^5.4.1",
"postcss": "^8.4.31",
"postcss-import": "^15.1.0",
"prettier": "^2.8.0",
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 096129a98c..349d314108 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -162,11 +162,15 @@ model Domain {
projectId String?
primary Boolean @default(false)
links Link[]
+ clicks Int @default(0)
+ lastClicked DateTime? // when the link was last clicked
lastChecked DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index(projectId)
+ @@index(clicks(sort: Desc))
+ @@index(lastClicked)
@@index(lastChecked)
}
diff --git a/apps/web/scripts/run.ts b/apps/web/scripts/run.ts
index 43b98c5dd8..1e2099dd48 100644
--- a/apps/web/scripts/run.ts
+++ b/apps/web/scripts/run.ts
@@ -10,11 +10,15 @@ if (!command) {
const scriptPath = `./scripts/${command}.ts`;
-exec(`tsx ${scriptPath}`, (error, stdout, stderr) => {
- if (error) {
- console.error(`Error executing script: ${error.message}`);
- return;
- }
- console.log(stdout);
- console.error(stderr);
-});
+exec(
+ `tsx ${scriptPath}`,
+ { maxBuffer: 1024 * 5000 },
+ (error, stdout, stderr) => {
+ if (error) {
+ console.error(`Error executing script: ${error.message}`);
+ return;
+ }
+ console.log(stdout);
+ console.error(stderr);
+ },
+);
diff --git a/apps/web/scripts/sync-domain-clicks.ts b/apps/web/scripts/sync-domain-clicks.ts
new file mode 100644
index 0000000000..03474c7cbc
--- /dev/null
+++ b/apps/web/scripts/sync-domain-clicks.ts
@@ -0,0 +1,36 @@
+import "dotenv-flow/config";
+import * as Papa from "papaparse";
+import * as fs from "fs";
+import prisma from "@/lib/prisma";
+
+const domainClicks: { domain: string; clicks: string }[] = [];
+
+async function main() {
+ Papa.parse(fs.createReadStream("sql.csv", "utf-8"), {
+ header: true,
+ step: (result: { data: { domain: string; clicks: string } }) => {
+ domainClicks.push(result.data);
+ },
+ complete: async () => {
+ console.table(domainClicks.slice(0, 50));
+ domainClicks.forEach(async (domainClick) => {
+ const { domain, clicks } = domainClick;
+ try {
+ await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ clicks: parseInt(clicks),
+ },
+ });
+ console.log(`Updated ${domain} with ${clicks} clicks.`);
+ } catch (e) {
+ console.log(`${domain} doesn't exist, skipping.`);
+ }
+ });
+ },
+ });
+}
+
+main();
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index 4a9db94186..6299f940f1 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -32,6 +32,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
slug && `/api/projects/${slug}/stats/clicks?domain=${domain}&key=_root`,
fetcher,
{
+ fallbackData: props.clicks,
dedupingInterval: 15000,
},
);
diff --git a/apps/web/ui/modals/add-edit-domain-modal.tsx b/apps/web/ui/modals/add-edit-domain-modal.tsx
index 0f7f78d735..3c840df923 100644
--- a/apps/web/ui/modals/add-edit-domain-modal.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal.tsx
@@ -41,6 +41,7 @@ function AddEditDomainModal({
primary: false,
target: "",
type: "redirect",
+ clicks: 0,
},
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e2bbcad43e..bce702e908 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -287,6 +287,9 @@ importers:
dotenv-flow:
specifier: ^4.0.0
version: 4.0.0
+ papaparse:
+ specifier: ^5.4.1
+ version: 5.4.1
postcss:
specifier: ^8.4.31
version: 8.4.31
@@ -12434,6 +12437,10 @@ packages:
resolution: {integrity: sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==}
dev: false
+ resolution: {integrity: sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw==}
+ dev: true
+
resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}
engines: {node: '>=6'}