stat.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { WorkerEntrypoint } from "cloudflare:workers"
  2. import { and, Database, inArray } from "@opencode-ai/console-core/drizzle/index.js"
  3. import { ModelTpsRateLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js"
  4. type Result = Record<string, { qualify: number; unqualify: number }>
  5. export default class Stat extends WorkerEntrypoint {
  6. async fetch() {
  7. return new Response("Not Found", { status: 404 })
  8. }
  9. async getStats(ids: string[]): Promise<Result> {
  10. if (ids.length === 0) return {}
  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 result
  32. }
  33. }