-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.test.ts
More file actions
596 lines (550 loc) · 18 KB
/
Copy pathgithub.test.ts
File metadata and controls
596 lines (550 loc) · 18 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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import fs from 'fs-extra'
import os from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
getContributors,
getRepos,
getRetryDelayMs,
getUser,
isRetryableGithubError,
isValidStat,
MalformedPayloadError,
OctokitLike,
resolveToken,
RetryConfig,
validateContributorsPayload,
withBoundedRetry,
} from './github'
import { loadCachedData, saveCachedData } from './cache'
import { Stat, Week } from './types'
const week = (overrides: Partial<Week> = {}): Week => ({
w: 1,
a: 1,
d: 0,
c: 1,
...overrides,
})
const stat = (login: string | null, total = 1): Stat => ({
total,
weeks: [week()],
author: login ? ({ login } as unknown as Stat['author']) : null,
})
const botStat = (login: string, type = 'Bot', total = 1): Stat => ({
total,
weeks: [week()],
author: { login, type } as unknown as Stat['author'],
})
interface FakeOptions {
getContributorsStats?: (args: {
owner: string
repo: string
request?: { signal?: AbortSignal }
}) => Promise<{
status: number
data: unknown
}>
getByUsername?: (args: {
username: string
request?: { signal?: AbortSignal }
}) => Promise<{ data: unknown }>
repos?: unknown[]
}
// A fake that never resolves until its request signal is aborted, mirroring how
// Octokit's fetch propagates the AbortSignal.
const abortable = (signal?: AbortSignal): Promise<never> =>
new Promise((_resolve, reject) => {
if (signal?.aborted) {
reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
return
}
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
)
})
const makeClient = (options: FakeOptions = {}): OctokitLike => ({
rest: {
repos: {
getContributorsStats:
options.getContributorsStats ??
(async () => ({ status: 200, data: [stat('Javran')] })),
listForOrg: {},
},
users: {
getByUsername:
options.getByUsername ?? (async () => ({ data: { login: 'Javran' } })),
},
},
paginate: async () => options.repos ?? [{ full_name: 'poooi/poi' }],
})
const fastRetry = (overrides: Partial<RetryConfig> = {}): Partial<RetryConfig> => ({
retries: 2,
minTimeout: 0,
maxTimeout: 0,
factor: 2,
totalBudgetMs: 1000,
requestTimeoutMs: 1000,
sleep: async () => {},
now: () => 0,
...overrides,
})
describe('payload validation', () => {
it('accepts well-formed stats including null authors', () => {
expect(isValidStat(stat('a'))).toBe(true)
expect(isValidStat(stat(null))).toBe(true)
})
it('rejects malformed totals and weeks', () => {
expect(isValidStat({ total: '1', weeks: [week()], author: stat('a').author })).toBe(false)
expect(isValidStat({ total: -1, weeks: [week()], author: stat('a').author })).toBe(false)
expect(isValidStat({ total: Infinity, weeks: [week()], author: stat('a').author })).toBe(false)
expect(
isValidStat({
total: 1,
weeks: [{ w: 1, a: 1, d: 0 }],
author: stat('a').author,
}),
).toBe(false)
expect(
isValidStat({ total: 1, weeks: [{ w: 1, a: 1, d: 0, c: -2 }], author: stat('a').author }),
).toBe(false)
})
it('rejects empty author logins and non-arrays', () => {
expect(
isValidStat({ total: 1, weeks: [week()], author: { login: ' ' } }),
).toBe(false)
expect(() => validateContributorsPayload({})).toThrow(MalformedPayloadError)
})
})
describe('token resolution', () => {
const originalGh = process.env.GH_TOKEN
const originalGithub = process.env.GITHUB_TOKEN
afterEach(() => {
if (originalGh === undefined) {
delete process.env.GH_TOKEN
} else {
process.env.GH_TOKEN = originalGh
}
if (originalGithub === undefined) {
delete process.env.GITHUB_TOKEN
} else {
process.env.GITHUB_TOKEN = originalGithub
}
})
it('prefers GH_TOKEN, then GITHUB_TOKEN', async () => {
process.env.GH_TOKEN = 'gh-token'
process.env.GITHUB_TOKEN = 'github-token'
expect(await resolveToken()).toBe('gh-token')
delete process.env.GH_TOKEN
expect(await resolveToken()).toBe('github-token')
})
})
describe('retry classification', () => {
it('retries 202, rate limits, 5xx and network errors, but not malformed payloads', () => {
expect(isRetryableGithubError({ status: 202 })).toBe(true)
expect(isRetryableGithubError({ status: 403 })).toBe(true)
expect(isRetryableGithubError({ status: 429 })).toBe(true)
expect(isRetryableGithubError({ status: 503 })).toBe(true)
expect(isRetryableGithubError(new Error('socket hang up'))).toBe(true)
expect(isRetryableGithubError({ status: 404 })).toBe(false)
expect(isRetryableGithubError(new MalformedPayloadError('bad'))).toBe(false)
})
it('honors Retry-After seconds and X-RateLimit-Reset', () => {
const config = fastRetry() as RetryConfig
expect(
getRetryDelayMs({ response: { headers: { 'retry-after': '2' } } }, 0, config),
).toBe(2000)
expect(
getRetryDelayMs(
{ response: { headers: { 'x-ratelimit-reset': '5' } } },
0,
{ ...config, now: () => 0 },
),
).toBe(5000)
})
})
describe('bounded retry', () => {
it('stops retrying once the wall-clock budget is exhausted', async () => {
const sleep = vi.fn(async () => {})
const config = {
...fastRetry(),
retries: 10,
totalBudgetMs: 100,
sleep,
now: () => 0,
} as RetryConfig
let calls = 0
await expect(
withBoundedRetry(
async () => {
calls += 1
throw { status: 403, response: { headers: { 'retry-after': '5000' } } }
},
config,
),
).rejects.toBeTruthy()
expect(calls).toBe(1)
expect(sleep).not.toHaveBeenCalled()
})
it('caps each attempt timeout by the remaining budget', async () => {
let nowValue = 0
const attemptTimeouts: number[] = []
const config = {
...fastRetry(),
retries: 10,
totalBudgetMs: 50,
requestTimeoutMs: 1000,
now: () => nowValue,
sleep: async () => {},
} as RetryConfig
await expect(
withBoundedRetry(async (_attempt, requestTimeoutMs) => {
attemptTimeouts.push(requestTimeoutMs)
nowValue += 30
throw { status: 500 }
}, config),
).rejects.toBeTruthy()
expect(attemptTimeouts).toEqual([50, 20])
})
it('never starts a request at or after the deadline', async () => {
let nowValue = 0
const attemptTimeouts: number[] = []
const config = {
...fastRetry(),
retries: 5,
totalBudgetMs: 100,
requestTimeoutMs: 1000,
now: () => nowValue,
sleep: async (ms: number) => {
nowValue += ms
},
} as RetryConfig
await expect(
withBoundedRetry(async (_attempt, requestTimeoutMs) => {
attemptTimeouts.push(requestTimeoutMs)
nowValue += 50
throw {
status: 403,
response: { headers: { 'retry-after': '0.05' } },
}
}, config),
).rejects.toThrow('budget')
expect(attemptTimeouts).toEqual([100])
})
})
describe('getContributors refresh behaviour', () => {
it('refreshes over the archive and saves the fresh stats', async () => {
const fresh = [stat('Javran', 9)]
const client = makeClient({ getContributorsStats: async () => ({ status: 200, data: fresh }) })
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'poi-plugin-mo2', {
octokit: client,
previous: [stat('Javran', 1)],
retry: fastRetry(),
save,
})
expect(result).toEqual(fresh)
expect(save).toHaveBeenCalledWith('Javran/poi-plugin-mo2', fresh)
})
it('keeps historical stats when 202 retries are exhausted', async () => {
const previous = [stat('Javran', 5)]
const client = makeClient({ getContributorsStats: async () => ({ status: 202, data: {} }) })
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'poi-plugin-mo2', {
octokit: client,
previous,
retry: fastRetry(),
save,
})
expect(result).toEqual(previous)
expect(save).not.toHaveBeenCalled()
})
it('keeps historical stats on server errors', async () => {
const previous = [stat('Javran', 5)]
const client = makeClient({
getContributorsStats: async () => {
throw { status: 500 }
},
})
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save: vi.fn(async () => true),
})
expect(result).toEqual(previous)
})
it('honors Retry-After before succeeding', async () => {
const sleep = vi.fn(async () => {})
const client = makeClient({
getContributorsStats: vi
.fn()
.mockRejectedValueOnce({ status: 403, response: { headers: { 'retry-after': '2' } } })
.mockResolvedValueOnce({ status: 200, data: [stat('Javran', 3)] }),
})
const result = await getContributors('Javran', 'mo2', {
octokit: client,
retry: fastRetry({ sleep, totalBudgetMs: 10_000 }),
save: vi.fn(async () => true),
})
expect(result).toEqual([stat('Javran', 3)])
expect(sleep).toHaveBeenCalledWith(2000)
})
it('does not retry malformed payloads and keeps the archive', async () => {
const getStats = vi.fn(async () => ({
status: 200,
data: [{ total: 'nope', weeks: [], author: null }],
}))
const client = makeClient({ getContributorsStats: getStats })
const previous = [stat('Javran', 5)]
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry({ retries: 5 }),
save: vi.fn(async () => true),
})
expect(result).toEqual(previous)
expect(getStats).toHaveBeenCalledTimes(1)
})
it('does not overwrite the archive with an empty response', async () => {
const save = vi.fn(async () => true)
const client = makeClient({ getContributorsStats: async () => ({ status: 200, data: [] }) })
const previous = [stat('Javran', 5)]
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save,
})
expect(result).toEqual(previous)
expect(save).not.toHaveBeenCalled()
})
it('fails the build when persisting fresh stats fails', async () => {
const client = makeClient({
getContributorsStats: async () => ({ status: 200, data: [stat('Javran', 3)] }),
})
await expect(
getContributors('Javran', 'mo2', {
octokit: client,
retry: fastRetry(),
save: async () => {
throw new Error('disk full')
},
}),
).rejects.toThrow('disk full')
})
it('keeps the whole previous snapshot when fresh null authors hide known identities', async () => {
const previous = [stat('Javran', 5), stat(null, 2)]
const client = makeClient({
getContributorsStats: async () => ({ status: 200, data: [stat(null, 8)] }),
})
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save,
})
expect(result).toEqual(previous)
expect(save).not.toHaveBeenCalled()
})
it('accepts fresh data containing null authors when no identity is lost', async () => {
const fresh = [stat(null, 8), stat('Javran', 1)]
const save = vi.fn(async () => true)
const client = makeClient({ getContributorsStats: async () => ({ status: 200, data: fresh }) })
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous: null,
retry: fastRetry(),
save,
})
expect(result).toEqual(fresh)
expect(save).toHaveBeenCalledWith('Javran/mo2', fresh)
})
it('aborts the underlying request when it exceeds the request timeout', async () => {
let signal: AbortSignal | undefined
const client = makeClient({
getContributorsStats: args => {
signal = args.request?.signal
return abortable(args.request?.signal)
},
})
const previous = [stat('Javran', 5)]
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry({ retries: 0, requestTimeoutMs: 10 }),
save: vi.fn(async () => true),
})
expect(result).toEqual(previous)
expect(signal?.aborted).toBe(true)
})
it('excludes bots before persisting the archive', async () => {
const human = stat('Javran', 5)
const fresh = [
human,
botStat('github-actions[bot]'),
botStat('some-app', 'Bot'),
botStat('CustomTool[bot]', 'User'),
botStat('chiba-bot', 'User'),
botStat('claude', 'User'),
]
const client = makeClient({
getContributorsStats: async () => ({ status: 200, data: fresh }),
})
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'mo2', {
octokit: client,
retry: fastRetry(),
save,
})
expect(result).toEqual([human])
expect(save).toHaveBeenCalledWith('Javran/mo2', [human])
})
it('drops legacy bot rows from the failure fallback', async () => {
const previous = [stat('Javran', 5), botStat('github-actions[bot]', 'Bot', 15)]
const client = makeClient({
getContributorsStats: async () => {
throw { status: 500 }
},
})
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save: vi.fn(async () => true),
})
expect(result).toEqual([previous[0]])
})
it('persists an empty archive for an all-bot repo', async () => {
const client = makeClient({
getContributorsStats: async () => ({
status: 200,
data: [botStat('github-actions[bot]', 'Bot', 15)],
}),
})
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous: [botStat('github-actions[bot]', 'Bot', 14)],
retry: fastRetry(),
save,
})
expect(result).toEqual([])
expect(save).toHaveBeenCalledWith('Javran/mo2', [])
})
it('preserves previous humans when a fresh payload filters to zero', async () => {
const previous = [stat('Javran', 5), botStat('github-actions[bot]', 'Bot', 14)]
const client = makeClient({
getContributorsStats: async () => ({
status: 200,
data: [botStat('github-actions[bot]', 'Bot', 15)],
}),
})
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save,
})
expect(result).toEqual([previous[0]])
expect(save).not.toHaveBeenCalled()
})
it('does not freeze a human refresh when a bot disappears with null authors', async () => {
const previous = [stat('Javran', 5), botStat('github-actions[bot]', 'Bot', 15)]
const fresh = [stat('Javran', 6), stat(null, 1)]
const client = makeClient({
getContributorsStats: async () => ({ status: 200, data: fresh }),
})
const save = vi.fn(async () => true)
const result = await getContributors('Javran', 'mo2', {
octokit: client,
previous,
retry: fastRetry(),
save,
})
expect(result).toEqual(fresh)
expect(save).toHaveBeenCalledWith('Javran/mo2', fresh)
})
it('does not rewrite the archive when only bot totals change', async () => {
const dir = await fs.mkdtemp(join(os.tmpdir(), 'contributors-bot-'))
try {
const human = stat('Javran', 5)
const changes: boolean[] = []
const save = async (name: string, data: Stat[]) => {
const changed = await saveCachedData(name, data, dir)
changes.push(changed)
return changed
}
const first = makeClient({
getContributorsStats: async () => ({
status: 200,
data: [human, botStat('github-actions[bot]', 'Bot', 14)],
}),
})
await getContributors('poooi', 'poi', {
octokit: first,
previous: null,
retry: fastRetry(),
save,
})
const archived = await loadCachedData('poooi/poi', dir)
expect(archived).toEqual([human])
const second = makeClient({
getContributorsStats: async () => ({
status: 200,
data: [human, botStat('github-actions[bot]', 'Bot', 15)],
}),
})
const result = await getContributors('poooi', 'poi', {
octokit: second,
previous: archived,
retry: fastRetry(),
save,
})
expect(result).toEqual([human])
// First run wrote the human archive; the bot-only increase was a no-op.
expect(changes).toEqual([true, false])
} finally {
await fs.remove(dir)
}
})
})
describe('getRepos and getUser', () => {
it('paginates org repos', async () => {
const client = makeClient({ repos: [{ full_name: 'poooi/poi' }] })
expect(await getRepos(client)).toEqual([{ full_name: 'poooi/poi' }])
})
it('passes an abort signal to pagination and user lookups', async () => {
let paginateSignal: AbortSignal | undefined
let userSignal: AbortSignal | undefined
const client = makeClient()
client.paginate = async (_method, args) => {
paginateSignal = (args as { request?: { signal?: AbortSignal } }).request
?.signal
return [{ full_name: 'poooi/poi' }]
}
client.rest.users.getByUsername = async args => {
userSignal = args.request?.signal
return { data: { login: 'Javran' } }
}
await getRepos(client)
await getUser('Javran', client)
expect(paginateSignal).toBeInstanceOf(AbortSignal)
expect(userSignal).toBeInstanceOf(AbortSignal)
})
it('returns null for missing users and throws for other errors', async () => {
const missing = makeClient({
getByUsername: async () => {
throw { status: 404 }
},
})
expect(await getUser('ghost', missing)).toBeNull()
const broken = makeClient({
getByUsername: async () => {
throw { status: 500 }
},
})
await expect(getUser('ghost', broken)).rejects.toBeTruthy()
})
})