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.

remove reliance on workspaceCache

Steven Tey367e89f6e2be
diff --git a/apps/web/app/api/track/click/route.ts b/apps/web/app/api/track/click/route.ts
index eda4f7b852..d64b07851a 100644
--- a/apps/web/app/api/track/click/route.ts
+++ b/apps/web/app/api/track/click/route.ts
@@ -3,7 +3,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { clickCache } from "@/lib/api/links/click-cache";
import { parseRequestBody } from "@/lib/api/utils";
-import { workspaceCache } from "@/lib/api/workspaces/cache";
+import { getWorkspaceViaEdge } from "@/lib/planetscale";
import { getLinkWithPartner } from "@/lib/planetscale/get-link-with-partner";
import { recordClick } from "@/lib/tinybird";
import { formatRedisLink } from "@/lib/upstash";
@@ -98,18 +98,6 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
});
}
- const allowedHostnames = await workspaceCache.get({
- id: cachedLink.projectId,
- key: "allowedHostnames",
- });
-
- if (allowedHostnames) {
- verifyAnalyticsAllowedHostnames({
- allowedHostnames,
- req,
- });
- }
-
const finalUrl = url
? isValidUrl(url)
? url
@@ -117,18 +105,30 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
: cachedLink.url;
waitUntil(
- recordClick({
- req,
- clickId,
- linkId: cachedLink.id,
- domain,
- key,
- url: finalUrl,
- workspaceId: cachedLink.projectId,
- skipRatelimit: true,
- ...(referrer && { referrer }),
- trackConversion: cachedLink.trackConversion,
- }),
+ (async () => {
+ const workspace = await getWorkspaceViaEdge(cachedLink.projectId!);
+ const allowedHostnames = workspace?.allowedHostnames as string[];
+
+ if (
+ verifyAnalyticsAllowedHostnames({
+ allowedHostnames,
+ req,
+ })
+ ) {
+ await recordClick({
+ req,
+ clickId,
+ linkId: cachedLink.id,
+ domain,
+ key,
+ url: finalUrl,
+ workspaceId: cachedLink.projectId,
+ skipRatelimit: true,
+ ...(referrer && { referrer }),
+ trackConversion: cachedLink.trackConversion,
+ });
+ }
+ })(),
);
const isPartnerLink = Boolean(cachedLink.programId && cachedLink.partnerId);
diff --git a/apps/web/app/api/track/visit/route.ts b/apps/web/app/api/track/visit/route.ts
index 56a87fb196..3313b49e56 100644
--- a/apps/web/app/api/track/visit/route.ts
+++ b/apps/web/app/api/track/visit/route.ts
@@ -1,9 +1,11 @@
import { verifyAnalyticsAllowedHostnames } from "@/lib/analytics/verify-analytics-allowed-hostnames";
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { linkCache } from "@/lib/api/links/cache";
import { clickCache } from "@/lib/api/links/click-cache";
import { parseRequestBody } from "@/lib/api/utils";
-import { getLinkWithAllowedHostnames } from "@/lib/planetscale/get-link-with-allowed-hostnames";
+import { getLinkViaEdge, getWorkspaceViaEdge } from "@/lib/planetscale";
import { recordClick } from "@/lib/tinybird";
+import { formatRedisLink } from "@/lib/upstash";
import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
import { ipAddress, waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
@@ -38,45 +40,72 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
- let clickId = await clickCache.get({ domain, key, ip });
+ let clickId = await clickCache.get({
+ domain,
+ key,
+ ip,
+ });
- // only generate + record a new click ID if it's not already cached in Redis
- if (!clickId) {
- clickId = nanoid(16);
+ // if the clickId is already cached in Redis, return it
+ if (clickId) {
+ return NextResponse.json({ clickId }, { headers: CORS_HEADERS });
+ }
+
+ // Otherwise, track the visit event
+ clickId = nanoid(16);
- let link = await getLinkWithAllowedHostnames(domain, key);
+ let cachedLink = await linkCache.get({
+ domain,
+ key,
+ });
+
+ if (!cachedLink) {
+ const link = await getLinkViaEdge({
+ domain,
+ key,
+ });
if (!link) {
- return NextResponse.json(
- {
- clickId: null,
- },
- {
- headers: CORS_HEADERS,
- },
- );
+ throw new DubApiError({
+ code: "not_found",
+ message: `Link not found for domain: ${domain} and key: ${key}.`,
+ });
}
- const allowedHostnames = link.allowedHostnames;
- verifyAnalyticsAllowedHostnames({ allowedHostnames, req });
-
- const finalUrl = isValidUrl(url) ? url : link.url;
-
- waitUntil(
- recordClick({
- req,
- clickId,
- linkId: link.id,
- domain,
- key,
- url: finalUrl,
- workspaceId: link.projectId,
- skipRatelimit: true,
- ...(referrer && { referrer }),
- }),
- );
+ cachedLink = formatRedisLink(link as any);
+
+ waitUntil(linkCache.set(link as any));
}
+ const finalUrl = isValidUrl(url) ? url : cachedLink.url;
+
+ waitUntil(
+ (async () => {
+ const workspace = await getWorkspaceViaEdge(cachedLink.projectId!);
+ const allowedHostnames = workspace?.allowedHostnames as string[];
+
+ if (
+ verifyAnalyticsAllowedHostnames({
+ allowedHostnames,
+ req,
+ })
+ ) {
+ await recordClick({
+ req,
+ clickId,
+ linkId: cachedLink.id,
+ domain,
+ key,
+ url: finalUrl,
+ workspaceId: cachedLink.projectId,
+ skipRatelimit: true,
+ ...(referrer && { referrer }),
+ trackConversion: cachedLink.trackConversion,
+ });
+ }
+ })(),
+ );
+
return NextResponse.json(
{
clickId,
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 237e4aae51..64764319f0 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -3,7 +3,6 @@ import { parseRequestBody } from "@/lib/api/utils";
import { validateAllowedHostnames } from "@/lib/api/validate-allowed-hostnames";
import { prefixWorkspaceId } from "@/lib/api/workspace-id";
import { deleteWorkspace } from "@/lib/api/workspaces";
-import { workspaceCache } from "@/lib/api/workspaces/cache";
import { withWorkspace } from "@/lib/auth";
import { getFeatureFlags } from "@/lib/edge-config";
import { storage } from "@/lib/storage";
@@ -111,22 +110,9 @@ export const PATCH = withWorkspace(
});
}
- waitUntil(
- (async () => {
- if (logoUploaded && workspace.logo) {
- await storage.delete(workspace.logo.replace(`${R2_URL}/`, ""));
- }
-
- if (validHostnames) {
- workspaceCache.set({
- id: workspace.id,
- data: {
- allowedHostnames: validHostnames,
- },
- });
- }
- })(),
- );
+ if (logoUploaded && workspace.logo) {
+ waitUntil(storage.delete(workspace.logo.replace(`${R2_URL}/`, "")));
+ }
return NextResponse.json(
WorkspaceSchema.parse({
diff --git a/apps/web/lib/analytics/verify-analytics-allowed-hostnames.ts b/apps/web/lib/analytics/verify-analytics-allowed-hostnames.ts
index 369eb7a923..094d655915 100644
--- a/apps/web/lib/analytics/verify-analytics-allowed-hostnames.ts
+++ b/apps/web/lib/analytics/verify-analytics-allowed-hostnames.ts
@@ -1,5 +1,3 @@
-import { DubApiError } from "../api/errors";
-
export const verifyAnalyticsAllowedHostnames = ({
allowedHostnames,
req,
@@ -7,22 +5,13 @@ export const verifyAnalyticsAllowedHostnames = ({
allowedHostnames: string[];
req: Request;
}) => {
- if (allowedHostnames && allowedHostnames.length > 0) {
+ if (allowedHostnames.length > 0) {
const source = req.headers.get("referer") || req.headers.get("origin");
const sourceUrl = source ? new URL(source) : null;
const hostname = sourceUrl?.hostname.replace(/^www\./, "");
- if (!hostname || !allowedHostnames.includes(hostname)) {
- console.error("Hostname not allowed.", {
- hostname,
- allowedHostnames,
- });
- throw new DubApiError({
- code: "forbidden",
- message: `Hostname ${hostname} not included in allowed hostnames (${allowedHostnames.join(
- ", ",
- )}).`,
- });
- }
+ return hostname && allowedHostnames.includes(hostname);
}
+
+ return true;
};
diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.ts
index c5415d6b80..71de693888 100644
--- a/apps/web/lib/api/workspaces.ts
+++ b/apps/web/lib/api/workspaces.ts
@@ -13,7 +13,6 @@ import { qstash } from "../cron";
import { cancelSubscription } from "../stripe/cancel-subscription";
import { markDomainAsDeleted } from "./domains";
import { linkCache } from "./links/cache";
-import { workspaceCache } from "./workspaces/cache";
export async function deleteWorkspace(
workspace: Pick<WorkspaceProps, "id" | "slug" | "logo" | "stripeId">,
@@ -58,8 +57,6 @@ export async function deleteWorkspace(
queueWorkspaceDeletion({
workspaceId: workspace.id,
}),
-
- workspaceCache.delete(workspace.id),
]),
);
}
diff --git a/apps/web/lib/api/workspaces/cache.ts b/apps/web/lib/api/workspaces/cache.ts
deleted file mode 100644
index 521b08d26b..0000000000
--- a/apps/web/lib/api/workspaces/cache.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { redis } from "@/lib/upstash";
-
-interface CacheProps {
- allowedHostnames: string[];
-}
-
-class WorkspaceCache {
- async set({ id, data }: { id: string; data: CacheProps }) {
- return await redis.hset(this._createKey(id), {
- ...data,
- });
- }
-
- async get<K extends keyof CacheProps>({
- id,
- key,
- }: {
- id: string;
- key: K;
- }): Promise<CacheProps[K] | null> {
- return await redis.hget<CacheProps[K]>(this._createKey(id), key);
- }
-
- async delete(id: string) {
- return await redis.del(this._createKey(id));
- }
-
- _createKey(id: string) {
- return `workspace:${id}`;
- }
-}
-
-export const workspaceCache = new WorkspaceCache();
diff --git a/apps/web/scripts/set-workspace-cache.ts b/apps/web/scripts/set-workspace-cache.ts
deleted file mode 100644
index 8577db389d..0000000000
--- a/apps/web/scripts/set-workspace-cache.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { workspaceCache } from "@/lib/api/workspaces/cache";
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-
-async function main() {
- const workspaces = await prisma.project.findMany({
- where: {
- allowedHostnames: {
- // @ts-ignore
- not: null,
- },
- },
- select: {
- id: true,
- allowedHostnames: true,
- },
- });
-
- console.log(`Setting cache for ${workspaces.length} workspaces`);
-
- await Promise.all(
- workspaces.map((workspace) => {
- workspaceCache.set({
- id: workspace.id,
- data: {
- allowedHostnames: workspace.allowedHostnames as string[],
- },
- });
- }),
- );
-}
-
-main();