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.

async usage updates

Steven Teyb73a52a57aa0
diff --git a/apps/web/app/api/cron/clicks/route.ts b/apps/web/app/api/cron/clicks/route.ts
new file mode 100644
index 0000000000..be5f13637d
--- /dev/null
+++ b/apps/web/app/api/cron/clicks/route.ts
@@ -0,0 +1,37 @@
+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.all(
+ 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
new file mode 100644
index 0000000000..9d913e846e
--- /dev/null
+++ b/apps/web/app/api/cron/clicks/usage/route.ts
@@ -0,0 +1,37 @@
+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.all(
+ 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
new file mode 100644
index 0000000000..4396cc8df3
--- /dev/null
+++ b/apps/web/app/api/cron/clicks/utils.ts
@@ -0,0 +1,36 @@
+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],
+ );
+ }
+
+ 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/tinybird.ts b/apps/web/lib/tinybird.ts
index 0461565a9f..979c37938b 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -5,11 +5,10 @@ import {
nanoid,
} from "@dub/utils";
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";
-import { getIdentityHash } from "./edge";
/**
* Recording clicks with geo, ua, referer and timestamp data
@@ -43,65 +42,44 @@ export async function recordClick({
}
}
- 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)",
- }),
+ 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}`,
},
- ).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],
- ),
- ],
- ]);
+ 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());
}
export async function recordLink({
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 8849bd0367..a6908a78a2 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -1,5 +1,13 @@
{
"crons": [
+ {
+ "path": "/api/cron/clicks",
+ "schedule": "* * * * *"
+ },
+ {
+ "path": "/api/cron/clicks/usage",
+ "schedule": "0 * * * *"
+ },
{
"path": "/api/cron/domains",
"schedule": "0 */3 * * *"