Repository navigation
Expand file tree
/
Copy pathtinybird.ts
More file actions
155 lines (151 loc) · 4.78 KB
/
Copy pathtinybird.ts
File metadata and controls
155 lines (151 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import {
EU_COUNTRY_CODES,
LOCALHOST_GEO_DATA,
LOCALHOST_IP,
capitalize,
getDomainWithoutWWW,
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 { ipAddress } from "@vercel/edge";
/**
* Recording clicks with geo, ua, referer and timestamp data
**/
export async function recordClick({
req,
id,
url,
root,
}: {
req: NextRequest;
id: string;
url?: string;
root?: boolean;
}) {
const isBot = detectBot(req);
if (isBot) {
return null;
}
const geo = process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA;
const ua = userAgent(req);
const referer = req.headers.get("referer");
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
const identity_hash = await getIdentityHash(req);
// if in production / preview env, deduplicate clicks from the same IP & link ID – only record 1 click per hour
if (process.env.VERCEL === "1") {
const { success } = await ratelimit(2, "1 h").limit(
`recordClick:${identity_hash}:${id}`,
);
if (!success) {
return null;
}
}
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 || "",
ip:
// only record IP if it's a valid IP and not from EU
typeof ip === "string" &&
ip.trim().length > 0 &&
(!geo?.country ||
(geo?.country && !EU_COUNTRY_CODES.includes(geo.country)))
? ip
: "",
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()),
// increment the click count for the link or domain (based on their ID)
// also increment the usage count for the workspace
// 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],
),
// only increment workspace clicks if there is a destination URL configured (not placeholder landing page)
url &&
conn.execute(
"UPDATE Project p JOIN Domain d ON p.id = d.projectId SET p.usage = p.usage + 1 WHERE d.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({
link,
deleted,
}: {
link: Partial<LinkProps> & {
tags?: { tagId: string }[];
};
deleted?: boolean;
}) {
return await fetch(
`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_links_metadata&wait=true`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
body: JSON.stringify({
timestamp: new Date(Date.now()).toISOString(),
link_id: link.id,
domain: link.domain,
key: link.key,
url: link.url,
tagIds: link.tags?.map(({ tagId }) => tagId) || [],
project_id: link.projectId || "",
deleted: deleted ? 1 : 0,
}),
},
).then((res) => res.json());
}