Repository navigation
Expand file tree
/
Copy pathissues.ts
More file actions
255 lines (234 loc) · 11.7 KB
/
Copy pathissues.ts
File metadata and controls
255 lines (234 loc) · 11.7 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
import { ghEnvironment } from './gh-env.ts';
import { runWithInput } from './run-with-input.ts';
const PAGE_SIZE = 100;
const MAX_PAGES = 10;
const MAX_ISSUES = PAGE_SIZE * MAX_PAGES;
const MAX_COLLABORATORS = PAGE_SIZE * MAX_PAGES;
const MAX_BODY_LENGTH = 65_536;
// Covers one bounded 100-record page, including JSON-escaped bodies, labels and response overhead.
export const ISSUE_PAGE_MAX_BYTES = 64 * 1024 * 1024;
/**
* How long a stopped `gh` gets after SIGTERM before SIGKILL, and how long its inherited output pipes may stay open after
* it exits. A fetch settles only when gh has stopped, so a fetch aborted at its 12 s deadline (web/issues.ts) settles up
* to 0.75 s later: 12.75 s, below the 15-second serving request budget.
*/
export const ISSUE_KILL_GRACE_MS = 500, ISSUE_PIPE_GRACE_MS = 250;
export type IssueAuthorAssociation =
| 'OWNER' | 'MEMBER' | 'COLLABORATOR' | 'CONTRIBUTOR'
| 'FIRST_TIMER' | 'FIRST_TIME_CONTRIBUTOR' | 'MANNEQUIN' | 'NONE';
export interface RepositoryIssue {
readonly repository: string;
readonly number: number;
readonly title: string;
readonly body: string;
readonly url: string;
readonly createdAt: string;
readonly updatedAt: string;
readonly comments: number;
readonly positiveReactions: number;
readonly labels: readonly string[];
readonly authorLogin: string | null;
readonly authorAssociation: IssueAuthorAssociation;
readonly trust: 'trusted' | 'requires-approval';
}
export interface IssueSnapshot {
readonly repository: string;
readonly retrievedAt: string;
readonly issues: readonly RepositoryIssue[];
}
export interface IssueGateway {
readonly repository: string;
fetch(options?: { signal?: AbortSignal; timeoutMs?: number }): Promise<IssueSnapshot>;
}
type RunGh = (args: readonly string[], options?: { signal?: AbortSignal }) => Promise<string>;
const associations = new Set<IssueAuthorAssociation>([
'OWNER', 'MEMBER', 'COLLABORATOR', 'CONTRIBUTOR', 'FIRST_TIMER',
'FIRST_TIME_CONTRIBUTOR', 'MANNEQUIN', 'NONE',
]);
function object(value: unknown, message: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(message);
return value as Record<string, unknown>;
}
function boundedString(value: unknown, field: string, maximum: number, nullable = false): string {
if (nullable && value === null) return '';
if (typeof value !== 'string' || value.length > maximum) throw new Error(`GitHub returned an invalid issue ${field}.`);
return value;
}
function count(value: unknown, field: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) throw new Error(`GitHub returned an invalid issue ${field}.`);
return value as number;
}
function login(value: unknown, context: 'issue author' | 'collaborator'): string {
if (typeof value !== 'string' || !value || value.length > 100 || /[\s\u0000-\u001f\u007f]/u.test(value))
throw new Error(`GitHub returned an invalid ${context} login.`);
return value;
}
function repositoryName(value: string): boolean {
if (value.length > 201 || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value)) return false;
return value.split('/').every(part => part !== '.' && part !== '..' && part.length <= 100);
}
function sameGithubUrl(value: unknown, expected: string, field: string): string {
const url = boundedString(value, field, 2048);
if (url.toLowerCase() !== expected.toLowerCase()) throw new Error(`GitHub returned an invalid issue ${field}.`);
return url;
}
function timestamp(value: unknown, field: string): string {
const text = boundedString(value, field, 64);
const parsed = Date.parse(text);
const canonical = text.includes('.') ? text : text.replace('Z', '.000Z');
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(text)
|| !Number.isFinite(parsed) || new Date(parsed).toISOString() !== canonical)
throw new Error(`GitHub returned an invalid issue ${field}.`);
return text;
}
function normalizeIssue(repository: string, value: unknown): RepositoryIssue | null {
const issue = object(value, 'GitHub returned a malformed issue.');
if (!Number.isSafeInteger(issue.number) || (issue.number as number) < 1) throw new Error('GitHub returned an invalid issue number.');
const number = issue.number as number;
if (Object.hasOwn(issue, 'pull_request')) {
const marker = object(issue.pull_request, 'GitHub returned an invalid pull request marker.');
sameGithubUrl(marker.url, `https://api.github.com/repos/${repository}/pulls/${number}`, 'pull request marker');
return null;
}
if (issue.state !== 'open') throw new Error('GitHub returned a non-open issue.');
const url = sameGithubUrl(issue.html_url, `https://github.com/${repository}/issues/${number}`, 'URL');
const createdAt = timestamp(issue.created_at, 'creation time');
const updatedAt = timestamp(issue.updated_at, 'update time');
if (Date.parse(updatedAt) < Date.parse(createdAt)) throw new Error('GitHub returned an issue update before its creation.');
if (!Array.isArray(issue.labels) || issue.labels.length > 100) throw new Error('GitHub returned invalid issue labels.');
const labels = issue.labels.map(label => {
const name = boundedString(object(label, 'GitHub returned an invalid issue label.').name, 'label', 100);
if (!name.trim()) throw new Error('GitHub returned an empty issue label.');
return name;
});
if (new Set(labels.map(label => label.toLocaleLowerCase('en-US'))).size !== labels.length)
throw new Error('GitHub returned duplicate issue labels.');
const reactionData = object(issue.reactions, 'GitHub returned invalid issue reactions.');
const positiveReactions = ['+1', 'heart', 'hooray', 'rocket']
.reduce((total, key) => total + count(reactionData[key], `${key} reactions`), 0);
if (!Number.isSafeInteger(positiveReactions)) throw new Error('GitHub returned an invalid positive reaction count.');
const authorAssociation = issue.author_association;
if (typeof authorAssociation !== 'string' || !associations.has(authorAssociation as IssueAuthorAssociation))
throw new Error('GitHub returned an unknown issue author association.');
const association = authorAssociation as IssueAuthorAssociation;
if (!Object.hasOwn(issue, 'user')) throw new Error('GitHub omitted the issue author.');
const authorLogin = issue.user === null
? null
: login(object(issue.user, 'GitHub returned an invalid issue author.').login, 'issue author');
const title = boundedString(issue.title, 'title', 4096);
if (!title.trim()) throw new Error('GitHub returned an empty issue title.');
return {
repository,
number,
title,
body: boundedString(issue.body, 'body', MAX_BODY_LENGTH, true),
url,
createdAt,
updatedAt,
comments: count(issue.comments, 'comment count'),
positiveReactions,
labels,
authorLogin,
authorAssociation: association,
trust: 'requires-approval',
};
}
/** Read-only GitHub CLI adapter. Issue content is returned only as data. */
export class GhIssueGateway implements IssueGateway {
readonly repository: string;
readonly run: RunGh;
readonly now: () => Date;
constructor(repository: string, run?: RunGh, now: () => Date = () => new Date()) {
if (!repositoryName(repository)) throw new Error('A GitHub repository is required for issue retrieval.');
this.repository = repository;
this.run = run ?? ((args, options) => runWithInput('gh', args, {
maxBuffer: ISSUE_PAGE_MAX_BYTES,
signal: options?.signal,
env: ghEnvironment(),
killGraceMs: ISSUE_KILL_GRACE_MS,
pipeGraceMs: ISSUE_PIPE_GRACE_MS,
}));
this.now = now;
}
async #loadIssues(signal: AbortSignal): Promise<RepositoryIssue[]> {
const issues: RepositoryIssue[] = [];
const numbers = new Set<number>();
for (let page = 1; page <= MAX_PAGES; page++) {
const output = await this.run([
'api', '--method', 'GET', '-H', 'Accept: application/vnd.github+json',
`repos/${this.repository}/issues`, '-f', 'state=open', '-f', `per_page=${PAGE_SIZE}`, '-f', `page=${page}`,
], { signal });
let decoded: unknown;
try { decoded = JSON.parse(output); }
catch { throw new Error('GitHub returned invalid issue JSON.'); }
if (!Array.isArray(decoded)) throw new Error('GitHub returned an invalid issue page.');
if (decoded.length > PAGE_SIZE) throw new Error('GitHub returned an oversized issue page.');
for (const value of decoded) {
const issue = normalizeIssue(this.repository, value);
if (!issue) continue;
if (numbers.has(issue.number)) throw new Error('GitHub returned a duplicate issue.');
numbers.add(issue.number);
issues.push(issue);
}
if (decoded.length < PAGE_SIZE) return issues;
}
throw new Error(`Issue retrieval exceeded the ${MAX_ISSUES}-record safety limit.`);
}
async #loadCollaborators(signal: AbortSignal): Promise<Set<string>> {
const collaborators = new Set<string>();
for (let page = 1; page <= MAX_PAGES; page++) {
const output = await this.run([
'api', '--method', 'GET', '-H', 'Accept: application/vnd.github+json',
`repos/${this.repository}/collaborators`, '-f', 'affiliation=all',
'-f', `per_page=${PAGE_SIZE}`, '-f', `page=${page}`,
], { signal });
let decoded: unknown;
try { decoded = JSON.parse(output); }
catch { throw new Error('GitHub returned invalid collaborator JSON.'); }
if (!Array.isArray(decoded)) throw new Error('GitHub returned an invalid collaborator page.');
if (decoded.length > PAGE_SIZE) throw new Error('GitHub returned an oversized collaborator page.');
for (const value of decoded) {
const author = object(value, 'GitHub returned an invalid collaborator.');
const key = login(author.login, 'collaborator').toLocaleLowerCase('en-US');
if (collaborators.has(key)) throw new Error('GitHub returned a duplicate collaborator.');
collaborators.add(key);
}
if (decoded.length < PAGE_SIZE) return collaborators;
}
throw new Error(`Collaborator retrieval exceeded the ${MAX_COLLABORATORS}-record safety limit.`);
}
async #load(signal: AbortSignal): Promise<RepositoryIssue[]> {
const issues = await this.#loadIssues(signal);
signal.throwIfAborted();
const collaborators = await this.#loadCollaborators(signal);
return issues.map(issue => ({
...issue,
trust: issue.authorLogin !== null && collaborators.has(issue.authorLogin.toLocaleLowerCase('en-US'))
? 'trusted'
: 'requires-approval',
}));
}
async fetch(options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<IssueSnapshot> {
const timeoutMs = options.timeoutMs ?? 12_000;
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30_000) throw new Error('Invalid issue retrieval timeout.');
options.signal?.throwIfAborted();
const controller = new AbortController();
const relay = () => controller.abort(options.signal?.reason);
options.signal?.addEventListener('abort', relay, { once: true });
const timer = setTimeout(() => controller.abort(new Error('Issue retrieval timed out.')), timeoutMs);
try {
const issues = await this.#load(controller.signal);
controller.signal.throwIfAborted();
const retrievedAt = this.now();
if (!Number.isFinite(retrievedAt.getTime())) throw new Error('Issue retrieval clock is invalid.');
return { repository: this.repository, retrievedAt: retrievedAt.toISOString(), issues };
} catch (error) {
if (options.signal?.aborted) throw options.signal.reason;
if (controller.signal.aborted) throw new Error('Issue retrieval timed out.');
throw error;
} finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', relay);
}
}
}