Repository navigation
Expand file tree
/
Copy pathgithub-fetcher.service.ts
More file actions
1324 lines (1195 loc) · 40.6 KB
/
Copy pathgithub-fetcher.service.ts
File metadata and controls
1324 lines (1195 loc) · 40.6 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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any */
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { readFileSync } from "fs";
import { sign } from "jsonwebtoken";
import {
Issue,
LabelEvent,
PrFile,
PrFileContent,
PullRequest,
Repo,
Review,
} from "../entities";
interface InstallationToken {
token: string;
expiresAt: number;
}
interface ClosingIssueReference {
number?: number;
repository?: { nameWithOwner?: string } | null;
}
// Files larger than this are stored with null content (AST parsing is wasteful past this).
const MAX_FILE_SIZE_BYTES = 1_000_000;
// Starting batch size for batched GraphQL file-content requests. Halves on failure.
const GRAPHQL_FILES_BATCH_SIZE = 50;
const sleep = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
@Injectable()
export class GitHubFetcherService implements OnModuleInit {
private readonly logger = new Logger(GitHubFetcherService.name);
private readonly appId: string;
private privateKey: string;
private readonly tokenCache = new Map<string, InstallationToken>();
constructor(
private readonly config: ConfigService,
@InjectRepository(PrFile)
private readonly prFileRepo: Repository<PrFile>,
@InjectRepository(PrFileContent)
private readonly prFileContentRepo: Repository<PrFileContent>,
@InjectRepository(PullRequest)
private readonly prRepo: Repository<PullRequest>,
@InjectRepository(Issue)
private readonly issueRepo: Repository<Issue>,
@InjectRepository(Review)
private readonly reviewRepo: Repository<Review>,
@InjectRepository(LabelEvent)
private readonly labelEventRepo: Repository<LabelEvent>,
@InjectRepository(Repo)
private readonly repoRepo: Repository<Repo>,
) {
this.appId = this.config.getOrThrow("GITHUB_APP_ID");
}
onModuleInit(): void {
const keyPath = this.config.getOrThrow("GITHUB_PRIVATE_KEY_PATH");
this.privateKey = readFileSync(keyPath, "utf8");
}
// --- Rate-limit-aware fetch ---
/**
* Wraps fetch() with GitHub rate-limit handling:
* - Parses X-RateLimit-Remaining on every response; warns below 500.
* - On 403/429 with remaining=0 or Retry-After header, waits until the
* rate limit resets and retries.
* - On 5xx / network errors, retries with exponential backoff (max 3).
*/
private async githubFetch(
url: string,
init: RequestInit = {},
): Promise<Response> {
const maxAttempts = 3;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
let res: Response;
try {
res = await fetch(url, init);
} catch (err) {
if (attempt < maxAttempts) {
const delay = Math.min(2000 * 2 ** (attempt - 1), 30_000);
this.logger.warn(
`Network error calling ${url}: ${err} (attempt ${attempt}/${maxAttempts}), retrying in ${delay}ms`,
);
await sleep(delay);
continue;
}
throw err;
}
const remainingStr = res.headers.get("x-ratelimit-remaining");
const remaining = remainingStr ? Number(remainingStr) : NaN;
if (!isNaN(remaining) && remaining > 0 && remaining < 500) {
this.logger.warn(`GitHub rate limit low: ${remaining} calls remaining`);
}
// Rate-limit exhausted → wait for reset and retry
if (
(res.status === 403 || res.status === 429) &&
(remaining === 0 || res.headers.has("retry-after"))
) {
const waitMs = this.computeRetryAfterMs(res);
this.logger.warn(
`Rate limit hit on ${url}: waiting ${Math.round(waitMs / 1000)}s before retry`,
);
await sleep(waitMs);
continue;
}
// Server-side transient error — retry with backoff
if (res.status >= 500 && res.status < 600 && attempt < maxAttempts) {
const delay = Math.min(2000 * 2 ** (attempt - 1), 30_000);
this.logger.warn(
`GitHub ${res.status} on ${url} (attempt ${attempt}/${maxAttempts}), retrying in ${delay}ms`,
);
await sleep(delay);
continue;
}
return res;
}
throw new Error(`githubFetch exhausted retries for ${url}`);
}
private computeRetryAfterMs(res: Response): number {
const retryAfter = res.headers.get("retry-after");
if (retryAfter) {
const seconds = Number(retryAfter);
if (!isNaN(seconds)) return (seconds + 1) * 1000;
const dateMs = Date.parse(retryAfter);
if (!isNaN(dateMs)) return Math.max(0, dateMs - Date.now()) + 1000;
}
const reset = res.headers.get("x-ratelimit-reset");
if (reset) {
const resetMs = Number(reset) * 1000;
if (!isNaN(resetMs)) return Math.max(0, resetMs - Date.now()) + 1000;
}
return 60_000;
}
private assertNoGraphQLErrors(body: any, context: string): void {
if (!body?.errors) return;
throw new Error(
`${context} GraphQL errors: ${JSON.stringify(body.errors)}`,
);
}
// --- Authentication ---
private createAppJwt(): string {
const now = Math.floor(Date.now() / 1000);
return sign(
{ iss: this.appId, iat: now - 60, exp: now + 600 },
this.privateKey,
{ algorithm: "RS256" },
);
}
private async getInstallationToken(installationId: string): Promise<string> {
const cached = this.tokenCache.get(installationId);
if (cached && cached.expiresAt > Date.now() + 60_000) {
return cached.token;
}
const jwt = this.createAppJwt();
const res = await this.githubFetch(
`https://api.github.com/app/installations/${installationId}/access_tokens`,
{
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
Accept: "application/vnd.github+json",
},
},
);
if (!res.ok) {
throw new Error(
`Failed to get installation token: ${res.status} ${await res.text()}`,
);
}
const body = await res.json();
this.tokenCache.set(installationId, {
token: body.token,
expiresAt: new Date(body.expires_at).getTime(),
});
return body.token;
}
private async getTokenForRepo(repoFullName: string): Promise<string> {
const repo = await this.repoRepo
.createQueryBuilder("repo")
.where("LOWER(repo.repo_full_name) = LOWER(:repoFullName)", {
repoFullName,
})
.getOne();
if (!repo?.installationId) {
throw new Error(`No installation for repo ${repoFullName}`);
}
return this.getInstallationToken(repo.installationId);
}
// --- REST: compare API for merge-base ---
/**
* Fetch the merge-base commit SHA between two refs.
* The merge-base is the common ancestor — the correct "before" state for
* computing a PR's own changes via tree-diff scoring (which differs from
* baseRefOid when the base branch has moved forward since PR open).
*/
async fetchMergeBaseSha(
repoFullName: string,
baseSha: string,
headSha: string,
): Promise<string | null> {
const token = await this.getTokenForRepo(repoFullName);
const maxAttempts = 3;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const res = await this.githubFetch(
`https://api.github.com/repos/${repoFullName}/compare/${baseSha}...${headSha}`,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
},
},
);
if (res.ok) {
const data: any = await res.json();
return data?.merge_base_commit?.sha ?? null;
}
if (attempt < maxAttempts) {
const delay = Math.min(5000 * 2 ** (attempt - 1), 30_000);
this.logger.warn(
`Compare API for ${repoFullName} failed: ${res.status} (attempt ${attempt}/${maxAttempts}), retrying in ${delay}ms`,
);
await new Promise((r) => setTimeout(r, delay));
}
} catch (err) {
if (attempt < maxAttempts) {
const delay = Math.min(5000 * 2 ** (attempt - 1), 30_000);
this.logger.warn(
`Compare API error for ${repoFullName}: ${err} (attempt ${attempt}/${maxAttempts}), retrying in ${delay}ms`,
);
await new Promise((r) => setTimeout(r, delay));
}
}
}
this.logger.warn(
`Compare API for ${repoFullName} failed after ${maxAttempts} attempts`,
);
return null;
}
// --- GraphQL: PR metadata (closing issues + body + last edit) ---
/**
* Fetch PR fields that require GraphQL — closing issue references,
* body text, and the lastEditedAt timestamp (which is specific to body
* edits, unlike REST's updated_at which changes on any interaction).
* Combined into one query to save a round trip.
*/
async fetchPrMetadata(
repoFullName: string,
prNumber: number,
): Promise<{
closingIssueNumbers: number[];
body: string | null;
lastEditedAt: string | null;
}> {
const [owner, repo] = repoFullName.split("/");
const token = await this.getTokenForRepo(repoFullName);
const query = `
query($owner: String!, $repo: String!, $pr: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr) {
bodyText
lastEditedAt
closingIssuesReferences(first: 10) {
nodes {
number
repository { nameWithOwner }
}
}
}
}
}
`;
const res = await this.githubFetch("https://api.github.com/graphql", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
variables: { owner, repo, pr: prNumber },
}),
});
if (!res.ok) {
throw new Error(
`GraphQL PR metadata fetch failed: ${res.status} ${await res.text()}`,
);
}
const body: any = await res.json();
this.assertNoGraphQLErrors(body, "PR metadata fetch");
const pr = body.data?.repository?.pullRequest;
if (!pr) {
throw new Error(`GraphQL PR metadata fetch returned no PR data`);
}
const nodes = pr.closingIssuesReferences?.nodes ?? [];
return {
closingIssueNumbers: this.sameRepoClosingIssueNumbers(
repoFullName,
nodes,
),
body: pr.bodyText ?? null,
lastEditedAt: pr.lastEditedAt ?? null,
};
}
private sameRepoClosingIssueNumbers(
repoFullName: string,
nodes: ClosingIssueReference[],
): number[] {
const expectedRepo = repoFullName.toLowerCase();
return nodes
.filter(
(node) =>
node.repository?.nameWithOwner?.toLowerCase() === expectedRepo,
)
.map((node) => node.number)
.filter((number): number is number => typeof number === "number");
}
// --- GraphQL: issue closure (which PR caused the current close) ---
/**
* Resolve the PR responsible for an issue's current closed state.
*
* Reads `ClosedEvent.closer` from the issue timeline and anchors to the
* issue's current `closedAt`, so reopen-then-reclose cycles attribute to
* the latest closer, not whichever PR first declared `Closes #N` in its
* body. When no PR closer is recorded — e.g. the issue was closed manually
* rather than auto-closed by the merge — falls back to the issue's
* closing-PR references (a merged same-repo PR). Returns `null` for non-PR
* closures (commits, projects), `NOT_PLANNED` closures, or when neither
* source yields a qualifying merged same-repo PR.
*
* Source of truth for `issues.solved_by_pr`. Issue discovery and the
* issue-bounty solver lookup both read from this field, so they stay 1:1.
*/
async fetchIssueClosingPr(
repoFullName: string,
issueNumber: number,
): Promise<number | null> {
const [owner, repo] = repoFullName.split("/");
const token = await this.getTokenForRepo(repoFullName);
const query = `
query($owner: String!, $repo: String!, $issue: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $issue) {
closedAt
stateReason
timelineItems(itemTypes: [CLOSED_EVENT], last: 20) {
nodes {
... on ClosedEvent {
createdAt
stateReason
closer {
__typename
... on PullRequest {
number
merged
state
baseRepository { nameWithOwner }
}
}
}
}
}
closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
nodes {
number
merged
mergedAt
baseRepository { nameWithOwner }
}
}
}
}
}
`;
const res = await this.githubFetch("https://api.github.com/graphql", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
variables: { owner, repo, issue: issueNumber },
}),
});
if (!res.ok) {
throw new Error(
`GraphQL issue closure fetch failed: ${res.status} ${await res.text()}`,
);
}
const body: any = await res.json();
this.assertNoGraphQLErrors(body, "Issue closure fetch");
const issue = body.data?.repository?.issue;
if (!issue) return null;
return this.selectClosingPr(repoFullName, issue);
}
private selectClosingPrFromTimeline(
repoFullName: string,
issue: {
closedAt: string | null;
timelineItems?: { nodes?: any[] };
},
): number | null {
const closedAt = issue.closedAt;
if (!closedAt) return null;
const expectedRepo = repoFullName.toLowerCase();
const nodes = issue.timelineItems?.nodes ?? [];
// Walk newest to oldest, find the close event matching the issue's
// current closedAt. NOT_PLANNED closures (and anything else non-COMPLETED)
// don't attribute a solver.
for (let i = nodes.length - 1; i >= 0; i--) {
const ev = nodes[i];
if (!ev) continue;
const stateReason = ev.stateReason;
if (
stateReason != null &&
String(stateReason).toUpperCase() !== "COMPLETED"
) {
continue;
}
if (ev.createdAt !== closedAt) continue;
const closer = ev.closer;
if (!closer || closer.__typename !== "PullRequest") return null;
if (
(closer.baseRepository?.nameWithOwner ?? "").toLowerCase() !==
expectedRepo
) {
return null;
}
const merged =
closer.merged === true ||
String(closer.state ?? "").toUpperCase() === "MERGED";
if (!merged) return null;
return typeof closer.number === "number" ? closer.number : null;
}
return null;
}
/**
* Resolve an issue's solving PR: prefer the authoritative
* `ClosedEvent.closer`, then fall back to the issue's closing-PR references.
* Shared by the webhook closure path and the backfill so both write
* `issues.solved_by_pr` identically.
*/
private selectClosingPr(
repoFullName: string,
issue: {
closedAt: string | null;
stateReason?: string | null;
timelineItems?: { nodes?: any[] };
closedByPullRequestsReferences?: { nodes?: any[] };
},
): number | null {
const viaCloser = this.selectClosingPrFromTimeline(repoFullName, issue);
if (viaCloser != null) return viaCloser;
return this.selectClosingPrFromClosingRefs(repoFullName, issue);
}
/**
* Fallback attribution from `closedByPullRequestsReferences` for issues that
* were closed without GitHub recording a PR closer (manual close, or a
* `Closes #N` keyword added after the PR merged). Gated to a COMPLETED
* closure and a merged same-repo PR that merged at or before the close —
* downstream gates (token threshold, one-issue-per-PR, author ≠ solver,
* branch eligibility) still apply on the consumer side.
*/
private selectClosingPrFromClosingRefs(
repoFullName: string,
issue: {
closedAt: string | null;
stateReason?: string | null;
closedByPullRequestsReferences?: { nodes?: any[] };
},
): number | null {
// Only COMPLETED closures attribute a solver — parity with the closer path.
if (
issue.stateReason != null &&
String(issue.stateReason).toUpperCase() !== "COMPLETED"
) {
return null;
}
const closedAt = issue.closedAt ? Date.parse(issue.closedAt) : null;
const expectedRepo = repoFullName.toLowerCase();
const candidates = (issue.closedByPullRequestsReferences?.nodes ?? [])
.filter((n: any) => n?.merged === true)
.filter(
(n: any) =>
(n.baseRepository?.nameWithOwner ?? "").toLowerCase() ===
expectedRepo,
)
.filter((n: any) => {
// A PR can't have caused a close that predates its merge.
if (closedAt == null || !n.mergedAt) return true;
return Date.parse(n.mergedAt) <= closedAt;
});
if (candidates.length === 0) return null;
// Deterministic pick: latest merge on/before the close (closest cause),
// tie-broken by highest PR number.
candidates.sort(
(a: any, b: any) =>
(Date.parse(b.mergedAt ?? "") || 0) -
(Date.parse(a.mergedAt ?? "") || 0) || b.number - a.number,
);
return candidates[0].number;
}
// --- PR files + contents (REST for list, batched GraphQL for contents) ---
/**
* Fetch the PR's file list (REST) and all file contents (batched GraphQL).
* GraphQL's object(expression: "SHA:path") returns content directly from git
* blobs, so it works even when fork branches are deleted post-merge. Files
* are fetched in batches of 50 to avoid GraphQL complexity limits; on
* failure the batch size halves down to a floor of 5.
*/
async fetchAndStorePrFiles(
repoFullName: string,
prNumber: number,
): Promise<void> {
const [owner, repo] = repoFullName.split("/");
const token = await this.getTokenForRepo(repoFullName);
const pr = await this.prRepo.findOneBy({ repoFullName, prNumber });
if (!pr) {
throw new Error(`PR ${repoFullName}#${prNumber} not found in DB`);
}
// Fetch and store the merge-base SHA. Needed for correct tree-diff
// scoring — differs from baseSha when base branch has advanced. Recompute
// on every fetch: a stored value can go stale when head advances via
// synchronize, leaving base_content pinned to an old ancestor and
// inflating the scored diff with churn from unrelated PRs.
if (pr.baseSha && pr.headSha) {
const mergeBaseSha = await this.fetchMergeBaseSha(
repoFullName,
pr.baseSha,
pr.headSha,
);
if (mergeBaseSha) {
await this.prRepo.update({ repoFullName, prNumber }, { mergeBaseSha });
pr.mergeBaseSha = mergeBaseSha;
}
}
// 1. Fetch file list via REST
const files = await this.fetchAllPrFiles(owner, repo, prNumber, token);
// Clear any stale data for this PR (e.g. after a synchronize event)
await this.prFileRepo.delete({ repoFullName, prNumber });
await this.prFileContentRepo.delete({ repoFullName, prNumber });
// 2. Upsert file metadata
for (const file of files) {
await this.prFileRepo.upsert(
{
repoFullName,
prNumber,
filename: file.filename,
previousFilename: file.previous_filename ?? null,
status: file.status,
additions: file.additions ?? 0,
deletions: file.deletions ?? 0,
changes: file.changes ?? 0,
},
["repoFullName", "prNumber", "filename"],
);
}
// 3. Fetch file contents in batches (base + head in one GraphQL call each)
if (!pr.headSha) {
throw new Error(
`PR ${repoFullName}#${prNumber} has no head SHA; cannot fetch content`,
);
}
// Prefer merge-base SHA (true common ancestor) over base SHA for
// fetching the "before" version of files. Falls back to base SHA if
// merge-base couldn't be resolved.
const baseForContents = pr.mergeBaseSha ?? pr.baseSha;
await this.fetchAndStoreBatchedContents(
repoFullName,
prNumber,
files,
owner,
repo,
token,
pr.headSha,
baseForContents,
);
}
private async fetchAllPrFiles(
owner: string,
repo: string,
prNumber: number,
token: string,
): Promise<any[]> {
const maxAttempts = 3;
let perPage = 100;
let attempt = 0;
while (attempt < maxAttempts) {
try {
const files: any[] = [];
let page = 1;
while (true) {
const res = await this.githubFetch(
`https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/files?per_page=${perPage}&page=${page}`,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
},
},
);
// Halve page size on server-side errors (large payload)
if ([502, 503, 504].includes(res.status)) {
perPage = Math.max(Math.floor(perPage / 2), 10);
throw new Error(
`status ${res.status}, retrying with per_page=${perPage}`,
);
}
if (!res.ok) {
throw new Error(
`Failed to fetch PR files: ${res.status} ${await res.text()}`,
);
}
const batch = await res.json();
files.push(...batch);
if (batch.length < perPage) return files;
page++;
}
} catch (err) {
attempt++;
if (attempt >= maxAttempts) throw err;
const delay = Math.min(5000 * 2 ** (attempt - 1), 30_000);
this.logger.warn(
`PR files fetch failed (attempt ${attempt}/${maxAttempts}): ${err}. Retrying in ${delay}ms`,
);
await new Promise((r) => setTimeout(r, delay));
}
}
return [];
}
/**
* Batched GraphQL fetch of base + head contents for all files in the PR.
* On complexity/size errors, batch size halves (50 → 25 → 12 → 6 → 5 floor).
*/
private async fetchAndStoreBatchedContents(
repoFullName: string,
prNumber: number,
files: any[],
owner: string,
repo: string,
token: string,
headSha: string,
baseSha: string | null,
): Promise<void> {
// Added files have only a head blob; removed files have only a base blob.
// Keep removed files when a base SHA is available so deletion scoring has
// the content that existed before the PR.
const contentFiles = files.filter(
(f) => f.status !== "removed" || baseSha !== null,
);
if (contentFiles.length === 0) return;
let batchSize = GRAPHQL_FILES_BATCH_SIZE;
const minBatchSize = 5;
for (let i = 0; i < contentFiles.length; ) {
const batch = contentFiles.slice(i, i + batchSize);
try {
await this.fetchContentBatch(
repoFullName,
prNumber,
batch,
owner,
repo,
token,
headSha,
baseSha,
);
i += batch.length;
} catch (err) {
if (batchSize > minBatchSize) {
const newSize = Math.max(Math.floor(batchSize / 2), minBatchSize);
this.logger.warn(
`GraphQL content batch failed (size=${batchSize}): ${err}. Halving to ${newSize}`,
);
batchSize = newSize;
// Retry same i with smaller batch
} else {
throw new Error(
`GraphQL content batch failed at min size ${minBatchSize}: ${err}`,
);
}
}
}
}
private async fetchContentBatch(
repoFullName: string,
prNumber: number,
batch: any[],
owner: string,
repo: string,
token: string,
headSha: string,
baseSha: string | null,
): Promise<void> {
const fields: string[] = [];
for (let i = 0; i < batch.length; i++) {
const file = batch[i];
// Base version — skip for added files or if we have no base SHA
if (file.status !== "added" && baseSha) {
const basePath = file.previous_filename ?? file.filename;
const baseExpr = this.escapeGraphql(`${baseSha}:${basePath}`);
fields.push(
`base${i}: object(expression: "${baseExpr}") { ... on Blob { text byteSize isBinary } }`,
);
}
// Removed files do not exist at head; store a null headContent while
// still fetching the base blob above.
if (file.status !== "removed") {
const headExpr = this.escapeGraphql(`${headSha}:${file.filename}`);
fields.push(
`head${i}: object(expression: "${headExpr}") { ... on Blob { text byteSize isBinary } }`,
);
}
}
const query = `
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
${fields.join("\n ")}
}
}
`;
const res = await this.githubFetch("https://api.github.com/graphql", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
variables: { owner, repo },
}),
});
if (!res.ok) {
throw new Error(
`GraphQL content fetch failed: ${res.status} ${await res.text()}`,
);
}
const body: any = await res.json();
this.assertNoGraphQLErrors(body, "Content fetch");
const repoData = body.data?.repository ?? {};
for (let i = 0; i < batch.length; i++) {
const file = batch[i];
const baseBlob = repoData[`base${i}`];
const headBlob = repoData[`head${i}`];
const isBinary = !!headBlob?.isBinary || !!baseBlob?.isBinary;
const headContent = this.extractBlobText(headBlob);
const baseContent = this.extractBlobText(baseBlob);
const byteSize = headBlob?.byteSize ?? baseBlob?.byteSize ?? null;
await this.prFileContentRepo.upsert(
{
repoFullName,
prNumber,
filename: file.filename,
baseContent,
headContent,
isBinary,
byteSize,
},
["repoFullName", "prNumber", "filename"],
);
}
}
private extractBlobText(blob: any): string | null {
if (!blob) return null;
if (blob.isBinary) return null;
if (
typeof blob.byteSize === "number" &&
blob.byteSize > MAX_FILE_SIZE_BYTES
) {
return null;
}
return blob.text ?? null;
}
private escapeGraphql(s: string): string {
// GraphQL string literals follow the same escape rules as JSON strings —
// reuse the JSON encoder, stripping the surrounding quotes. Covers
// backslash, double-quote, newlines, tabs, and control characters.
const json = JSON.stringify(s);
return json.slice(1, -1);
}
// --- Backfill ---
/**
* Page through GraphQL for PRs in a repo created within the last N days.
* Upserts each PR. Returns the list of PR numbers so the caller can
* enqueue follow-up fetch jobs for diffs + closing issues.
*/
async backfillPullRequests(
repoFullName: string,
sinceDate: Date,
): Promise<
{ prNumber: number; headSha: string | null; baseSha: string | null }[]
> {
const [owner, repo] = repoFullName.split("/");
const token = await this.getTokenForRepo(repoFullName);
const query = `
query($owner: String!, $repo: String!, $cursor: String) {
repository(owner: $owner, name: $repo) {
defaultBranchRef { name }
pullRequests(
first: 50,
after: $cursor,
orderBy: {field: CREATED_AT, direction: DESC}
) {
pageInfo { hasNextPage endCursor }
nodes {
number
title
bodyText
state
createdAt
closedAt
mergedAt
lastEditedAt
merged
author {
login
... on User { databaseId }
... on Bot { databaseId }
}
authorAssociation
mergedBy { login }
baseRef { name }
headRef { name }
headRepository { nameWithOwner }
baseRefOid
headRefOid
additions
deletions
commits { totalCount }
labels(first: 10) { nodes { name } }
reviews(first: 10) {
nodes {
submittedAt
state
authorAssociation
author {
login
... on User { databaseId }
... on Bot { databaseId }
}
}
}
timelineItems(
itemTypes: [LABELED_EVENT, UNLABELED_EVENT]
first: 30
) {
nodes {
__typename
... on LabeledEvent {
createdAt
label { name }
actor {
login
... on User { databaseId }
}
}
... on UnlabeledEvent {
createdAt
label { name }
actor {
login
... on User { databaseId }
}
}
}
}
}
}
}
}
`;
const prs: {
prNumber: number;
headSha: string | null;
baseSha: string | null;
}[] = [];
let cursor: string | null = null;
let defaultBranchWritten = false;
while (true) {
const res: Response = await this.githubFetch(
"https://api.github.com/graphql",
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
variables: { owner, repo, cursor },
}),
},
);
if (!res.ok) {
throw new Error(
`Backfill PR GraphQL failed: ${res.status} ${await res.text()}`,
);
}