From ee320d2a4fccfe7940ea20313ffbdfce90d1ab44 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:09:32 +0000 Subject: [PATCH] fix: stop /admin sync status from timing out MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unpriced-txs count (prices: { none: {} } -> NOT IN subquery over the whole Transaction table) ran inside the request and outlasted the reverse proxy's timeout, so the client got an HTML error page and failed parsing it as JSON. - Count unpriced txs in the background with a NOT EXISTS anti-join, share one in-flight query, cache it for 5 min, and return the last finished count (null while the first one runs). - Replace the four Address groupBy scans with a single aggregate query. - Client: report non-JSON responses as an HTTP status instead of a JSON parse error, and show "counting…" until the first count is available. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019G564hvGkZJY3UCe17WV6u --- components/Admin/SyncStatus.tsx | 14 +++++- services/syncStatusService.ts | 89 +++++++++++++++++++++------------ 2 files changed, 70 insertions(+), 33 deletions(-) diff --git a/components/Admin/SyncStatus.tsx b/components/Admin/SyncStatus.tsx index d5f92d96..38ec7eb0 100644 --- a/components/Admin/SyncStatus.tsx +++ b/components/Admin/SyncStatus.tsx @@ -69,8 +69,15 @@ export default function SyncStatus (): JSX.Element { const load = async (): Promise => { try { const res = await fetch('/api/admin/syncStatus') - const json = await res.json() + // A proxy timeout or crash returns an HTML error page, not JSON. + const text = await res.text() if (cancelled) return + let json: any + try { + json = JSON.parse(text) + } catch { + throw new Error(`HTTP ${res.status} ${res.statusText} (non-JSON response)`) + } if (!res.ok) throw new Error(json.message ?? `HTTP ${res.status}`) setData(json) setError(undefined) @@ -173,7 +180,10 @@ export default function SyncStatus (): JSX.Element { ))}

- Transactions without linked prices: {data.unpricedTxs.toLocaleString()} (counted {formatDuration(now - data.unpricedTxsCheckedAt)} ago) + Transactions without linked prices:{' '} + {data.unpricedTxs === null || data.unpricedTxsCheckedAt === null + ? counting… + : <>{data.unpricedTxs.toLocaleString()} (counted {formatDuration(now - data.unpricedTxsCheckedAt)} ago)}

diff --git a/services/syncStatusService.ts b/services/syncStatusService.ts index 0ba23bf3..af1f7010 100644 --- a/services/syncStatusService.ts +++ b/services/syncStatusService.ts @@ -6,9 +6,10 @@ import { getSyncJobProgress, SyncJobProgress } from 'redis/syncProgress' // over from a sync that crashed or hung. export const STUCK_SYNCING_THRESHOLD_MS = 15 * 60 * 1000 const SYNCING_ADDRESSES_LIST_LIMIT = 50 -// Counting unpriced txs scans the transactions table, so the admin page's -// polling reuses a recent count instead of running it every few seconds. -const UNPRICED_TXS_CACHE_MS = 60 * 1000 +// Counting unpriced txs scans the whole transactions table, which can take +// longer than the reverse proxy's request timeout. It is refreshed in the +// background and requests only ever return the last finished count. +const UNPRICED_TXS_CACHE_MS = 5 * 60 * 1000 export interface NetworkAddressStats { total: number @@ -31,55 +32,81 @@ export interface SyncStatus { job: SyncJobProgress | null networks: Record syncingAddresses: SyncingAddress[] - unpricedTxs: number - unpricedTxsCheckedAt: number + // null until the first background count finishes. + unpricedTxs: number | null + unpricedTxsCheckedAt: number | null } let unpricedTxsCache: { count: number, checkedAt: number } | undefined +let unpricedTxsInFlight: Promise | undefined -async function countUnpricedTxs (): Promise<{ count: number, checkedAt: number }> { - const now = Date.now() - if (unpricedTxsCache === undefined || now - unpricedTxsCache.checkedAt > UNPRICED_TXS_CACHE_MS) { - const count = await prisma.transaction.count({ where: { prices: { none: {} } } }) - unpricedTxsCache = { count, checkedAt: now } - } - return unpricedTxsCache +// Starts a background recount when the cached one is missing or old, without +// waiting for it; concurrent callers share the one in-flight query. +function refreshUnpricedTxsCount (): void { + const fresh = unpricedTxsCache !== undefined && Date.now() - unpricedTxsCache.checkedAt <= UNPRICED_TXS_CACHE_MS + if (fresh || unpricedTxsInFlight !== undefined) return + const startedAt = Date.now() + unpricedTxsInFlight = (async () => { + try { + // NOT EXISTS lets MySQL anti-join on the transactionId FK index; Prisma's + // `prices: { none: {} }` compiles to a NOT IN subquery that is far slower. + const rows = await prisma.$queryRaw>` + SELECT COUNT(*) AS count FROM Transaction t + WHERE NOT EXISTS (SELECT 1 FROM PricesOnTransactions p WHERE p.transactionId = t.id) + ` + unpricedTxsCache = { count: Number(rows[0]?.count ?? 0), checkedAt: startedAt } + } catch (err: any) { + console.error(`[syncStatus] failed to count unpriced txs: ${err?.message as string}`) + } finally { + unpricedTxsInFlight = undefined + } + })() } -const countsByNetwork = (rows: Array<{ networkId: number, _count: { _all: number } }>): Record => - Object.fromEntries(rows.map(r => [r.networkId, r._count._all])) +interface AddressStatsRow { + networkId: number + total: bigint | number + syncing: bigint | number | null + stuck: bigint | number | null + withoutTxs: bigint | number | null +} export async function fetchSyncStatus (): Promise { const now = Date.now() const stuckBefore = new Date(now - STUCK_SYNCING_THRESHOLD_MS) - const [job, totals, syncing, stuck, withoutTxs, syncingRows, unpriced] = await Promise.all([ + refreshUnpricedTxsCount() + const [job, addressStats, syncingRows] = await Promise.all([ getSyncJobProgress(), - prisma.address.groupBy({ by: ['networkId'], _count: { _all: true } }), - prisma.address.groupBy({ by: ['networkId'], where: { syncing: true }, _count: { _all: true } }), - prisma.address.groupBy({ by: ['networkId'], where: { syncing: true, updatedAt: { lt: stuckBefore } }, _count: { _all: true } }), - prisma.address.groupBy({ by: ['networkId'], where: { lastSynced: null }, _count: { _all: true } }), + // One pass over Address instead of a separate groupBy per counter. + prisma.$queryRaw` + SELECT + networkId, + COUNT(*) AS total, + SUM(syncing = 1) AS syncing, + SUM(syncing = 1 AND updatedAt < ${stuckBefore}) AS stuck, + SUM(lastSynced IS NULL) AS withoutTxs + FROM Address + GROUP BY networkId + `, prisma.address.findMany({ where: { syncing: true }, orderBy: { updatedAt: 'asc' }, take: SYNCING_ADDRESSES_LIST_LIMIT, select: { address: true, networkId: true, updatedAt: true } - }), - countUnpricedTxs() + }) ]) - const totalsMap = countsByNetwork(totals) - const syncingMap = countsByNetwork(syncing) - const stuckMap = countsByNetwork(stuck) - const withoutTxsMap = countsByNetwork(withoutTxs) + const statsByNetwork = Object.fromEntries(addressStats.map(r => [Number(r.networkId), r])) const networks: Record = {} for (const [id, slug] of Object.entries(NETWORK_SLUGS_FROM_IDS)) { const networkId = Number(id) + const row = statsByNetwork[networkId] networks[slug] = { - total: totalsMap[networkId] ?? 0, - syncing: syncingMap[networkId] ?? 0, - stuck: stuckMap[networkId] ?? 0, - withoutTxs: withoutTxsMap[networkId] ?? 0 + total: Number(row?.total ?? 0), + syncing: Number(row?.syncing ?? 0), + stuck: Number(row?.stuck ?? 0), + withoutTxs: Number(row?.withoutTxs ?? 0) } } @@ -93,7 +120,7 @@ export async function fetchSyncStatus (): Promise { since: a.updatedAt.getTime(), stuck: a.updatedAt < stuckBefore })), - unpricedTxs: unpriced.count, - unpricedTxsCheckedAt: unpriced.checkedAt + unpricedTxs: unpricedTxsCache?.count ?? null, + unpricedTxsCheckedAt: unpricedTxsCache?.checkedAt ?? null } }