-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.ts
More file actions
266 lines (251 loc) · 9.76 KB
/
client.ts
File metadata and controls
266 lines (251 loc) · 9.76 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
import { retry } from '@octokit/plugin-retry';
import { throttling } from '@octokit/plugin-throttling';
import { Octokit } from 'octokit';
export type GitHubClient = {
checkAuth: (reporter?: GitHubReporter) => Promise<void>;
getRepo: (owner: string, repo: string, reporter?: GitHubReporter) => Promise<Record<string, unknown>>;
getFileContents: (
owner: string,
repo: string,
filePath: string,
ref?: string,
reporter?: GitHubReporter,
) => Promise<string>;
listRepositoryIssues: (
owner: string,
repo: string,
since?: string,
limit?: number,
reporter?: GitHubReporter,
state?: 'open' | 'closed',
) => Promise<Array<Record<string, unknown>>>;
getIssue: (owner: string, repo: string, number: number, reporter?: GitHubReporter) => Promise<Record<string, unknown>>;
getPull: (owner: string, repo: string, number: number, reporter?: GitHubReporter) => Promise<Record<string, unknown>>;
listIssueComments: (owner: string, repo: string, number: number, reporter?: GitHubReporter) => Promise<Array<Record<string, unknown>>>;
listPullReviews: (owner: string, repo: string, number: number, reporter?: GitHubReporter) => Promise<Array<Record<string, unknown>>>;
listPullReviewComments: (
owner: string,
repo: string,
number: number,
reporter?: GitHubReporter,
) => Promise<Array<Record<string, unknown>>>;
};
export type GitHubReporter = (message: string) => void;
export class GitHubRequestError extends Error {
readonly status?: number;
constructor(message: string, status?: number) {
super(message);
this.name = 'GitHubRequestError';
this.status = status;
}
}
type RequestOptions = {
token: string;
userAgent?: string;
timeoutMs?: number;
pageDelayMs?: number;
};
type OctokitPage<T> = {
data: T[];
};
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const seconds = Math.ceil(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes < 60) return remainingSeconds === 0 ? `${minutes}m` : `${minutes}m ${remainingSeconds}s`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes === 0 ? `${hours}h` : `${hours}h ${remainingMinutes}m`;
}
function formatResetTime(resetSeconds: string | null | undefined): string | null {
if (!resetSeconds) return null;
const value = Number(resetSeconds);
if (!Number.isFinite(value) || value <= 0) return null;
return new Date(value * 1000).toISOString();
}
export function makeGitHubClient(options: RequestOptions): GitHubClient {
const userAgent = options.userAgent ?? 'ghcrawl';
const timeoutMs = options.timeoutMs ?? 30_000;
const pageDelayMs = options.pageDelayMs ?? 5000;
const BaseOctokit = Octokit.plugin(retry, throttling);
function createOctokit(reporter?: GitHubReporter) {
return new BaseOctokit({
auth: options.token,
request: {
timeout: timeoutMs,
},
userAgent,
retry: {
doNotRetry: [400, 401, 403, 404, 422],
retries: 4,
},
throttle: {
fallbackSecondaryRateRetryAfter: Math.ceil(pageDelayMs / 1000),
onRateLimit: (retryAfter, requestOptions) => {
const responseHeaders = (requestOptions.response as { headers?: Record<string, string> } | undefined)?.headers;
const resetAt = formatResetTime(responseHeaders?.['x-ratelimit-reset']);
const remaining = responseHeaders?.['x-ratelimit-remaining'];
const method = requestOptions.method ?? 'GET';
const url = requestOptions.url ?? 'unknown';
reporter?.(
`[github] backoff rate-limited wait=${formatDuration(retryAfter * 1000)}${remaining ? ` remaining=${remaining}` : ''}${resetAt ? ` reset_at=${resetAt}` : ''} method=${method} url=${url}`,
);
return true;
},
onSecondaryRateLimit: (retryAfter, requestOptions) => {
const method = requestOptions.method ?? 'GET';
const url = requestOptions.url ?? 'unknown';
reporter?.(
`[github] backoff secondary-rate-limit wait=${formatDuration(retryAfter * 1000)} method=${method} url=${url}`,
);
return true;
},
},
});
}
async function request<T>(label: string, reporter: GitHubReporter | undefined, fn: (octokit: InstanceType<typeof BaseOctokit>) => Promise<T>): Promise<T> {
reporter?.(`[github] request ${label}`);
const octokit = createOctokit(reporter);
try {
return await fn(octokit);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const status = typeof (error as { status?: unknown })?.status === 'number' ? Number((error as { status?: unknown }).status) : undefined;
throw new GitHubRequestError(`GitHub request failed for ${label}: ${message}`, status);
}
}
async function paginate<T>(
label: string,
limit: number | undefined,
reporter: GitHubReporter | undefined,
iteratorFactory: (octokit: InstanceType<typeof BaseOctokit>) => AsyncIterable<OctokitPage<T>>,
): Promise<T[]> {
reporter?.(`[github] request ${label}`);
const octokit = createOctokit(reporter);
const out: T[] = [];
try {
let pageIndex = 0;
for await (const page of iteratorFactory(octokit)) {
pageIndex += 1;
const remaining = typeof limit === 'number' ? Math.max(limit - out.length, 0) : page.data.length;
out.push(...page.data.slice(0, remaining));
reporter?.(`[github] page ${pageIndex} fetched count=${page.data.length} accumulated=${out.length}`);
if (typeof limit === 'number' && out.length >= limit) {
break;
}
await delay(pageDelayMs);
}
return out;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const status = typeof (error as { status?: unknown })?.status === 'number' ? Number((error as { status?: unknown }).status) : undefined;
throw new GitHubRequestError(`GitHub pagination failed for ${label}: ${message}`, status);
}
}
return {
async checkAuth(reporter) {
await request('GET /rate_limit', reporter, async (octokit) => {
await octokit.request('GET /rate_limit');
});
},
async getRepo(owner, repo, reporter) {
return request(`GET /repos/${owner}/${repo}`, reporter, async (octokit) => {
const response = await octokit.rest.repos.get({ owner, repo });
return response.data as Record<string, unknown>;
});
},
async getFileContents(owner, repo, filePath, ref, reporter) {
return request(`GET /repos/${owner}/${repo}/contents/${filePath}`, reporter, async (octokit) => {
const response = await octokit.rest.repos.getContent({
owner,
repo,
path: filePath,
ref,
mediaType: {
format: 'raw',
},
});
if (typeof response.data !== 'string') {
throw new Error(`GitHub content for ${filePath} was not returned as raw text.`);
}
return response.data;
});
},
async listRepositoryIssues(owner, repo, since, limit, reporter, state = 'open') {
return paginate(
`GET /repos/${owner}/${repo}/issues state=${state} per_page=100`,
limit,
reporter,
(octokit) =>
octokit.paginate.iterator(octokit.rest.issues.listForRepo, {
owner,
repo,
state,
sort: 'updated',
direction: 'desc',
per_page: 100,
since,
}) as AsyncIterable<OctokitPage<Record<string, unknown>>>,
);
},
async getIssue(owner, repo, number, reporter) {
return request(`GET /repos/${owner}/${repo}/issues/${number}`, reporter, async (octokit) => {
const response = await octokit.rest.issues.get({ owner, repo, issue_number: number });
return response.data as Record<string, unknown>;
});
},
async getPull(owner, repo, number, reporter) {
return request(`GET /repos/${owner}/${repo}/pulls/${number}`, reporter, async (octokit) => {
const response = await octokit.rest.pulls.get({ owner, repo, pull_number: number });
return response.data as Record<string, unknown>;
});
},
async listIssueComments(owner, repo, number, reporter) {
return paginate(
`GET /repos/${owner}/${repo}/issues/${number}/comments per_page=100`,
undefined,
reporter,
(octokit) =>
octokit.paginate.iterator(octokit.rest.issues.listComments, {
owner,
repo,
issue_number: number,
per_page: 100,
}) as AsyncIterable<OctokitPage<Record<string, unknown>>>,
);
},
async listPullReviews(owner, repo, number, reporter) {
return paginate(
`GET /repos/${owner}/${repo}/pulls/${number}/reviews per_page=100`,
undefined,
reporter,
(octokit) =>
octokit.paginate.iterator(octokit.rest.pulls.listReviews, {
owner,
repo,
pull_number: number,
per_page: 100,
}) as AsyncIterable<OctokitPage<Record<string, unknown>>>,
);
},
async listPullReviewComments(owner, repo, number, reporter) {
return paginate(
`GET /repos/${owner}/${repo}/pulls/${number}/comments per_page=100`,
undefined,
reporter,
(octokit) =>
octokit.paginate.iterator(octokit.rest.pulls.listReviewComments, {
owner,
repo,
pull_number: number,
per_page: 100,
}) as AsyncIterable<OctokitPage<Record<string, unknown>>>,
);
},
};
}