Repository navigation
Expand file tree
/
Copy pathgithub.ts
More file actions
578 lines (531 loc) · 18.1 KB
/
Copy pathgithub.ts
File metadata and controls
578 lines (531 loc) · 18.1 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import { Octokit } from '@octokit/rest'
import childProcess from 'child_process'
import { promisify } from 'util'
import { saveCachedData } from './cache'
import { isExcludedContributor } from './config'
import { Repo, Stat, Week } from './types'
const execFile = promisify(childProcess.execFile)
// Minimal structural client shape so tests can inject a fake without depending
// on the full Octokit type.
export interface StatsResponse {
status: number
data: unknown
}
export interface RequestSignal {
request?: { signal?: AbortSignal }
}
export interface OctokitLike {
rest: {
repos: {
getContributorsStats: (args: {
owner: string
repo: string
} & RequestSignal) => Promise<StatsResponse>
listForOrg: unknown
}
users: {
getByUsername: (args: {
username: string
} & RequestSignal) => Promise<{ data: unknown }>
getById: (args: {
account_id: number
} & RequestSignal) => Promise<{ data: unknown }>
}
}
paginate: (method: unknown, args: unknown) => Promise<unknown[]>
}
// Resolve a token lazily. Environment tokens take priority so CI (which sets
// GITHUB_TOKEN/GH_TOKEN) never shells out. The local `gh` fallback is only
// attempted when both environment variables are absent.
export const resolveToken = async (): Promise<string | undefined> => {
const envToken = (process.env.GH_TOKEN || process.env.GITHUB_TOKEN || '').trim()
if (envToken) {
return envToken
}
try {
const { stdout } = await execFile('gh', ['auth', 'token'])
const token = stdout.trim()
return token || undefined
} catch {
return undefined
}
}
let octokitPromise: Promise<Octokit> | undefined
export const getOctokit = (): Promise<Octokit> => {
if (!octokitPromise) {
octokitPromise = resolveToken().then(
token => new Octokit(token ? { auth: token } : {}),
)
}
return octokitPromise
}
const asClient = async (octokit?: OctokitLike): Promise<OctokitLike> => {
if (octokit) {
return octokit
}
return (await getOctokit()) as unknown as OctokitLike
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
const isFiniteNonNegative = (value: unknown): value is number =>
typeof value === 'number' && Number.isFinite(value) && value >= 0
const isValidWeek = (value: unknown): value is Week =>
isRecord(value) &&
isFiniteNonNegative(value.w) &&
isFiniteNonNegative(value.a) &&
isFiniteNonNegative(value.d) &&
isFiniteNonNegative(value.c)
// A payload that does not match the documented stats shape is not a transient
// network problem, so it must never be retried or allowed to overwrite a valid
// historical archive.
export class MalformedPayloadError extends Error {
constructor(message: string) {
super(message)
this.name = 'MalformedPayloadError'
}
}
// Validate the raw stats payload at the API boundary before it is trusted or
// archived. GitHub returns HTTP 202 with an empty object while stats are still
// being computed; that is handled by the retry loop, not here.
export const isValidStat = (value: unknown): value is Stat => {
if (!isRecord(value)) {
return false
}
if (!isFiniteNonNegative(value.total) || !Array.isArray(value.weeks)) {
return false
}
if (!value.weeks.every(isValidWeek)) {
return false
}
const author = value.author
if (author === null) {
return true
}
return (
isRecord(author) &&
typeof author.login === 'string' &&
author.login.trim().length > 0
)
}
export const validateContributorsPayload = (data: unknown): Stat[] => {
if (!Array.isArray(data)) {
throw new MalformedPayloadError('Malformed contributors payload: expected an array')
}
const invalidIndex = data.findIndex(entry => !isValidStat(entry))
if (invalidIndex >= 0) {
throw new MalformedPayloadError(
`Malformed contributors payload: invalid entry at index ${invalidIndex}`,
)
}
return data as Stat[]
}
export interface RetryConfig {
retries: number
minTimeout: number
maxTimeout: number
factor: number
totalBudgetMs: number
requestTimeoutMs: number
sleep: (ms: number) => Promise<void>
now: () => number
}
// Tuned for a daily refresh: a handful of quick retries within a small per-repo
// budget. GitHub 202 (stats still computing) is expected to recover across
// scheduled runs, so there is no point in blocking a single build for long.
export const defaultRetryConfig: RetryConfig = {
retries: 4,
minTimeout: 3000,
maxTimeout: 15000,
factor: 2,
totalBudgetMs: 60 * 1000,
requestTimeoutMs: 30 * 1000,
sleep: ms =>
new Promise(resolve => {
setTimeout(resolve, ms)
}),
now: () => Date.now(),
}
const getStatus = (error: unknown): number | undefined => {
const err = error as { status?: number; response?: { status?: number } }
return err?.status ?? err?.response?.status
}
const getHeaders = (
error: unknown,
): Record<string, string | number | undefined> | undefined => {
const err = error as {
response?: { headers?: Record<string, string | number | undefined> }
headers?: Record<string, string | number | undefined>
}
return err?.response?.headers ?? err?.headers
}
// Decide whether an API error is worth retrying. 202 means stats are still
// being computed; 403/429 and 5xx/network errors are transient (rate limits
// and outages). 404/401/422 and malformed payloads are not retried.
export const isRetryableGithubError = (error: unknown): boolean => {
if (error instanceof MalformedPayloadError) {
return false
}
const status = getStatus(error)
if (status === undefined) {
return true
}
if (status === 202 || status === 403 || status === 408 || status === 429) {
return true
}
return status >= 500
}
// Honor Retry-After (seconds or HTTP date) and X-RateLimit-Reset (epoch
// seconds) when present, otherwise fall back to exponential backoff.
export const getRetryDelayMs = (
error: unknown,
attempt: number,
config: RetryConfig,
): number | undefined => {
const headers = getHeaders(error)
const retryAfter = headers?.['retry-after']
if (retryAfter !== undefined && retryAfter !== null) {
const seconds = Number(retryAfter)
if (Number.isFinite(seconds) && seconds >= 0) {
return seconds * 1000
}
const timestamp = Date.parse(String(retryAfter))
if (!Number.isNaN(timestamp)) {
return Math.max(0, timestamp - config.now())
}
}
const reset = headers?.['x-ratelimit-reset']
if (reset !== undefined && reset !== null) {
const resetMs = Number(reset) * 1000
if (Number.isFinite(resetMs)) {
return Math.max(0, resetMs - config.now())
}
}
return Math.min(config.maxTimeout, config.minTimeout * config.factor ** attempt)
}
// Attach a real AbortSignal to the underlying request so a timeout actually
// cancels the in-flight HTTP call instead of merely racing it from the outside.
const withRequestTimeout = async <T>(
ms: number,
run: (signal: AbortSignal) => Promise<T>,
): Promise<T> => {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), ms)
try {
return await run(controller.signal)
} catch (error) {
if (controller.signal.aborted) {
throw new Error(`GitHub request timed out after ${ms}ms`)
}
throw error
} finally {
clearTimeout(timer)
}
}
// Bounded retry loop. Both the time spent sleeping and the wall-clock elapsed
// time (including request time) are bounded by totalBudgetMs, so a slow or
// hostile server cannot stall a build indefinitely. The callback receives the
// timeout for that attempt, which is capped by the remaining budget so no
// request can outlive the deadline.
export const withBoundedRetry = async <T>(
fn: (attempt: number, requestTimeoutMs: number) => Promise<T>,
config: RetryConfig,
isRetryable: (error: unknown) => boolean = isRetryableGithubError,
): Promise<T> => {
const startedAt = config.now()
let attempt = 0
for (;;) {
const remaining = config.totalBudgetMs - (config.now() - startedAt)
if (remaining <= 0) {
throw new Error(
`GitHub request budget of ${config.totalBudgetMs}ms exhausted`,
)
}
try {
return await fn(attempt, Math.min(config.requestTimeoutMs, remaining))
} catch (error) {
const elapsed = config.now() - startedAt
if (
!isRetryable(error) ||
attempt >= config.retries ||
elapsed >= config.totalBudgetMs
) {
throw error
}
const delay = getRetryDelayMs(error, attempt, config) ?? 0
if (elapsed + delay > config.totalBudgetMs) {
throw error
}
await config.sleep(delay)
attempt += 1
}
}
}
const fetchContributorStats = async (
client: OctokitLike,
owner: string,
repo: string,
requestTimeoutMs: number,
): Promise<Stat[]> => {
const response = await withRequestTimeout(requestTimeoutMs, signal =>
client.rest.repos.getContributorsStats({
owner,
repo,
request: { signal },
}),
)
if (response.status === 202) {
throw Object.assign(new Error('Stats being computed (202)'), { status: 202 })
}
return validateContributorsPayload(response.data)
}
export interface GetContributorsOptions {
octokit?: OctokitLike
previous?: Stat[] | null
retry?: Partial<RetryConfig>
save?: (repoFullName: string, data: Stat[]) => Promise<unknown>
}
// Bots are never trusted, archived, or returned: bot-only activity must not
// churn the archives or published output.
const withoutBots = (stats: Stat[]): Stat[] =>
stats.filter(entry => !isExcludedContributor(entry.author))
// Stable identity of a stat author: the numeric GitHub account id when known,
// otherwise null. Comparing this first is what makes identity checks immune to
// username reuse and account renames.
const authorAccountId = (author: Stat['author']): number | null => {
if (!author) {
return null
}
const id = (author as { id?: unknown }).id
return typeof id === 'number' && Number.isFinite(id) ? id : null
}
// Always refresh from GitHub on a normal build, but never replace valid
// historical data with a failure, empty or malformed response. The previous
// archive (if any) is returned as a fallback, with any legacy bot rows removed.
// Archive persistence failures propagate so the build fails loudly instead of
// pretending success.
export const getContributors = async (
owner: string,
repo: string,
options: GetContributorsOptions = {},
): Promise<Stat[]> => {
const repoFullName = `${owner}/${repo}`
const previous = options.previous ?? null
const client = await asClient(options.octokit)
const config: RetryConfig = { ...defaultRetryConfig, ...options.retry }
const save = options.save ?? saveCachedData
let raw: Stat[]
try {
raw = await withBoundedRetry(
(_attempt, requestTimeoutMs) =>
fetchContributorStats(client, owner, repo, requestTimeoutMs),
config,
)
} catch (error) {
console.error(`[ERROR] failed to refresh ${repoFullName}:`, error)
const fallback = withoutBots(previous ?? [])
if (fallback.length > 0) {
console.warn(`⚠️ keeping previous archived stats for ${repoFullName}`)
}
return fallback
}
// A truly empty payload is treated like a transient failure: keep the last
// good human archive rather than overwriting it with nothing.
if (raw.length === 0) {
console.warn(`⚠️ empty data for ${repoFullName}; keeping previous archive`)
return withoutBots(previous ?? [])
}
const fresh = withoutBots(raw)
const previouslyKnown = withoutBots(previous ?? [])
// A valid payload that only contains bots: if we already know humans, keep
// them (the bot-only payload may be partial), otherwise persist an empty
// archive so an all-bot repo stops churning and stays stable.
if (fresh.length === 0) {
if (previouslyKnown.length > 0) {
console.warn(
`⚠️ ${repoFullName}: fresh data had no human contributors; keeping previous archive`,
)
return previouslyKnown
}
await save(repoFullName, [])
console.info(
`✅ Refreshed 0 human contributors for ${repoFullName} (bots excluded)`,
)
return []
}
// Reconcile per identity against the previous archive. Match by stable
// numeric ID whenever the previous row has one, otherwise by case-insensitive
// login (legacy rows without IDs only). A same-ID rename or updated stats
// supersede the previous row. A previous human missing from fresh data is
// retained. A fresh row reusing that human's login with an ID that was not
// previously known (including a missing ID when the previous ID is known) is a
// misattributed replacement and is dropped, even when the original ID also
// reappears under a renamed login; a previously known ID taking over the login
// is a legitimate rename and is allowed.
// Every archived login pinned to the ID(s) previously recorded for it, plus
// the set of all archived IDs (globally known identities).
const previousIds = new Set<number>()
const previousPinnedByLogin = new Map<string, Set<number>>()
for (const stat of previouslyKnown) {
const author = stat.author
if (!author) {
continue
}
const id = authorAccountId(author)
if (id === null) {
continue
}
previousIds.add(id)
const loginKey = author.login.toLowerCase()
const pinned = previousPinnedByLogin.get(loginKey)
if (pinned) {
pinned.add(id)
} else {
previousPinnedByLogin.set(loginKey, new Set([id]))
}
}
// A fresh row is a misattributed claimant when it reuses a login previously
// pinned to a different identity and its own ID is neither that pinned ID nor
// any other previously known ID. Deciding per row (not per login) keeps the
// result independent of fresh row order and never drops a trusted row that
// shares its login with a claimant.
const isConflictingClaimant = (stat: Stat): boolean => {
const author = stat.author
if (!author) {
return false
}
const pinned = previousPinnedByLogin.get(author.login.toLowerCase())
if (!pinned) {
return false
}
const id = authorAccountId(author)
if (id !== null && (pinned.has(id) || previousIds.has(id))) {
return false
}
return true
}
const accepted = fresh.filter(stat => !isConflictingClaimant(stat))
const droppedClaimants = fresh.filter(isConflictingClaimant)
// Retain an archived identity only when no accepted fresh row accounts for it.
const acceptedIds = new Set<number>()
const acceptedLogins = new Set<string>()
for (const stat of accepted) {
const author = stat.author
if (!author) {
continue
}
const id = authorAccountId(author)
if (id !== null) {
acceptedIds.add(id)
}
acceptedLogins.add(author.login.toLowerCase())
}
const retained: Stat[] = []
for (const stat of previouslyKnown) {
const author = stat.author
if (!author) {
continue
}
const id = authorAccountId(author)
if (id !== null) {
if (!acceptedIds.has(id)) {
retained.push(stat)
}
} else if (!acceptedLogins.has(author.login.toLowerCase())) {
retained.push(stat)
}
}
if (droppedClaimants.length > 0) {
console.warn(
`⚠️ ${repoFullName}: fresh data reused login(s) with a different identity (${droppedClaimants
.map(stat => stat.author!.login)
.join(', ')}); dropped the fresh claimant and kept the archived identity`,
)
}
if (retained.length > 0) {
console.warn(
`⚠️ ${repoFullName}: retaining ${retained.length} archived contributor row(s) missing from fresh data (${retained
.map(stat => stat.author!.login)
.join(', ')})`,
)
}
const hasNullAuthors = fresh.some(stat => !stat.author)
if (hasNullAuthors) {
console.warn(
`⚠️ ${repoFullName}: ${fresh.filter(stat => !stat.author).length}/${
fresh.length
} contributors have null author (skipped when aggregating)`,
)
}
const reconciled = [...accepted, ...retained]
await save(repoFullName, reconciled)
console.info(
`✅ Refreshed ${accepted.length} contributors for ${repoFullName}` +
(retained.length > 0 ? ` (retained ${retained.length} archived)` : ''),
)
return reconciled
}
export const getRepos = async (octokit?: OctokitLike): Promise<Repo[]> => {
const client = await asClient(octokit)
const repos = await withRequestTimeout(
defaultRetryConfig.requestTimeoutMs,
signal =>
client.paginate(client.rest.repos.listForOrg, {
org: 'poooi',
per_page: 100,
request: { signal },
}),
)
return repos as Repo[]
}
// Profile lookups run once per contributor and are best-effort, so they get a
// short timeout: a widespread outage must not let them dominate the job budget.
export const USER_REQUEST_TIMEOUT_MS = 5_000
export const getUser = async (
login: string,
octokit?: OctokitLike,
): Promise<Record<string, unknown> | null> => {
const client = await asClient(octokit)
try {
const response = await withRequestTimeout(
USER_REQUEST_TIMEOUT_MS,
signal =>
client.rest.users.getByUsername({
username: login,
request: { signal },
}),
)
return (response.data as Record<string, unknown>) ?? null
} catch (error) {
if (getStatus(error) === 404) {
return null
}
throw error
}
}
// Look an account up by its stable numeric ID (`GET /user/{account_id}`). A 404
// returns null: the account is not found/unavailable, which may indicate
// deletion but is not definitive proof of it. Timeouts, rate limits and 5xx are
// transient failures and throw, so the caller never mistakes an outage for a
// deletion and can retry on a future build.
export const getUserById = async (
accountId: number,
octokit?: OctokitLike,
): Promise<Record<string, unknown> | null> => {
const client = await asClient(octokit)
try {
const response = await withRequestTimeout(
USER_REQUEST_TIMEOUT_MS,
signal =>
client.rest.users.getById({
account_id: accountId,
request: { signal },
}),
)
return (response.data as Record<string, unknown>) ?? null
} catch (error) {
if (getStatus(error) === 404) {
return null
}
throw error
}
}