From e1f994704a163f8713ec18dd6932d122234260d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:26:37 +0000 Subject: [PATCH] Add sync status section to /admin Shows background blockchain sync progress (phase, timings, per-network address/tx progress, failed addresses) reported by the jobs process to Redis, plus DB-derived address sync state (syncing, stuck, no txs yet) covering on-demand syncs and the unpriced tx count. Polls every 5s via a new admin-only /api/admin/syncStatus endpoint. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019G564hBpc52rzA51pEcwxb --- components/Admin/SyncStatus.tsx | 212 +++++++++++++++++++++++++++ components/Admin/admin.module.css | 64 ++++++++ jobs/workers.ts | 21 ++- pages/admin/index.tsx | 3 + pages/api/admin/syncStatus.ts | 21 +++ redis/syncProgress.ts | 185 +++++++++++++++++++++++ services/chronikService.ts | 20 ++- services/syncStatusService.ts | 99 +++++++++++++ tests/unittests/syncProgress.test.ts | 81 ++++++++++ 9 files changed, 696 insertions(+), 10 deletions(-) create mode 100644 components/Admin/SyncStatus.tsx create mode 100644 pages/api/admin/syncStatus.ts create mode 100644 redis/syncProgress.ts create mode 100644 services/syncStatusService.ts create mode 100644 tests/unittests/syncProgress.test.ts diff --git a/components/Admin/SyncStatus.tsx b/components/Admin/SyncStatus.tsx new file mode 100644 index 000000000..d5f92d96d --- /dev/null +++ b/components/Admin/SyncStatus.tsx @@ -0,0 +1,212 @@ +import { useEffect, useState } from 'react' +import type { SyncStatus as SyncStatusData } from 'services/syncStatusService' +import type { NetworkSyncProgress, SyncPhase } from 'redis/syncProgress' +import style from './admin.module.css' + +const POLL_INTERVAL_MS = 5000 +// The job refreshes its progress at least every 30s while running. +const JOB_STALLED_AFTER_MS = 90 * 1000 + +const NETWORK_TITLES: Record = { + ecash: 'eCash', + bitcoincash: 'Bitcoin Cash' +} + +const PHASES: Array<{ key: SyncPhase, title: string }> = [ + { key: 'prices', title: 'Past prices' }, + { key: 'transactions', title: 'Transactions' }, + { key: 'priceLinking', title: 'Price linking' }, + { key: 'cacheInvalidation', title: 'Cache invalidation' } +] + +const formatDuration = (ms: number): string => { + const s = Math.max(0, Math.floor(ms / 1000)) + const h = Math.floor(s / 3600) + const m = Math.floor((s % 3600) / 60) + const sec = s % 60 + if (h > 0) return `${h}h ${m}m` + if (m > 0) return `${m}m ${sec}s` + return `${sec}s` +} + +const formatTime = (ts: number): string => new Date(ts).toLocaleString() + +const percent = (done: number, total: number): number => + total === 0 ? 100 : Math.min(100, Math.round((done / total) * 100)) + +function ProgressBar ({ done, total }: { done: number, total: number }): JSX.Element { + const pct = percent(done, total) + return ( +
+
+ {done.toLocaleString()} / {total.toLocaleString()} ({pct}%) +
+ ) +} + +function JobNetwork ({ slug, net, now }: { slug: string, net: NetworkSyncProgress, now: number }): JSX.Element { + const end = net.finishedAt ?? now + return ( +
+
{NETWORK_TITLES[slug] ?? slug}
+ +
+ {net.txsCommitted.toLocaleString()} txs committed · {formatDuration(end - net.startedAt)} + {net.finishedAt === undefined ? ' (running)' : ''} + {net.failedCount > 0 && · {net.failedCount} failed} +
+
+ ) +} + +export default function SyncStatus (): JSX.Element { + const [data, setData] = useState() + const [error, setError] = useState() + + useEffect(() => { + let cancelled = false + let timer: ReturnType | undefined + const load = async (): Promise => { + try { + const res = await fetch('/api/admin/syncStatus') + const json = await res.json() + if (cancelled) return + if (!res.ok) throw new Error(json.message ?? `HTTP ${res.status}`) + setData(json) + setError(undefined) + } catch (err: any) { + if (!cancelled) setError(err.message) + } finally { + if (!cancelled) timer = setTimeout(() => { void load() }, POLL_INTERVAL_MS) + } + } + void load() + return () => { + cancelled = true + if (timer !== undefined) clearTimeout(timer) + } + }, []) + + if (data === undefined) { + return <> +

Sync Status

+

{error !== undefined ? `Failed to load sync status: ${error}` : 'Loading…'}

+ + } + + const now = data.serverTime + const job = data.job + const stalled = job?.status === 'running' && now - job.updatedAt > JOB_STALLED_AFTER_MS + const failedAddresses = job === null + ? [] + : Object.entries(job.networks).flatMap(([slug, n]) => n.failedAddresses.map(f => ({ ...f, slug }))) + + let jobStatusLabel = 'No run recorded' + let jobStatusClass = '' + if (job !== null) { + if (stalled) { + jobStatusLabel = `Stalled (no update for ${formatDuration(now - job.updatedAt)}; jobs process may have died)` + jobStatusClass = style.sync_error + } else if (job.status === 'running') { + jobStatusLabel = 'Running' + jobStatusClass = style.sync_running + } else if (job.status === 'completed') { + jobStatusLabel = 'Completed' + jobStatusClass = style.sync_ok + } else { + jobStatusLabel = 'Failed' + jobStatusClass = style.sync_error + } + } + + return <> +

Sync Status

+ {error !== undefined &&

Last refresh failed: {error}

} + +
+

Background sync job

+

+ Status: {jobStatusLabel} + {job !== null && <> + {' · '}started {formatTime(job.startedAt)} + {' · '}{job.finishedAt !== undefined ? `took ${formatDuration(job.finishedAt - job.startedAt)}` : `elapsed ${formatDuration(now - job.startedAt)}`} + } +

+ {job?.error !== undefined &&

+ Error{job.failedPhase !== undefined ? ` during ${PHASES.find(p => p.key === job.failedPhase)?.title ?? job.failedPhase}` : ''}: {job.error} +

} + {job !== null &&
    + {PHASES.map(({ key, title }) => { + const t = job.phases[key] + const active = job.currentPhase === key + const failed = job.failedPhase === key + let detail = 'pending' + if (t !== undefined) { + detail = t.finishedAt !== undefined + ? `done in ${formatDuration(t.finishedAt - t.startedAt)}` + : `running for ${formatDuration(now - t.startedAt)}` + } + if (failed) detail = 'failed' + return
  1. + {title}: {detail} +
  2. + })} +
} + {job !== null && Object.keys(job.networks).length > 0 &&
+ {Object.entries(job.networks).map(([slug, net]) => )} +
} +
+ +
+

Addresses (all syncs, including on-demand)

+
+ {Object.entries(data.networks).map(([slug, n]) => ( +
+
{NETWORK_TITLES[slug] ?? slug}
+ +
+ {n.syncing.toLocaleString()} syncing + {n.stuck > 0 && ({n.stuck.toLocaleString()} stuck)} + {' · '}{n.withoutTxs.toLocaleString()} with no txs yet +
+
+ ))} +
+

+ Transactions without linked prices: {data.unpricedTxs.toLocaleString()} (counted {formatDuration(now - data.unpricedTxsCheckedAt)} ago) +

+
+ + {data.syncingAddresses.length > 0 &&
+

Currently syncing addresses (oldest first)

+ + + + {data.syncingAddresses.map(a => ( + + + + + + ))} + +
AddressNetworkSyncing since
{a.address}{NETWORK_TITLES[a.network] ?? a.network}{formatDuration(now - a.since)} ago{a.stuck ? ' (stuck?)' : ''}
+
} + + {failedAddresses.length > 0 &&
+

Failed addresses in last job run

+ + + + {failedAddresses.map(f => ( + + + + + + ))} + +
AddressNetworkError
{f.address}{NETWORK_TITLES[f.slug] ?? f.slug}{f.error}
+
} + +} diff --git a/components/Admin/admin.module.css b/components/Admin/admin.module.css index 45a7a37fb..f47298039 100644 --- a/components/Admin/admin.module.css +++ b/components/Admin/admin.module.css @@ -6,3 +6,67 @@ .userEmail { text-decoration: underline; } + +.progress { + position: relative; + height: 24px; + border-radius: 6px; + background-color: var(--primary-bg-color); + overflow: hidden; + margin: 6px 0; +} + +.progress_fill { + height: 100%; + background-color: var(--accent-color); + transition: width 0.4s ease; +} + +.progress_label { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + color: var(--primary-text-color); +} + +.sync_meta { + font-size: 14px; + color: var(--secondary-text-color); +} + +.sync_ok { + color: #2e9e5b; +} + +.sync_running { + color: var(--accent-color); +} + +.sync_error { + color: #d9534f; +} + +.phases { + margin: 10px 0 15px; +} + +.phase_done { + color: var(--secondary-text-color); +} + +.phase_active { + font-weight: bold; + color: var(--accent-color); +} + +.phase_pending { + opacity: 0.6; +} + +.address_cell { + word-break: break-all; + font-family: monospace; +} diff --git a/jobs/workers.ts b/jobs/workers.ts index 2d815b5b9..aee2312a5 100644 --- a/jobs/workers.ts +++ b/jobs/workers.ts @@ -4,6 +4,7 @@ import { DEFAULT_WORKER_LOCK_DURATION } from 'constants/index' import { clearBalanceCache } from 'redis/balanceCache' import { clearDashboardCache } from 'redis/dashboardCache' import { clearPaymentCacheForAddress } from 'redis/paymentCache' +import { SyncProgressTracker } from 'redis/syncProgress' import { fetchAllAddresses } from 'services/addressService' import { cleanupExpiredClientPayments } from 'services/clientPaymentService' import { multiBlockchainClient } from 'services/chronikService' @@ -123,10 +124,22 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet queueName, async (job) => { console.log(`job ${job.id as string}: syncing missed prices, transactions and connecting them...`) - await priceService.syncPastDaysNewerPrices() - const changedAddresses = await multiBlockchainClient.syncMissedTransactions() - await connectAllTransactionsToPrices() - await invalidateCachesAfterBlockchainSync(changedAddresses) + const progress = new SyncProgressTracker() + await progress.start() + try { + await progress.startPhase('prices') + await priceService.syncPastDaysNewerPrices() + await progress.startPhase('transactions') + const changedAddresses = await multiBlockchainClient.syncMissedTransactions(progress) + await progress.startPhase('priceLinking') + await connectAllTransactionsToPrices() + await progress.startPhase('cacheInvalidation') + await invalidateCachesAfterBlockchainSync(changedAddresses) + await progress.finish('completed') + } catch (err: any) { + await progress.finish('failed', err?.message ?? String(err)) + throw err + } }, { connection: redisBullMQ, diff --git a/pages/admin/index.tsx b/pages/admin/index.tsx index 5744b8e9e..074bb7c18 100644 --- a/pages/admin/index.tsx +++ b/pages/admin/index.tsx @@ -13,6 +13,7 @@ import { multiBlockchainClient } from 'services/chronikService' import { MainNetworkSlugsType } from 'constants/index' import SubscribedAddresses from 'components/Admin/SubscribedAddresses' import ChronikURLs from 'components/Admin/ChronikURLs' +import SyncStatus from 'components/Admin/SyncStatus' import Loading from 'components/Loading' export const getServerSideProps: GetServerSideProps = async (context) => { @@ -97,6 +98,8 @@ export default function Admin ({ user, isAdmin, chronikUrls }: IProps): JSX.Elem

+ +

diff --git a/pages/api/admin/syncStatus.ts b/pages/api/admin/syncStatus.ts new file mode 100644 index 000000000..faf8313c5 --- /dev/null +++ b/pages/api/admin/syncStatus.ts @@ -0,0 +1,21 @@ +import { fetchSyncStatus } from 'services/syncStatusService' +import { fetchUserProfileFromId } from 'services/userService' +import { setSession } from 'utils/setSession' + +export default async (req: any, res: any): Promise => { + await setSession(req, res, true) + if (req.method !== 'GET') { + res.status(405).json({ statusCode: 405, message: 'method not allowed' }) + return + } + try { + const user = await fetchUserProfileFromId(req.session.userId) + if (user.isAdmin !== true) { + res.status(403).json({ statusCode: 403, message: 'unauthorised' }) + return + } + res.status(200).json(await fetchSyncStatus()) + } catch (err: any) { + res.status(500).json({ statusCode: 500, message: err.message }) + } +} diff --git a/redis/syncProgress.ts b/redis/syncProgress.ts new file mode 100644 index 000000000..a840eca43 --- /dev/null +++ b/redis/syncProgress.ts @@ -0,0 +1,185 @@ +import { redis } from './clientInstance' + +/** + * Live progress of the background blockchain sync job (jobs/workers.ts). + * The job runs in the jobs process, so its progress is written to Redis for + * the admin page (served by the Next.js process) to read. + */ +export const SYNC_PROGRESS_KEY = 'sync:progress' + +export const SYNC_PHASES = ['prices', 'transactions', 'priceLinking', 'cacheInvalidation'] as const +export type SyncPhase = typeof SYNC_PHASES[number] + +const MAX_FAILED_ADDRESSES_STORED = 50 +const MAX_ERROR_LENGTH = 300 +const FLUSH_THROTTLE_MS = 1000 +const HEARTBEAT_INTERVAL_MS = 30 * 1000 + +export interface PhaseTiming { + startedAt: number + finishedAt?: number +} + +export interface FailedAddress { + address: string + error: string +} + +export interface NetworkSyncProgress { + totalAddresses: number + addressesDone: number + txsCommitted: number + failedCount: number + failedAddresses: FailedAddress[] + startedAt: number + finishedAt?: number +} + +export interface SyncJobProgress { + status: 'running' | 'completed' | 'failed' + startedAt: number + finishedAt?: number + // Refreshed by a heartbeat while running; a stale value means the job process likely died. + updatedAt: number + currentPhase?: SyncPhase + // Phase that was running when the job failed. + failedPhase?: SyncPhase + phases: Partial> + networks: Record + error?: string +} + +const shortError = (err: string): string => { + const firstLine = err.split('\n')[0] + return firstLine.length > MAX_ERROR_LENGTH ? `${firstLine.slice(0, MAX_ERROR_LENGTH)}…` : firstLine +} + +export class SyncProgressTracker { + private readonly state: SyncJobProgress + private flushTimer: NodeJS.Timeout | undefined + private heartbeat: NodeJS.Timeout | undefined + + constructor () { + const now = Date.now() + this.state = { + status: 'running', + startedAt: now, + updatedAt: now, + phases: {}, + networks: {} + } + } + + getState (): SyncJobProgress { + return this.state + } + + async start (): Promise { + this.heartbeat = setInterval(() => { void this.flush() }, HEARTBEAT_INTERVAL_MS) + this.heartbeat.unref?.() + await this.flush() + } + + async startPhase (phase: SyncPhase): Promise { + const now = Date.now() + this.closeCurrentPhase(now) + this.state.currentPhase = phase + this.state.phases[phase] = { startedAt: now } + await this.flush() + } + + startNetwork (networkSlug: string, totalAddresses: number): void { + this.state.networks[networkSlug] = { + totalAddresses, + addressesDone: 0, + txsCommitted: 0, + failedCount: 0, + failedAddresses: [], + startedAt: Date.now() + } + this.scheduleFlush() + } + + addressesDone (networkSlug: string, count: number): void { + const net = this.state.networks[networkSlug] + if (net === undefined) return + net.addressesDone += count + this.scheduleFlush() + } + + txsCommitted (networkSlug: string, count: number): void { + const net = this.state.networks[networkSlug] + if (net === undefined) return + net.txsCommitted += count + this.scheduleFlush() + } + + addressesFailed (networkSlug: string, failed: Record): void { + const net = this.state.networks[networkSlug] + if (net === undefined) return + const entries = Object.entries(failed) + net.failedCount += entries.length + for (const [address, error] of entries) { + if (net.failedAddresses.length >= MAX_FAILED_ADDRESSES_STORED) break + net.failedAddresses.push({ address, error: shortError(error) }) + } + this.scheduleFlush() + } + + finishNetwork (networkSlug: string): void { + const net = this.state.networks[networkSlug] + if (net === undefined) return + net.finishedAt = Date.now() + this.scheduleFlush() + } + + async finish (status: 'completed' | 'failed', error?: string): Promise { + const now = Date.now() + if (status === 'failed') this.state.failedPhase = this.state.currentPhase + this.closeCurrentPhase(now) + this.state.status = status + this.state.finishedAt = now + if (error !== undefined) this.state.error = shortError(error) + if (this.heartbeat !== undefined) clearInterval(this.heartbeat) + this.heartbeat = undefined + await this.flush() + } + + private closeCurrentPhase (now: number): void { + const current = this.state.currentPhase + if (current === undefined) return + const timing = this.state.phases[current] + if (timing !== undefined && timing.finishedAt === undefined) timing.finishedAt = now + this.state.currentPhase = undefined + } + + private scheduleFlush (): void { + if (this.flushTimer !== undefined) return + this.flushTimer = setTimeout(() => { void this.flush() }, FLUSH_THROTTLE_MS) + this.flushTimer.unref?.() + } + + private async flush (): Promise { + if (this.flushTimer !== undefined) { + clearTimeout(this.flushTimer) + this.flushTimer = undefined + } + this.state.updatedAt = Date.now() + try { + await redis.set(SYNC_PROGRESS_KEY, JSON.stringify(this.state)) + } catch (err: any) { + // Progress reporting must never break the sync itself. + console.error(`[SYNC PROGRESS]: failed to write progress: ${err.message as string}`) + } + } +} + +export async function getSyncJobProgress (): Promise { + const raw = await redis.get(SYNC_PROGRESS_KEY) + if (raw === null || raw === undefined) return null + try { + return JSON.parse(raw) + } catch { + return null + } +} diff --git a/services/chronikService.ts b/services/chronikService.ts index f8199d6be..a295770ec 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -32,6 +32,7 @@ import { fetchAddressesArray, fetchAllAddressesForNetworkId, getEarliestUnconfir import * as ws from 'ws' import { BroadcastTxData } from 'ws-service/types' import config from 'config' +import { SyncProgressTracker } from 'redis/syncProgress' import io, { Socket } from 'socket.io-client' import moment from 'moment' import { OpReturnData, parseError, parseOpReturnData } from 'utils/validators' @@ -1265,12 +1266,14 @@ export class ChronikBlockchainClient { return changedAddresses } - public async syncAddresses (addresses: Address[], runTriggers = false): Promise { + public async syncAddresses (addresses: Address[], runTriggers = false, progress?: SyncProgressTracker): Promise { const failedAddressesWithErrors: KeyValueT = {} const successfulAddressesWithCount: KeyValueT = {} const productionAddressesIds = productionAddresses.filter(a => a.networkId === this.networkId).map(a => a.id) + progress?.startNetwork(this.networkSlug, addresses.length) if (addresses.length === 0) { + progress?.finishNetwork(this.networkSlug) return { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses: [] } } @@ -1292,6 +1295,7 @@ export class ChronikBlockchainClient { try { const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) changed.forEach(a => changedAddresses.add(a)) + progress?.txsCommitted(this.networkSlug, tuples.length) } catch (err) { changedAddressesUnknown = true throw err @@ -1306,6 +1310,7 @@ export class ChronikBlockchainClient { if (batch.phase === 'addresses-synced') { // marcador de slice => desmarca syncing await setSyncingBatch(batch.addressesSynced, false) + progress?.addressesDone(this.networkSlug, batch.addressesSynced.length) continue } @@ -1375,6 +1380,9 @@ export class ChronikBlockchainClient { }) } + progress?.addressesFailed(this.networkSlug, failedAddressesWithErrors) + progress?.finishNetwork(this.networkSlug) + const failed = Object.keys(failedAddressesWithErrors) const total = Object.values(successfulAddressesWithCount).reduce((p, c) => p + c, 0) console.log(`${this.CHRONIK_MSG_PREFIX} Finished syncing ${total} txs for ${addresses.length} addresses with ${failed.length} errors.`) @@ -1391,10 +1399,10 @@ export class ChronikBlockchainClient { * Returns the addresses whose txs changed (new or updated), or undefined if * the sync failed in a way that leaves that unknown. */ - public async syncMissedTransactions (): Promise { + public async syncMissedTransactions (progress?: SyncProgressTracker): Promise { const addresses = await fetchAllAddressesForNetworkId(this.networkId) try { - const { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses } = await this.syncAddresses(addresses, true) + const { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses } = await this.syncAddresses(addresses, true, progress) Object.keys(failedAddressesWithErrors).forEach((addr) => { console.error(`${this.CHRONIK_MSG_PREFIX}: When syncing missing addresses for address ${addr} encountered error: ${failedAddressesWithErrors[addr]}`) }) @@ -1623,10 +1631,10 @@ class MultiBlockchainClient { * Returns the addresses whose txs changed during the sync, or undefined if * that is unknown for any network (callers should then assume all changed). */ - public async syncMissedTransactions (): Promise { + public async syncMissedTransactions (progress?: SyncProgressTracker): Promise { await this.waitForStart() - const bch = await this.clients.bitcoincash.syncMissedTransactions() - const xec = await this.clients.ecash.syncMissedTransactions() + const bch = await this.clients.bitcoincash.syncMissedTransactions(progress) + const xec = await this.clients.ecash.syncMissedTransactions(progress) if (bch === undefined || xec === undefined) return undefined return [...bch, ...xec] } diff --git a/services/syncStatusService.ts b/services/syncStatusService.ts new file mode 100644 index 000000000..0ba23bf30 --- /dev/null +++ b/services/syncStatusService.ts @@ -0,0 +1,99 @@ +import prisma from 'prisma-local/clientInstance' +import { NETWORK_SLUGS_FROM_IDS } from 'constants/index' +import { getSyncJobProgress, SyncJobProgress } from 'redis/syncProgress' + +// An address flagged as syncing with no activity for this long is likely left +// 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 + +export interface NetworkAddressStats { + total: number + syncing: number + stuck: number + // lastSynced is the newest tx's timestamp, so null means no tx has been synced for the address. + withoutTxs: number +} + +export interface SyncingAddress { + address: string + network: string + // Last time the row changed (the syncing flag being set, or lastSynced moving). + since: number + stuck: boolean +} + +export interface SyncStatus { + serverTime: number + job: SyncJobProgress | null + networks: Record + syncingAddresses: SyncingAddress[] + unpricedTxs: number + unpricedTxsCheckedAt: number +} + +let unpricedTxsCache: { count: number, checkedAt: number } | 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 +} + +const countsByNetwork = (rows: Array<{ networkId: number, _count: { _all: number } }>): Record => + Object.fromEntries(rows.map(r => [r.networkId, r._count._all])) + +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([ + 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 } }), + 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 networks: Record = {} + for (const [id, slug] of Object.entries(NETWORK_SLUGS_FROM_IDS)) { + const networkId = Number(id) + networks[slug] = { + total: totalsMap[networkId] ?? 0, + syncing: syncingMap[networkId] ?? 0, + stuck: stuckMap[networkId] ?? 0, + withoutTxs: withoutTxsMap[networkId] ?? 0 + } + } + + return { + serverTime: now, + job, + networks, + syncingAddresses: syncingRows.map(a => ({ + address: a.address, + network: NETWORK_SLUGS_FROM_IDS[a.networkId] ?? String(a.networkId), + since: a.updatedAt.getTime(), + stuck: a.updatedAt < stuckBefore + })), + unpricedTxs: unpriced.count, + unpricedTxsCheckedAt: unpriced.checkedAt + } +} diff --git a/tests/unittests/syncProgress.test.ts b/tests/unittests/syncProgress.test.ts new file mode 100644 index 000000000..2bf691840 --- /dev/null +++ b/tests/unittests/syncProgress.test.ts @@ -0,0 +1,81 @@ +import { SyncProgressTracker, SYNC_PROGRESS_KEY } from '../../redis/syncProgress' +import { redis } from '../../redis/clientInstance' + +jest.mock('../../redis/clientInstance', () => ({ + redis: { set: jest.fn(), get: jest.fn() } +})) + +const lastWritten = (): any => { + const calls = (redis.set as jest.Mock).mock.calls + return JSON.parse(calls[calls.length - 1][1]) +} + +describe('SyncProgressTracker', () => { + beforeEach(() => { + jest.useFakeTimers() + jest.clearAllMocks() + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it('records phases, network progress and completion', async () => { + const tracker = new SyncProgressTracker() + await tracker.start() + await tracker.startPhase('prices') + await tracker.startPhase('transactions') + tracker.startNetwork('ecash', 10) + tracker.addressesDone('ecash', 4) + tracker.txsCommitted('ecash', 200) + tracker.txsCommitted('ecash', 50) + tracker.addressesFailed('ecash', { 'ecash:a': 'boom\nstack line' }) + tracker.finishNetwork('ecash') + await tracker.finish('completed') + + expect((redis.set as jest.Mock).mock.calls[0][0]).toBe(SYNC_PROGRESS_KEY) + const state = lastWritten() + expect(state.status).toBe('completed') + expect(state.currentPhase).toBeUndefined() + expect(state.phases.prices.finishedAt).toBeDefined() + expect(state.phases.transactions.finishedAt).toBeDefined() + expect(state.networks.ecash).toMatchObject({ + totalAddresses: 10, + addressesDone: 4, + txsCommitted: 250, + failedCount: 1, + failedAddresses: [{ address: 'ecash:a', error: 'boom' }] + }) + }) + + it('keeps the phase that was running when the job failed', async () => { + const tracker = new SyncProgressTracker() + await tracker.start() + await tracker.startPhase('priceLinking') + await tracker.finish('failed', 'db down') + + const state = lastWritten() + expect(state.status).toBe('failed') + expect(state.failedPhase).toBe('priceLinking') + expect(state.error).toBe('db down') + }) + + it('throttles writes of frequent counter updates', async () => { + const tracker = new SyncProgressTracker() + tracker.startNetwork('ecash', 100) + for (let i = 0; i < 50; i++) tracker.addressesDone('ecash', 1) + expect(redis.set).not.toHaveBeenCalled() + jest.advanceTimersByTime(1000) + await Promise.resolve() + expect(redis.set).toHaveBeenCalledTimes(1) + expect(lastWritten().networks.ecash.addressesDone).toBe(50) + }) + + it('does not throw when redis fails', async () => { + ;(redis.set as jest.Mock).mockRejectedValueOnce(new Error('redis down')) + jest.spyOn(console, 'error').mockImplementation(() => {}) + const tracker = new SyncProgressTracker() + await expect(tracker.start()).resolves.toBeUndefined() + await tracker.finish('completed') + }) +})