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.

revert for now

Steven Tey3a1c9f35068e
diff --git a/apps/web/app/api/cron/clicks/route.ts b/apps/web/app/api/cron/clicks/route.ts
deleted file mode 100644
index 1ef31d5e1f..0000000000
--- a/apps/web/app/api/cron/clicks/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { verifySignature } from "@/lib/cron";
-import { NextResponse } from "next/server";
-import { updateLinkOrDomain } from "./utils";
-
-export const runtime = "edge";
-
-export async function GET(req: Request) {
- const validSignature = await verifySignature(req);
- if (!validSignature) {
- return new Response("Unauthorized", { status: 401 });
- }
-
- const data = (await fetch(
- `${process.env.TINYBIRD_API_URL}/v0/pipes/cron_clicks.json`,
- {
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- },
- )
- .then((res) => res.json())
- .then(({ data }) => data)) as {
- link_id: string;
- clicks: number;
- }[];
-
- await Promise.allSettled(
- data.map(({ link_id: id, clicks }) =>
- updateLinkOrDomain({
- id,
- clicks,
- }),
- ),
- );
-
- return NextResponse.json(data);
-}
diff --git a/apps/web/app/api/cron/clicks/usage/route.ts b/apps/web/app/api/cron/clicks/usage/route.ts
deleted file mode 100644
index eaed447a29..0000000000
--- a/apps/web/app/api/cron/clicks/usage/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { verifySignature } from "@/lib/cron";
-import { NextResponse } from "next/server";
-import { updateProjectUsage } from "../utils";
-
-export const runtime = "edge";
-
-export async function GET(req: Request) {
- const validSignature = await verifySignature(req);
- if (!validSignature) {
- return new Response("Unauthorized", { status: 401 });
- }
-
- const data = (await fetch(
- `${process.env.TINYBIRD_API_URL}/v0/pipes/cron_clicks_usage.json`,
- {
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- },
- )
- .then((res) => res.json())
- .then(({ data }) => data)) as {
- project_id: string;
- clicks: number;
- }[];
-
- await Promise.allSettled(
- data.map(({ project_id: projectId, clicks }) =>
- updateProjectUsage({
- projectId,
- clicks,
- }),
- ),
- );
-
- return NextResponse.json(data);
-}
diff --git a/apps/web/app/api/cron/clicks/utils.ts b/apps/web/app/api/cron/clicks/utils.ts
deleted file mode 100644
index 9854b983d5..0000000000
--- a/apps/web/app/api/cron/clicks/utils.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { conn } from "@/lib/planetscale";
-
-export async function updateLinkOrDomain({
- id,
- clicks,
-}: {
- id: string;
- clicks: number;
-}) {
- let res = await conn.execute(
- "UPDATE Link SET clicks = clicks + ?, lastClicked = NOW() WHERE id = ?",
- [clicks, id],
- );
-
- if (res.rowsAffected === 0) {
- res = await conn.execute(
- "UPDATE Domain SET clicks = clicks + ?, lastClicked = NOW() WHERE id = ?",
- [clicks, id],
- );
- }
- console.log(res);
-
- return res;
-}
-
-export async function updateProjectUsage({
- projectId,
- clicks,
-}: {
- projectId: string;
- clicks: number;
-}) {
- return await conn.execute(
- "UPDATE Project SET usage = usage + ? WHERE id = ?",
- [clicks, projectId],
- );
-}
diff --git a/apps/web/lib/middleware/root.ts b/apps/web/lib/middleware/root.ts
index 87d53849ff..9599f67e34 100644
--- a/apps/web/lib/middleware/root.ts
+++ b/apps/web/lib/middleware/root.ts
@@ -39,7 +39,7 @@ export default async function RootMiddleware(
const { id, url, rewrite, iframeable } = link;
// record clicks on root page
- ev.waitUntil(recordClick({ req, id, ...(url && { url }) }));
+ ev.waitUntil(recordClick({ req, id, ...(url && { url }), root: true }));
if (!url) {
// rewrite to placeholder page unless the user defines a site to redirect to
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 147f45722e..7f438cfc71 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -7,6 +7,7 @@ import {
import { NextRequest, userAgent } from "next/server";
import { getIdentityHash } from "./edge";
import { detectBot } from "./middleware/utils";
+import { conn } from "./planetscale";
import { LinkProps } from "./types";
import { ratelimit } from "./upstash";
@@ -17,10 +18,12 @@ export async function recordClick({
req,
id,
url,
+ root,
}: {
req: NextRequest;
id: string;
url?: string;
+ root?: boolean;
}) {
const isBot = detectBot(req);
if (isBot) {
@@ -40,44 +43,65 @@ export async function recordClick({
}
}
- return await fetch(
- `${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
+ return await Promise.allSettled([
+ fetch(
+ `${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
+ },
+ body: JSON.stringify({
+ timestamp: new Date(Date.now()).toISOString(),
+ identity_hash,
+ click_id: nanoid(16),
+ link_id: id,
+ alias_link_id: "",
+ url: url || "",
+ country: geo?.country || "Unknown",
+ city: geo?.city || "Unknown",
+ region: geo?.region || "Unknown",
+ latitude: geo?.latitude || "Unknown",
+ longitude: geo?.longitude || "Unknown",
+ device: ua.device.type ? capitalize(ua.device.type) : "Desktop",
+ device_vendor: ua.device.vendor || "Unknown",
+ device_model: ua.device.model || "Unknown",
+ browser: ua.browser.name || "Unknown",
+ browser_version: ua.browser.version || "Unknown",
+ engine: ua.engine.name || "Unknown",
+ engine_version: ua.engine.version || "Unknown",
+ os: ua.os.name || "Unknown",
+ os_version: ua.os.version || "Unknown",
+ cpu_architecture: ua.cpu?.architecture || "Unknown",
+ ua: ua.ua || "Unknown",
+ bot: ua.isBot,
+ referer: referer
+ ? getDomainWithoutWWW(referer) || "(direct)"
+ : "(direct)",
+ referer_url: referer || "(direct)",
+ }),
},
- body: JSON.stringify({
- timestamp: new Date(Date.now()).toISOString(),
- identity_hash,
- click_id: nanoid(16),
- link_id: id,
- alias_link_id: "",
- url: url || "",
- country: geo?.country || "Unknown",
- city: geo?.city || "Unknown",
- region: geo?.region || "Unknown",
- latitude: geo?.latitude || "Unknown",
- longitude: geo?.longitude || "Unknown",
- device: ua.device.type ? capitalize(ua.device.type) : "Desktop",
- device_vendor: ua.device.vendor || "Unknown",
- device_model: ua.device.model || "Unknown",
- browser: ua.browser.name || "Unknown",
- browser_version: ua.browser.version || "Unknown",
- engine: ua.engine.name || "Unknown",
- engine_version: ua.engine.version || "Unknown",
- os: ua.os.name || "Unknown",
- os_version: ua.os.version || "Unknown",
- cpu_architecture: ua.cpu?.architecture || "Unknown",
- ua: ua.ua || "Unknown",
- bot: ua.isBot,
- referer: referer
- ? getDomainWithoutWWW(referer) || "(direct)"
- : "(direct)",
- referer_url: referer || "(direct)",
- }),
- },
- ).then((res) => res.json());
+ ).then((res) => res.json()),
+
+ // increment the click count for the link or domain (based on their ID)
+ // also increment the usage count for the project (if it's a link click)
+ // and then we have a cron that will reset it at the start of new billing cycle
+ root
+ ? conn.execute(
+ "UPDATE Domain SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
+ [id],
+ )
+ : [
+ conn.execute(
+ "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
+ [id],
+ ),
+ conn.execute(
+ "UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1 WHERE l.id = ?",
+ [id],
+ ),
+ ],
+ ]);
}
export async function recordLink({
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 89e6fa287f..8849bd0367 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -1,13 +1,5 @@
{
"crons": [
- {
- "path": "/api/cron/clicks",
- "schedule": "* * * * *"
- },
- {
- "path": "/api/cron/clicks/usage",
- "schedule": "*/30 * * * *"
- },
{
"path": "/api/cron/domains",
"schedule": "0 */3 * * *"