The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add token caching functionality
Kiran K8623440445b5
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.tsindex 2cce7ead2f..4943c4ba65 100644--- a/apps/web/app/api/tokens/[id]/route.ts+++ b/apps/web/app/api/tokens/[id]/route.ts@@ -2,8 +2,10 @@ import { DubApiError } from "@/lib/api/errors";import { validateScopesForRole } from "@/lib/api/tokens/scopes";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";+import { tokenCache } from "@/lib/auth/token-cache";import { tokenSchema, updateTokenSchema } from "@/lib/zod/schemas/token";import { prisma } from "@dub/prisma";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// GET /api/tokens/:id - get info about a specific token@@ -82,25 +84,18 @@ export const PATCH = withWorkspace(...(name && { name }),...(scopes && { scopes: [...new Set(scopes)].join(" ") }),},- select: {- id: true,- name: true,- partialKey: true,- scopes: true,- lastUsed: true,- createdAt: true,- updatedAt: true,- user: {- select: {- id: true,- name: true,- image: true,- isMachine: true,- },- },+ include: {+ user: true,},});+ waitUntil(+ tokenCache.set({+ hashedKey: token.hashedKey,+ token,+ }),+ );+return NextResponse.json(tokenSchema.parse(token));},{@@ -118,6 +113,7 @@ export const DELETE = withWorkspace(},select: {id: true,+ hashedKey: true,user: {select: {id: true,@@ -135,6 +131,12 @@ export const DELETE = withWorkspace(});}+ waitUntil(+ tokenCache.delete({+ hashedKey: token.hashedKey,+ }),+ );+return NextResponse.json({id: token.id,});diff --git a/apps/web/lib/auth/token-cache.ts b/apps/web/lib/auth/token-cache.tsnew file mode 100644index 0000000000..ed7f0f1411--- /dev/null+++ b/apps/web/lib/auth/token-cache.ts@@ -0,0 +1,57 @@+import { redis } from "@/lib/upstash";+import { z } from "zod";++const CACHE_EXPIRATION = 60 * 60 * 24; // 24 hours+const CACHE_KEY_PREFIX = "tokenCache";++const tokenCacheItemSchema = z.object({+ scopes: z.string().nullish(),+ rateLimit: z.number().nullish(),+ projectId: z.string().nullish(),+ expires: z.date().nullish(),+ installationId: z.string().nullish(),+ user: z.object({+ id: z.string(),+ name: z.string().nullable(),+ email: z.string().nullable(),+ isMachine: z.boolean(),+ }),+});++type TokenCacheItem = z.infer<typeof tokenCacheItemSchema>;++// Cache for the restricted tokens+class TokenCache {+ async set({+ hashedKey,+ token,+ }: {+ hashedKey: string;+ token: TokenCacheItem;+ }) {+ return await redis.set(+ this._createKey({ hashedKey }),+ JSON.stringify(tokenCacheItemSchema.parse(token)),+ {+ ex: CACHE_EXPIRATION,+ },+ );+ }++ async get({ hashedKey }: { hashedKey: string }) {+ return await redis.get<TokenCacheItem>(this._createKey({ hashedKey }));+ }++ async delete({ hashedKey }: { hashedKey: string }) {+ return await redis.del(this._createKey({ hashedKey }));+ }++ // TODO:+ // Delete the cache when the plan is updated, workspace is deleted, etc.++ _createKey({ hashedKey }: { hashedKey: string }) {+ return `${CACHE_KEY_PREFIX}:${hashedKey}`;+ }+}++export const tokenCache = new TokenCache();diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 2d235a4922..66ad62c2c4 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -15,6 +15,7 @@ import { normalizeWorkspaceId } from "../api/workspace-id";import { getFeatureFlags } from "../edge-config";import { logConversionEvent } from "../tinybird/log-conversion-events";import { hashToken } from "./hash-token";+import { tokenCache } from "./token-cache";import { Session, getSession } from "./utils";interface WithWorkspaceHandler {@@ -142,35 +143,44 @@ export const withWorkspace = (if (apiKey) {const hashedKey = await hashToken(apiKey);- const prismaArgs = {- where: {- hashedKey,- },- select: {- ...(isRestrictedToken && {- scopes: true,- rateLimit: true,- projectId: true,- expires: true,- installationId: true,- }),- user: {- select: {- id: true,- name: true,- email: true,- isMachine: true,++ const cachedToken = await tokenCache.get({+ hashedKey,+ });++ if (!cachedToken) {+ const prismaArgs = {+ where: {+ hashedKey,+ },+ select: {+ ...(isRestrictedToken && {+ scopes: true,+ rateLimit: true,+ projectId: true,+ expires: true,+ installationId: true,+ }),+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ isMachine: true,+ },},},- },- };+ };- if (isRestrictedToken) {- token = await prisma.restrictedToken.findUnique(prismaArgs);- } else {- token = await prisma.token.findUnique(prismaArgs);+ if (isRestrictedToken) {+ token = await prisma.restrictedToken.findUnique(prismaArgs);+ } else {+ token = await prisma.token.findUnique(prismaArgs);+ }}+ token = cachedToken || token;+if (!token || !token.user) {throw new DubApiError({code: "unauthorized",@@ -185,6 +195,15 @@ export const withWorkspace = (});}+ if (!cachedToken) {+ waitUntil(+ tokenCache.set({+ hashedKey,+ token,+ }),+ );+ }+// Rate limit checks for API keysconst rateLimit = token.rateLimit || 600;