|
| 1 | +import { getServiceChildLogger } from '@crowd/logging' |
| 2 | +import { QueryExecutor } from '@crowd/data-access-layer/src/queryExecutor' |
| 3 | + |
| 4 | +import { getEnricherConfig } from '../config' |
| 5 | +import { fetchLightRepo, parseGithubUrl } from './fetchLightRepo' |
| 6 | +import { FetchError, LightRepoResult } from './types' |
| 7 | +import { updateEnrichedRepos } from './updateEnrichedRepos' |
| 8 | + |
| 9 | +const log = getServiceChildLogger('github-repos-enricher') |
| 10 | + |
| 11 | +async function fetchWithRetries( |
| 12 | + url: string, |
| 13 | + token: string, |
| 14 | + maxRetries: number, |
| 15 | +): Promise<LightRepoResult | null> { |
| 16 | + for (let attempt = 0; attempt <= maxRetries; attempt++) { |
| 17 | + try { |
| 18 | + return await fetchLightRepo(url, token) |
| 19 | + } catch (err) { |
| 20 | + if (!(err instanceof FetchError)) throw err |
| 21 | + |
| 22 | + if (['NOT_FOUND', 'AUTH', 'MALFORMED'].includes(err.kind)) { |
| 23 | + log.warn({ url, kind: err.kind }, err.message) |
| 24 | + return null |
| 25 | + } |
| 26 | + |
| 27 | + if (err.kind === 'RATE_LIMIT') throw err |
| 28 | + |
| 29 | + if (attempt < maxRetries) { |
| 30 | + const backoffMs = 1000 * 2 ** attempt |
| 31 | + log.warn({ url, attempt, backoffMs }, `Transient error, retrying: ${err.message}`) |
| 32 | + await new Promise((r) => setTimeout(r, backoffMs)) |
| 33 | + } else { |
| 34 | + log.error({ url }, `Gave up after ${maxRetries} retries: ${err.message}`) |
| 35 | + return null |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return null |
| 40 | +} |
| 41 | + |
| 42 | +async function fetchPage( |
| 43 | + qx: QueryExecutor, |
| 44 | + cursor: string | null, |
| 45 | + pageSize: number, |
| 46 | + updateIntervalHours: number, |
| 47 | +): Promise<{ rows: Array<{ id: string; url: string }>; urls: string[] }> { |
| 48 | + const rows = await qx.select( |
| 49 | + ` |
| 50 | + SELECT id, url |
| 51 | + FROM repos |
| 52 | + WHERE host = 'github' |
| 53 | + AND (last_synced_at IS NULL OR last_synced_at < NOW() - INTERVAL '$(updateIntervalHours) hours') |
| 54 | + AND ($(cursor) IS NULL OR id > $(cursor)) |
| 55 | + ORDER BY id |
| 56 | + LIMIT $(pageSize) |
| 57 | + `, |
| 58 | + { cursor, pageSize, updateIntervalHours }, |
| 59 | + ) |
| 60 | + return { |
| 61 | + rows, |
| 62 | + urls: rows.map((r: { url: string }) => r.url), |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +async function processPage( |
| 67 | + urls: string[], |
| 68 | + tokens: string[], |
| 69 | + parkedUntil: Map<string, number>, |
| 70 | + config: ReturnType<typeof getEnricherConfig>, |
| 71 | + qx: QueryExecutor, |
| 72 | +): Promise<{ fetched: number; failed: number; flushed: number }> { |
| 73 | + const validUrls: string[] = [] |
| 74 | + let skipped = 0 |
| 75 | + for (const url of urls) { |
| 76 | + try { |
| 77 | + parseGithubUrl(url) |
| 78 | + validUrls.push(url) |
| 79 | + } catch { |
| 80 | + skipped++ |
| 81 | + } |
| 82 | + } |
| 83 | + if (skipped > 0) log.warn(`Skipped ${skipped} non-GitHub URLs`) |
| 84 | + |
| 85 | + const buffer: LightRepoResult[] = [] |
| 86 | + const failures: Array<{ url: string; reason: string }> = [] |
| 87 | + let failed = 0 |
| 88 | + let flushed = 0 |
| 89 | + let nextIdx = 0 |
| 90 | + |
| 91 | + await Promise.all( |
| 92 | + tokens.map(async (token, tokenIdx) => { |
| 93 | + // Respect any park set during a previous page of this run |
| 94 | + const initialPark = (parkedUntil.get(token) ?? 0) - Date.now() |
| 95 | + if (initialPark > 0) { |
| 96 | + log.warn(`token#${tokenIdx} still parked, waiting ${Math.round(initialPark / 1000)}s`) |
| 97 | + await new Promise((r) => setTimeout(r, initialPark)) |
| 98 | + } |
| 99 | + |
| 100 | + while (true) { |
| 101 | + const idx = nextIdx++ |
| 102 | + if (idx >= validUrls.length) break |
| 103 | + const url = validUrls[idx] |
| 104 | + |
| 105 | + try { |
| 106 | + const result = await fetchWithRetries(url, token, config.maxRetries) |
| 107 | + if (result) { |
| 108 | + buffer.push(result) |
| 109 | + if (buffer.length >= config.batchSize) { |
| 110 | + const batch = buffer.splice(0) |
| 111 | + await updateEnrichedRepos(qx, batch) |
| 112 | + flushed += batch.length |
| 113 | + } |
| 114 | + } else { |
| 115 | + failures.push({ url, reason: 'see warn log above' }) |
| 116 | + failed++ |
| 117 | + } |
| 118 | + } catch (err) { |
| 119 | + if (err instanceof FetchError && err.kind === 'RATE_LIMIT') { |
| 120 | + const resetAt = err.resetAt ?? Date.now() + 60_000 |
| 121 | + const waitMs = Math.max(1_000, resetAt - Date.now()) |
| 122 | + parkedUntil.set(token, resetAt) |
| 123 | + log.warn( |
| 124 | + { tokenIdx, parkedUntil: new Date(resetAt).toISOString() }, |
| 125 | + `token#${tokenIdx} rate limited — parking for ${Math.round(waitMs / 1000)}s`, |
| 126 | + ) |
| 127 | + await new Promise((r) => setTimeout(r, waitMs)) |
| 128 | + failures.push({ url, reason: 'rate-limit' }) |
| 129 | + failed++ |
| 130 | + } else { |
| 131 | + log.error({ url, err }, 'Unexpected error') |
| 132 | + failures.push({ url, reason: (err as Error).message }) |
| 133 | + failed++ |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + }), |
| 138 | + ) |
| 139 | + |
| 140 | + if (buffer.length > 0) { |
| 141 | + await updateEnrichedRepos(qx, buffer) |
| 142 | + flushed += buffer.length |
| 143 | + } |
| 144 | + |
| 145 | + if (failures.length > 0) { |
| 146 | + log.warn({ failures }, `${failures.length} repo(s) failed this page`) |
| 147 | + } |
| 148 | + |
| 149 | + return { fetched: validUrls.length - failed, failed, flushed } |
| 150 | +} |
| 151 | + |
| 152 | +export async function runEnrichmentLoop( |
| 153 | + qx: QueryExecutor, |
| 154 | + config: ReturnType<typeof getEnricherConfig>, |
| 155 | + isShuttingDown: () => boolean, |
| 156 | +): Promise<void> { |
| 157 | + const parkedUntil = new Map<string, number>() |
| 158 | + let cursor: string | null = null |
| 159 | + let pageNum = 0 |
| 160 | + |
| 161 | + while (!isShuttingDown()) { |
| 162 | + pageNum++ |
| 163 | + |
| 164 | + const { rows, urls } = await fetchPage(qx, cursor, config.pageSize, config.updateIntervalHours) |
| 165 | + |
| 166 | + if (urls.length === 0) { |
| 167 | + log.info('No more repos to process, sleeping') |
| 168 | + await new Promise((r) => setTimeout(r, config.idleSleepSec * 1000)) |
| 169 | + cursor = null |
| 170 | + continue |
| 171 | + } |
| 172 | + |
| 173 | + const { fetched, failed, flushed } = await processPage(urls, config.tokens, parkedUntil, config, qx) |
| 174 | + |
| 175 | + log.info( |
| 176 | + `Page ${pageNum}: read=${urls.length} fetched=${fetched} failed=${failed} flushed=${flushed}`, |
| 177 | + ) |
| 178 | + |
| 179 | + if (rows.length > 0) { |
| 180 | + cursor = rows[rows.length - 1].id |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments