|
1 | 1 | import type { Range, Result, ScoreParams } from 'nimiq-validator-trustscore/types' |
2 | 2 | import type { NewScore } from './drizzle' |
3 | | -import { and, count, desc, eq, gte, lte, or } from 'drizzle-orm' |
| 3 | +import { and, desc, eq, gte, lte, or, sql } from 'drizzle-orm' |
4 | 4 | import { getRange } from 'nimiq-validator-trustscore/range' |
5 | 5 | import { computeScore } from 'nimiq-validator-trustscore/score' |
6 | 6 | import { activity } from '../db/schema' |
| 7 | +import { isScoreLagMissing } from './score-freshness' |
7 | 8 | import { getStoredValidatorsId } from './validators' |
8 | 9 |
|
9 | 10 | interface CalculateScoreResult { |
@@ -117,12 +118,36 @@ export async function upsertScoresSnapshotEpoch(): Result<CalculateScoreResult> |
117 | 118 | return [true, undefined, { scores, range }] |
118 | 119 | } |
119 | 120 |
|
120 | | -export async function isMissingScore(range: Range): Promise<boolean> { |
121 | | - const scoreCount = await useDrizzle() |
122 | | - .select({ count: count(tables.scores.epochNumber) }) |
| 121 | +export async function getLatestScoreEpoch(): Promise<number | null> { |
| 122 | + const latestScoreEpoch = await useDrizzle() |
| 123 | + .select({ |
| 124 | + latestScoreEpoch: sql<number>`max(${tables.scores.epochNumber})`, |
| 125 | + }) |
123 | 126 | .from(tables.scores) |
124 | | - .where(eq(tables.scores.epochNumber, range.toEpoch)) |
125 | 127 | .get() |
126 | | - .then(res => res?.count || 0) |
127 | | - return scoreCount === 0 |
| 128 | + .then((res) => { |
| 129 | + const value = res?.latestScoreEpoch |
| 130 | + if (value === null || value === undefined) |
| 131 | + return null |
| 132 | + if (typeof value === 'number') |
| 133 | + return value |
| 134 | + |
| 135 | + const parsed = Number(value) |
| 136 | + return Number.isFinite(parsed) ? parsed : null |
| 137 | + }) |
| 138 | + |
| 139 | + return latestScoreEpoch |
| 140 | +} |
| 141 | + |
| 142 | +export async function isScoreMissingWithLag( |
| 143 | + range: Range, |
| 144 | + allowedLagEpochs = 1, |
| 145 | + latestScoreEpoch?: number | null, |
| 146 | +): Promise<boolean> { |
| 147 | + const epoch = latestScoreEpoch === undefined ? await getLatestScoreEpoch() : latestScoreEpoch |
| 148 | + return isScoreLagMissing({ |
| 149 | + toEpoch: range.toEpoch, |
| 150 | + latestScoreEpoch: epoch, |
| 151 | + allowedLagEpochs, |
| 152 | + }) |
128 | 153 | } |
0 commit comments