All files / services recompute-stale-scores.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 1/1
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                          5x   5x 8x   8x     3x       5x    
/**
 * Recompute quality scores for stale projects.
 *
 * Decision 2B2: stale-only filter — only processes projects where
 * qualityScoreComputedAt IS NULL or dateUpdated > qualityScoreComputedAt.
 * Capped at 100 rows per tick to stay within Cloudflare Worker CPU budget.
 *
 * Called from the hourly cron (E2A) BEFORE rebuildSearchIndexes so that
 * the search index sees fresh scores on rebuild.
 */
import type { Dal } from "../dal";
 
export interface RecomputeResult {
	rowsProcessed: number;
}
 
export async function recomputeAllStaleScores(
	dal: Dal,
): Promise<RecomputeResult> {
	// Find up to 100 stale projects. The partial index
	// idx_projects_score_stale makes this O(1) lookup for the NULL case.
	const stale = await dal.projects.findStale(100);
 
	for (const { id } of stale) {
		try {
			// Pass empty data object — no content change, just triggers recompute hook.
			await dal.projects.computeAndSaveQualityScore(id);
		} catch (err) {
			// Log per-row failure, continue batch. One bad row must not stop the rest.
			console.error("[recomputeAllStaleScores]", { projectId: id, err });
		}
	}
 
	return { rowsProcessed: stale.length };
}