stat.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { and, Database, inArray } from "@opencode-ai/console-core/drizzle/index.js"
  2. import { ModelTpsRateLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js"
  3. type Entry = { provider: string; model: string; tps: number }
  4. type Result = Record<string, { qualify: number; unqualify: number }>
  5. export default {
  6. async fetch(request: Request) {
  7. if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 })
  8. const entries = (await request.json()) as Entry[]
  9. if (!Array.isArray(entries) || entries.length === 0) return Response.json({} satisfies Result)
  10. const ids = entries.map((e) => `${e.provider}/${e.model}/${e.tps}`)
  11. const toInterval = (date: Date) =>
  12. parseInt(
  13. date
  14. .toISOString()
  15. .replace(/[^0-9]/g, "")
  16. .substring(0, 12),
  17. )
  18. const now = Date.now()
  19. const intervals = Array.from({ length: 5 }, (_, i) => toInterval(new Date(now - i * 60 * 1000)))
  20. const rows = await Database.use((tx) =>
  21. tx
  22. .select()
  23. .from(ModelTpsRateLimitTable)
  24. .where(and(inArray(ModelTpsRateLimitTable.id, ids), inArray(ModelTpsRateLimitTable.interval, intervals))),
  25. )
  26. const result: Result = Object.fromEntries(ids.map((id) => [id, { qualify: 0, unqualify: 0 }]))
  27. for (const row of rows) {
  28. result[row.id].qualify += row.qualify
  29. result[row.id].unqualify += row.unqualify
  30. }
  31. return Response.json(result)
  32. },
  33. }