Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add KV cache layer for machine token and member lookups
Gener9f959d89a993
diff --git a/src/web/src/app/api/members/me/route.ts b/src/web/src/app/api/members/me/route.tsindex ac13d01e3..4cf8d17e1 100644--- a/src/web/src/app/api/members/me/route.ts+++ b/src/web/src/app/api/members/me/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";+import { invalidate, cacheKeys } from "@/lib/cache";export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -41,5 +42,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {);if (!updated) return writeError("member not found", 404);+ await invalidate(cacheKeys.member(ws.workspaceId, ctx.userId));+return writeJSON({ global_instruction: updated.globalInstruction });});diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex b14c26146..4cbd47187 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -16,6 +16,7 @@ declare namespace Cloudflare {BETTER_AUTH_URL: stringENCRYPTION_KEY: stringRATE_LIMIT_KV: KVNamespace+ CACHE_KV: KVNamespaceAUTH_OTP_RATE_LIMIT_MAX?: stringAUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringRUNTIME_MODEL_OPTIONS?: stringdiff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.tsnew file mode 100644index 000000000..b1b830bc8--- /dev/null+++ b/src/web/src/lib/cache.ts@@ -0,0 +1,41 @@+let _kv: KVNamespace | null | undefined;++export function bindCacheKV(kv: KVNamespace | null) {+ _kv = kv;+}++function getKV(): KVNamespace | null {+ return _kv ?? null;+}++export async function cached<T>(+ key: string,+ ttlSeconds: number,+ fn: () => Promise<T>,+): Promise<T> {+ const kv = getKV();+ if (kv) {+ try {+ const raw = await kv.get(key);+ if (raw) return JSON.parse(raw) as T;+ } catch {}+ }++ const value = await fn();++ if (value != null && kv) {+ kv.put(key, JSON.stringify(value), { expirationTtl: ttlSeconds }).catch(() => {});+ }++ return value;+}++export async function invalidate(key: string): Promise<void> {+ const kv = getKV();+ if (kv) await kv.delete(key).catch(() => {});+}++export const cacheKeys = {+ machineToken: (token: string) => `mt:${token.slice(0, 20)}`,+ member: (workspaceId: string, userId: string) => `mem:${workspaceId}:${userId}`,+};diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex 994ca8b97..25cdfe3ef 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"+import { cached, cacheKeys, bindCacheKV } from "@/lib/cache"export interface AuthContext {userId: string@@ -28,6 +29,7 @@ export function withAuth(handler: AuthenticatedHandler) {const { env } = await getCloudflareContext({ async: true })const cloudflareEnv = env as Env+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)const authHeader = req.headers.get("Authorization")if (authHeader?.startsWith("Bearer ")) {@@ -35,7 +37,11 @@ export function withAuth(handler: AuthenticatedHandler) {if (raw.startsWith("al_")) {try {const db = getDb(cloudflareEnv.DB)- const mt = await queries.machineToken.getMachineTokenByToken(db, raw)+ const mt = await cached(+ cacheKeys.machineToken(raw),+ 900,+ () => queries.machineToken.getMachineTokenByToken(db, raw),+ )if (!mt) {return NextResponse.json({ error: "invalid token" }, { status: 401 })}diff --git a/src/web/src/lib/middleware/workspace.ts b/src/web/src/lib/middleware/workspace.tsindex 4fd4e887c..5abf03c58 100644--- a/src/web/src/lib/middleware/workspace.ts+++ b/src/web/src/lib/middleware/workspace.ts@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"+import { cached, cacheKeys } from "@/lib/cache"import type { AuthContext } from "./auth"export interface WorkspaceContext extends AuthContext {@@ -35,10 +36,10 @@ export async function withWorkspaceMember(const { env } = await getCloudflareContext({ async: true })const db = getDb((env as Env).DB)- const membership = await queries.member.getMemberByUserAndWorkspace(- db,- auth.userId,- workspaceId+ const membership = await cached(+ cacheKeys.member(workspaceId, auth.userId),+ 1800,+ () => queries.member.getMemberByUserAndWorkspace(db, auth.userId, workspaceId),)if (!membership && auth.workspaceId === workspaceId) {return { workspaceId, memberRole: "member" }diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex 4dbe9c9cd..b275e2e22 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -65,6 +65,10 @@ service = "alook-email-worker"binding = "RATE_LIMIT_KV"id = "a3d035bea7bc49d99377b82ec21ce4c1"+[[kv_namespaces]]+binding = "CACHE_KV"+id = "placeholder-create-via-wrangler-kv-namespace-create"+[vars]RUNTIME_MODEL_OPTIONS = '{"claude":["claude-opus-4-6","claude-sonnet-4-6","claude-haiku-4-5"],"codex":["gpt-5.4","gpt-5.3-codex"]}'MIN_CLI_VERSION = "0.0.46"