GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(stats): reduce database query load · krumpstead/opencode@08c483d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • console/app/src/lib
      • stats-proxy.ts
    • stats
      • app/src
        • component
          • model-compare-detail.tsx
        • routes
          • [lab]
            • [model].tsx
          • index.tsx
      • core
        • migrations/20260903161929_parched_patriot
          • migration.sql
          • snapshot.json
        • src
          • database
            • schema.ts
          • domain
            • home.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/console/app/src/lib/stats-proxy.ts‎

Copy file name to clipboardExpand all lines: packages/console/app/src/lib/stats-proxy.ts
+43-2Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
import type { APIEvent } from "@solidjs/start/server"
2-
import { Resource } from "@opencode-ai/console-resource"
2+
import { Resource, waitUntil } from "@opencode-ai/console-resource"
33
import { LOCALE_HEADER, cookie, localeFromRequest, route, tag } from "~/lib/language"
44

55
const dataPath = "/data"
6+
const statsCacheParam = "__opencode_stats_locale"
67

78
export async function statsProxy(evt: APIEvent) {
89
const req = evt.request.clone()
910
const locale = localeFromRequest(req)
1011
const redirect = redirectToLocalizedData(req, new URL(req.url), locale)
1112
if (redirect) return redirect
1213

14+
const cache = defaultCache(caches)
15+
const cacheKey = statsCacheKey(req, locale)
16+
if (cacheKey) {
17+
const cached = await cache.match(cacheKey)
18+
if (cached) return withStatsCacheStatus(cached, "HIT")
19+
}
20+
1321
const targetUrl = new URL(req.url)
1422
targetUrl.protocol = "https:"
1523
targetUrl.hostname = Resource.App.stage === "production" ? "stats.opencode.ai" : "stats.dev.opencode.ai"
@@ -40,13 +48,18 @@ export async function statsProxy(evt: APIEvent) {
4048
headers.delete("content-encoding")
4149
headers.delete("content-length")
4250
headers.delete("etag")
51+
headers.delete("set-cookie")
4352
appendVary(headers, "Accept-Language", "Cookie", LOCALE_HEADER)
4453

45-
return new Response(rewriteStatsHtml(await response.text()), {
54+
const result = new Response(rewriteStatsHtml(await response.text()), {
4655
status: response.status,
4756
statusText: response.statusText,
4857
headers,
4958
})
59+
if (!cacheKey || !response.ok) return result
60+
61+
void waitUntil(cache.put(cacheKey, result.clone()))
62+
return withStatsCacheStatus(result, "MISS")
5063
}
5164

5265
export function statsRedirect(evt: APIEvent) {
@@ -64,6 +77,34 @@ function rewriteStatsHtml(html: string) {
6477
return html.replaceAll('"/_build/', `"${dataPath}/_build/`).replaceAll("'/_build/", `'${dataPath}/_build/`)
6578
}
6679

80+
function statsCacheKey(request: Request, locale: ReturnType<typeof localeFromRequest>): Request | undefined {
81+
if (request.method !== "GET") return undefined
82+
if (!acceptsHtml(request)) return undefined
83+
if (isDataBypassPath(new URL(request.url).pathname)) return undefined
84+
85+
const url = new URL(request.url)
86+
const additionalModels = url.searchParams.get("add")
87+
url.search = ""
88+
if (additionalModels) url.searchParams.set("add", additionalModels)
89+
url.searchParams.set(statsCacheParam, locale)
90+
return new Request(url)
91+
}
92+
93+
function defaultCache(storage: CacheStorage) {
94+
if (!isCloudflareCacheStorage(storage)) throw new Error("Cloudflare default cache is unavailable")
95+
return storage.default
96+
}
97+
98+
function isCloudflareCacheStorage(storage: CacheStorage): storage is CacheStorage & { default: Cache } {
99+
return "default" in storage
100+
}
101+
102+
function withStatsCacheStatus(response: Response, status: "HIT" | "MISS") {
103+
const headers = new Headers(response.headers)
104+
headers.set("x-opencode-stats-cache", status)
105+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
106+
}
107+
67108
function redirectToLocalizedData(request: Request, url: URL, locale: ReturnType<typeof localeFromRequest>) {
68109
if (locale === "en") return null
69110
if (request.headers.get(LOCALE_HEADER)) return null
Collapse file

‎packages/stats/app/src/component/model-compare-detail.tsx‎

Copy file name to clipboardExpand all lines: packages/stats/app/src/component/model-compare-detail.tsx
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
type StatsModelComparisonInput,
88
type StatsModelComparisonEntry,
99
} from "@opencode-ai/stats-core/domain/home"
10-
import { runtime } from "@opencode-ai/stats-core/runtime"
1110
import { createAsync, query, useParams, useSearchParams } from "@solidjs/router"
1211
import { createEffect, createMemo, createSignal, For, onMount, Show } from "solid-js"
1312
import { getRequestEvent } from "solid-js/web"
@@ -46,6 +45,7 @@ import {
4645
type ResolvedComparisonFamily,
4746
} from "../lib/comparison-pages"
4847
import { baseUrl } from "../lib/language"
48+
import { runStatsEffect } from "../stats-runtime"
4949

5050
const compareHeaderLinks: readonly HeaderLink[] = [
5151
{ href: `${import.meta.env.BASE_URL}#top-models`, label: "Top Models" },
@@ -110,7 +110,7 @@ export type ModelCompareDetailPageProps = {
110110

111111
const getComparisonData = query(async (models: StatsModelComparisonInput[]) => {
112112
"use server"
113-
return runtime.runPromise(getStatsModelsComparisonData(models))
113+
return runStatsEffect(getStatsModelsComparisonData(models))
114114
}, "getStatsModelComparisonDetailData")
115115

116116
export default function ModelCompareDetailPage(props: ModelCompareDetailPageProps = {}) {
Collapse file

‎packages/stats/app/src/routes/[lab]/[model].tsx‎

Copy file name to clipboardExpand all lines: packages/stats/app/src/routes/[lab]/[model].tsx
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ type ModelPageCatalog = {
5252
labs: { id: string; name: string }[]
5353
labModels: ModelCatalogOption[]
5454
}
55-
type StatsModelPageData = Omit<StatsModelData, "country"> & { country: CountryEntry[] }
55+
type StatsModelPageData = StatsModelData
5656
type ModelPageData = { catalog: ModelPageCatalog; stats: StatsModelPageData | null }
5757

5858
const countryNumericIds = new Map(
@@ -75,7 +75,7 @@ const getModelPageData = query(async (labParam: string, modelParam: string) => {
7575
.find((item) => item.id === (entry?.lab ?? providerSlug(labParam)))
7676
?.models.map((item) => ({ id: item.id, lab: item.lab, slug: item.slug, name: item.name })) ?? [],
7777
},
78-
stats: stats ? { ...stats, country: stats.country["2M"] } : null,
78+
stats,
7979
} satisfies ModelPageData
8080
}, "getStatsModelPageData")
8181

Collapse file

‎packages/stats/app/src/routes/index.tsx‎

Copy file name to clipboardExpand all lines: packages/stats/app/src/routes/index.tsx
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ const getData = query(async () => {
9191
cacheRatio: stats.cacheRatio.Go,
9292
sessionCost: stats.sessionCost.Go,
9393
retention: stats.retention,
94-
country: stats.country["2M"],
94+
country: stats.country,
9595
} satisfies StatsHomePageData
9696
}, "getStatsHomeData")
9797

Collapse file

‎packages/stats/core/migrations/20260903161929_parched_patriot/migration.sql‎

Copy file name to clipboard
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
CREATE INDEX `idx_country_model_range` ON `geo_stat` (`model`,`provider`,`grain`,`dataset`,`client`,`source`,`tier`,`period_key`);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.