Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions components/Admin/SyncStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,15 @@ export default function SyncStatus (): JSX.Element {
const load = async (): Promise<void> => {
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)
Expand Down Expand Up @@ -173,7 +180,10 @@ export default function SyncStatus (): JSX.Element {
))}
</div>
<p className={style.sync_meta}>
Transactions without linked prices: <strong>{data.unpricedTxs.toLocaleString()}</strong> (counted {formatDuration(now - data.unpricedTxsCheckedAt)} ago)
Transactions without linked prices:{' '}
{data.unpricedTxs === null || data.unpricedTxsCheckedAt === null
? <em>counting…</em>
: <><strong>{data.unpricedTxs.toLocaleString()}</strong> (counted {formatDuration(now - data.unpricedTxsCheckedAt)} ago)</>}
</p>
</div>

Expand Down
89 changes: 58 additions & 31 deletions services/syncStatusService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,55 +32,81 @@ export interface SyncStatus {
job: SyncJobProgress | null
networks: Record<string, NetworkAddressStats>
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<void> | 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<Array<{ count: bigint | number }>>`
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<number, number> =>
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<SyncStatus> {
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<AddressStatsRow[]>`
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<string, NetworkAddressStats> = {}
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)
}
}

Expand All @@ -93,7 +120,7 @@ export async function fetchSyncStatus (): Promise<SyncStatus> {
since: a.updatedAt.getTime(),
stuck: a.updatedAt < stuckBefore
})),
unpricedTxs: unpriced.count,
unpricedTxsCheckedAt: unpriced.checkedAt
unpricedTxs: unpricedTxsCache?.count ?? null,
unpricedTxsCheckedAt: unpricedTxsCache?.checkedAt ?? null
}
}
Loading