@@ -12,14 +12,14 @@ import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js" |
12 | 12 | import { ModelTable } from "@opencode-ai/console-core/schema/model.sql.js" |
13 | 13 | import { ProviderTable } from "@opencode-ai/console-core/schema/provider.sql.js" |
14 | 14 | import { logger } from "./logger" |
15 | | -import { AuthError, CreditsError, MonthlyLimitError, UserLimitError, ModelError } from "./error" |
| 15 | +import { AuthError, CreditsError, MonthlyLimitError, UserLimitError, ModelError, RateLimitError } from "./error" |
16 | 16 | import { createBodyConverter, createStreamPartConverter, createResponseConverter } from "./provider/provider" |
17 | 17 | import { anthropicHelper } from "./provider/anthropic" |
18 | 18 | import { openaiHelper } from "./provider/openai" |
19 | 19 | import { oaCompatHelper } from "./provider/openai-compatible" |
| 20 | +import { createRateLimiter } from "./rateLimiter" |
20 | 21 |
|
21 | 22 | type ZenData = Awaited<ReturnType<typeof ZenData.list>> |
22 | | -type Model = ZenData["models"][string] |
23 | 23 |
|
24 | 24 | export async function handler( |
25 | 25 | input: APIEvent, |
@@ -28,23 +28,30 @@ export async function handler( |
28 | 28 | parseApiKey: (headers: Headers) => string | undefined |
29 | 29 | }, |
30 | 30 | ) { |
| 31 | + type AuthInfo = Awaited<ReturnType<typeof authenticate>> |
| 32 | + type ModelInfo = Awaited<ReturnType<typeof validateModel>> |
| 33 | + type ProviderInfo = Awaited<ReturnType<typeof selectProvider>> |
| 34 | + |
31 | 35 | const FREE_WORKSPACES = [ |
32 | 36 | "wrk_01K46JDFR0E75SG2Q8K172KF3Y", // frank |
33 | 37 | "wrk_01K6W1A3VE0KMNVSCQT43BG2SX", // opencode bench |
34 | 38 | ] |
35 | 39 |
|
36 | 40 | try { |
37 | 41 | const body = await input.request.json() |
| 42 | + const ip = input.request.headers.get("x-real-ip") ?? "" |
38 | 43 | logger.metric({ |
39 | 44 | is_tream: !!body.stream, |
40 | 45 | session: input.request.headers.get("x-opencode-session"), |
41 | 46 | request: input.request.headers.get("x-opencode-request"), |
42 | 47 | }) |
43 | 48 | const zenData = ZenData.list() |
44 | 49 | const modelInfo = validateModel(zenData, body.model) |
45 | | - const providerInfo = selectProvider(zenData, modelInfo, input.request.headers.get("x-real-ip") ?? "") |
| 50 | + const providerInfo = selectProvider(zenData, modelInfo, ip) |
46 | 51 | const authInfo = await authenticate(modelInfo, providerInfo) |
47 | | - validateBilling(modelInfo, authInfo) |
| 52 | + const rateLimiter = createRateLimiter(modelInfo.id, modelInfo.rateLimit, ip) |
| 53 | + await rateLimiter?.check() |
| 54 | + validateBilling(authInfo, modelInfo) |
48 | 55 | validateModelSettings(authInfo) |
49 | 56 | updateProviderKey(authInfo, providerInfo) |
50 | 57 | logger.metric({ provider: providerInfo.id }) |
@@ -59,7 +66,7 @@ export async function handler( |
59 | 66 | }), |
60 | 67 | ) |
61 | 68 | logger.debug("REQUEST URL: " + reqUrl) |
62 | | - logger.debug("REQUEST: " + reqBody) |
| 69 | + logger.debug("REQUEST: " + reqBody.substring(0, 300) + "...") |
63 | 70 | const res = await fetch(reqUrl, { |
64 | 71 | method: "POST", |
65 | 72 | headers: (() => { |
@@ -84,9 +91,6 @@ export async function handler( |
84 | 91 | } |
85 | 92 | } |
86 | 93 | logger.debug("STATUS: " + res.status + " " + res.statusText) |
87 | | - if (res.status === 400 || res.status === 503) { |
88 | | - logger.debug("RESPONSE: " + (await res.text())) |
89 | | - } |
90 | 94 |
|
91 | 95 | // Handle non-streaming response |
92 | 96 | if (!body.stream) { |
@@ -95,6 +99,7 @@ export async function handler( |
95 | 99 | const body = JSON.stringify(responseConverter(json)) |
96 | 100 | logger.metric({ response_length: body.length }) |
97 | 101 | logger.debug("RESPONSE: " + body) |
| 102 | + await rateLimiter?.track() |
98 | 103 | await trackUsage(authInfo, modelInfo, providerInfo, json.usage) |
99 | 104 | await reload(authInfo) |
100 | 105 | return new Response(body, { |
@@ -123,6 +128,7 @@ export async function handler( |
123 | 128 | response_length: responseLength, |
124 | 129 | "timestamp.last_byte": Date.now(), |
125 | 130 | }) |
| 131 | + await rateLimiter?.track() |
126 | 132 | const usage = usageParser.retrieve() |
127 | 133 | if (usage) { |
128 | 134 | await trackUsage(authInfo, modelInfo, providerInfo, usage) |
@@ -197,6 +203,15 @@ export async function handler( |
197 | 203 | { status: 401 }, |
198 | 204 | ) |
199 | 205 |
|
| 206 | + if (error instanceof RateLimitError) |
| 207 | + return new Response( |
| 208 | + JSON.stringify({ |
| 209 | + type: "error", |
| 210 | + error: { type: error.constructor.name, message: error.message }, |
| 211 | + }), |
| 212 | + { status: 429 }, |
| 213 | + ) |
| 214 | + |
200 | 215 | return new Response( |
201 | 216 | JSON.stringify({ |
202 | 217 | type: "error", |
@@ -221,8 +236,8 @@ export async function handler( |
221 | 236 | return { id: modelId, ...modelData } |
222 | 237 | } |
223 | 238 |
|
224 | | - function selectProvider(zenData: ZenData, model: Awaited<ReturnType<typeof validateModel>>, ip: string) { |
225 | | - const providers = model.providers |
| 239 | + function selectProvider(zenData: ZenData, modelInfo: ModelInfo, ip: string) { |
| 240 | + const providers = modelInfo.providers |
226 | 241 | .filter((provider) => !provider.disabled) |
227 | 242 | .flatMap((provider) => Array<typeof provider>(provider.weight ?? 1).fill(provider)) |
228 | 243 |
|
@@ -235,22 +250,22 @@ export async function handler( |
235 | 250 | throw new ModelError(`Provider ${provider.id} not supported`) |
236 | 251 | } |
237 | 252 |
|
238 | | - const format = zenData.providers[provider.id].format |
239 | | - |
240 | 253 | return { |
241 | 254 | ...provider, |
242 | 255 | ...zenData.providers[provider.id], |
243 | | - ...(format === "anthropic" ? anthropicHelper : format === "openai" ? openaiHelper : oaCompatHelper), |
| 256 | + ...(() => { |
| 257 | + const format = zenData.providers[provider.id].format |
| 258 | + if (format === "anthropic") return anthropicHelper |
| 259 | + if (format === "openai") return openaiHelper |
| 260 | + return oaCompatHelper |
| 261 | + })(), |
244 | 262 | } |
245 | 263 | } |
246 | 264 |
|
247 | | - async function authenticate( |
248 | | - model: Awaited<ReturnType<typeof validateModel>>, |
249 | | - providerInfo: Awaited<ReturnType<typeof selectProvider>>, |
250 | | - ) { |
| 265 | + async function authenticate(modelInfo: ModelInfo, providerInfo: ProviderInfo) { |
251 | 266 | const apiKey = opts.parseApiKey(input.request.headers) |
252 | 267 | if (!apiKey) { |
253 | | - if (model.allowAnonymous) return |
| 268 | + if (modelInfo.allowAnonymous) return |
254 | 269 | throw new AuthError("Missing API key.") |
255 | 270 | } |
256 | 271 |
|
@@ -282,7 +297,7 @@ export async function handler( |
282 | 297 | .innerJoin(WorkspaceTable, eq(WorkspaceTable.id, KeyTable.workspaceID)) |
283 | 298 | .innerJoin(BillingTable, eq(BillingTable.workspaceID, KeyTable.workspaceID)) |
284 | 299 | .innerJoin(UserTable, and(eq(UserTable.workspaceID, KeyTable.workspaceID), eq(UserTable.id, KeyTable.userID))) |
285 | | - .leftJoin(ModelTable, and(eq(ModelTable.workspaceID, KeyTable.workspaceID), eq(ModelTable.model, model.id))) |
| 300 | + .leftJoin(ModelTable, and(eq(ModelTable.workspaceID, KeyTable.workspaceID), eq(ModelTable.model, modelInfo.id))) |
286 | 301 | .leftJoin( |
287 | 302 | ProviderTable, |
288 | 303 | and(eq(ProviderTable.workspaceID, KeyTable.workspaceID), eq(ProviderTable.provider, providerInfo.id)), |
@@ -308,11 +323,11 @@ export async function handler( |
308 | 323 | } |
309 | 324 | } |
310 | 325 |
|
311 | | - function validateBilling(model: Model, authInfo: Awaited<ReturnType<typeof authenticate>>) { |
| 326 | + function validateBilling(authInfo: AuthInfo, modelInfo: ModelInfo) { |
312 | 327 | if (!authInfo) return |
313 | 328 | if (authInfo.provider?.credentials) return |
314 | 329 | if (authInfo.isFree) return |
315 | | - if (model.allowAnonymous) return |
| 330 | + if (modelInfo.allowAnonymous) return |
316 | 331 |
|
317 | 332 | const billing = authInfo.billing |
318 | 333 | if (!billing.paymentMethodID) |
@@ -356,26 +371,18 @@ export async function handler( |
356 | 371 | } |
357 | 372 | } |
358 | 373 |
|
359 | | - function validateModelSettings(authInfo: Awaited<ReturnType<typeof authenticate>>) { |
| 374 | + function validateModelSettings(authInfo: AuthInfo) { |
360 | 375 | if (!authInfo) return |
361 | 376 | if (authInfo.isDisabled) throw new ModelError("Model is disabled") |
362 | 377 | } |
363 | 378 |
|
364 | | - function updateProviderKey( |
365 | | - authInfo: Awaited<ReturnType<typeof authenticate>>, |
366 | | - providerInfo: Awaited<ReturnType<typeof selectProvider>>, |
367 | | - ) { |
| 379 | + function updateProviderKey(authInfo: AuthInfo, providerInfo: ProviderInfo) { |
368 | 380 | if (!authInfo) return |
369 | 381 | if (!authInfo.provider?.credentials) return |
370 | 382 | providerInfo.apiKey = authInfo.provider.credentials |
371 | 383 | } |
372 | 384 |
|
373 | | - async function trackUsage( |
374 | | - authInfo: Awaited<ReturnType<typeof authenticate>>, |
375 | | - modelInfo: ReturnType<typeof validateModel>, |
376 | | - providerInfo: Awaited<ReturnType<typeof selectProvider>>, |
377 | | - usage: any, |
378 | | - ) { |
| 385 | + async function trackUsage(authInfo: AuthInfo, modelInfo: ModelInfo, providerInfo: ProviderInfo, usage: any) { |
379 | 386 | const { inputTokens, outputTokens, reasoningTokens, cacheReadTokens, cacheWrite5mTokens, cacheWrite1hTokens } = |
380 | 387 | providerInfo.normalizeUsage(usage) |
381 | 388 |
|
@@ -483,7 +490,7 @@ export async function handler( |
483 | 490 | ) |
484 | 491 | } |
485 | 492 |
|
486 | | - async function reload(authInfo: Awaited<ReturnType<typeof authenticate>>) { |
| 493 | + async function reload(authInfo: AuthInfo) { |
487 | 494 | if (!authInfo) return |
488 | 495 | if (authInfo.isFree) return |
489 | 496 | if (authInfo.provider?.credentials) return |
|