import { serve } from "https://deno.land/std@0.178.0/http/server.ts"; // -------------------- 改造部分:使用内存 Map 和自定义的异步锁 -------------------- // 使用一个 Map 在内存中存储每个 provider 的轮询索引 const rotationIndexes = new Map(); // 使用一个 Set 来实现一个简单的 provider 锁,防止并发更新时的竞态条件 const providerLocks = new Set(); /** * 延时函数 * @param ms 毫秒数 */ const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); /** * 改造后的函数 v2: * 使用自定义的异步锁来原子性地获取并递增轮询索引。 * 这可以防止并发请求时多个请求拿到同一个索引。 * @param provider - 服务商名称 * @param length - 密钥池的长度 * @returns 将用于当前请求的索引 */ async function getAndIncrementRotationIndex( provider: string, length: number, ): Promise { // 1. 等待获取锁 // 当 provider 在锁集合中时,持续等待 while (providerLocks.has(provider)) { await delay(10); // 等待10毫秒后重试,避免CPU空转 } try { // 2. 成功获取锁 providerLocks.add(provider); // --- 临界区开始 (Critical Section) --- // 这部分代码在同一时间只允许一个请求为同一个 provider 执行 const currentIndex = rotationIndexes.get(provider) ?? 0; const nextIndex = (currentIndex + 1) % length; rotationIndexes.set(provider, nextIndex); // --- 临界区结束 --- return currentIndex; } finally { // 3. 释放锁 // 无论 try 块中是否发生错误,都必须释放锁,否则会造成死锁 providerLocks.delete(provider); } } // -------------------- 改造部分结束 -------------------- // -------------------- 1. 自定义配置-------------------- // 路径映射 // 键名中斜杠后的部分(如`gemini`)将会作为后续变量 provider 的值,用以标记服务商 const apiMapping: Record = { "/openai": "https://api.openai.com", "/claude": "https://api.anthropic.com", "/gemini": "https://generativelanguage.googleapis.com", "/xai": "https://api.x.ai", "/groq": "https://api.groq.com/openai", "/openrouter": "https://openrouter.ai/api", "/meta": "https://www.meta.ai/api", "/cohere": "https://api.cohere.ai", "/huggingface": "https://api-inference.huggingface.co", "/together": "https://api.together.xyz", "/novita": "https://api.novita.ai", "/portkey": "https://api.portkey.ai", "/fireworks": "https://api.fireworks.ai", "/cerebras": "https://api.cerebras.ai", "/discord": "https://discord.com/api", "/telegram": "https://api.telegram.org", }; // 密钥轮询配置 const rotationConfig: Record = { gemini: true, groq: true, openrouter: true }; // 鉴权请求头格式声明 const authHeaderMapping: Record [string, string]> = { gemini: (apiKey: string) => ["x-goog-api-key", apiKey], claude: (apiKey: string) => ["x-api-key", apiKey], }; // -------------------- 2. 敏感请求头过滤 -------------------- const deniedHeaders = ["host", "referer", "cf-", "forward", "cdn"]; function isAllowedHeader(key: string): boolean { const lowerKey = key.toLowerCase(); for (const deniedHeader of deniedHeaders) { if (lowerKey.includes(deniedHeader)) { return false; } } return true; } // -------------------- 3. parseTarget:尝试匹配 provider 并且提取路径 -------------------- function parseTarget(urlPath: string): { provider: string; targetUrl: string } { const splitIndex = urlPath.indexOf("/", 1); if (splitIndex === -1) { return { provider: "", targetUrl: "" }; } const prefix = urlPath.substring(0, splitIndex); const provider = prefix.replace("/", ""); const mappedBase = apiMapping[prefix]; if (!mappedBase) { return { provider: "", targetUrl: "" }; } const restPath = urlPath.substring(prefix.length); return { provider, targetUrl: mappedBase + restPath, }; } // -------------------- 4. 处理密钥池与轮询索引 -------------------- async function getKeyPool(provider: string): Promise { const envKeyName = `${provider.toUpperCase()}_KEYS`; const keyPoolStr = Deno.env.get(envKeyName); if (!keyPoolStr) return []; return keyPoolStr.split(",").map((k) => k.trim()).filter((k) => k.length > 0); } // -------------------- 5. 传入请求头鉴权 -------------------- function extractInboundAuthKey( request: Request, provider: string, ): string | undefined { const buildAuthHeader = authHeaderMapping[provider]; if (buildAuthHeader) { const [customHeaderKey] = buildAuthHeader(""); return request.headers.get(customHeaderKey) || undefined; } else { const incomingAuth = request.headers.get("Authorization"); if (!incomingAuth || !incomingAuth.startsWith("Bearer ")) { return undefined; } return incomingAuth.substring("Bearer ".length).trim(); } } function checkInboundAuth(request: Request, provider: string): boolean { const envAuthKey = Deno.env.get("AUTH_KEY"); if (!envAuthKey) { return false; } const inboundKey = extractInboundAuthKey(request, provider); if (inboundKey === envAuthKey) { return true; } if (provider === "gemini") { const url = new URL(request.url); const keyParam = url.searchParams.get("key"); return keyParam === envAuthKey; } return false; } // -------------------- 6. 启动服务,处理请求 -------------------- serve(async (request: Request) => { const url = new URL(request.url); const pathname = url.pathname + url.search; if (pathname === "/" || pathname === "/index.html") { return new Response("Service is running!", { status: 200, headers: { "Content-Type": "text/html" }, }); } if (pathname === "/robots.txt") { return new Response("User-agent: *\nDisallow: /", { status: 200, headers: { "Content-Type": "text/plain" }, }); } let { provider, targetUrl } = parseTarget(pathname); if (!targetUrl) { return new Response("无效路径: " + pathname, { status: 404 }); } const rotationEnabled = rotationConfig[provider] ?? false; const headers = new Headers(); for (const [key, value] of request.headers.entries()) { if (isAllowedHeader(key)) { headers.set(key, value); } } if (!rotationEnabled) { try { return await fetch(targetUrl, { method: request.method, headers, body: request.body, }); } catch (error) { const message = `转发模式: ${targetUrl}\n\n` + `错误消息: ${error.message}\n\n` + `堆栈跟踪:\n${error.stack ?? 'No stack trace'}`; return new Response(message, { status: 500 }); } } if (!checkInboundAuth(request, provider)) { return new Response("轮询模式:脚本鉴权未通过", { status: 401 }); } const keyPool = await getKeyPool(provider); if (keyPool.length === 0) { return new Response(`轮询模式:${provider} 缺少密钥池`, { status: 500, }); } headers.delete("Authorization"); headers.delete("x-api-key"); headers.delete("x-goog-api-key"); if (provider === "gemini") { const targetUrlObj = new URL(targetUrl); targetUrlObj.searchParams.delete("key"); targetUrl = targetUrlObj.toString(); } let currentIndex: number; try { currentIndex = await getAndIncrementRotationIndex(provider, keyPool.length); } catch (err) { return new Response(`轮询模式:密钥轮询索引更新失败: ${err.message}`, { status: 500, }); } const apiKey = keyPool[currentIndex]; const buildAuthHeader = authHeaderMapping[provider]; let authHeaderKey = "Authorization"; let authHeaderValue = `Bearer ${apiKey}`; if (buildAuthHeader) { [authHeaderKey, authHeaderValue] = buildAuthHeader(apiKey); } headers.set(authHeaderKey, authHeaderValue); try { return await fetch(targetUrl, { method: request.method, headers, body: request.body, }); } catch (error) { const message = `轮询模式 - 请求失败: ${targetUrl}\n\n` + `错误消息: ${error.message}\n\n` + `堆栈跟踪:\n${error.stack ?? 'No stack trace'}`; return new Response(message, { status: 500 }); } },{port:7860});