-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepository-directory.ts
More file actions
324 lines (294 loc) · 11.6 KB
/
Copy pathrepository-directory.ts
File metadata and controls
324 lines (294 loc) · 11.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
import type { WorkflowRepositoryScope } from "@shared/contracts";
import type { VcsConfig, VcsProviderConfig } from "../../../env.js";
import { buildOctokit } from "../../lib/github-auth.js";
const GITLAB_PROJECTS_TIMEOUT_MS = 18_000;
// A few bounded retries with jittered exponential backoff. A provider's 5xx or
// timeout is usually gone within a couple of calls, while the pre-sandbox step
// that owns this listing runs under a 60s budget: a longer ladder would spend
// that budget hanging instead of failing with a reason an operator can act on.
// Worst case is 3 * 18s + <=1.5s of backoff ~= 55.5s, which stays inside that
// budget while surviving a GitLab hiccup that outlasts a single 18s window.
const LISTING_MAX_ATTEMPTS = 3;
const LISTING_RETRY_BASE_DELAY_MS = 500;
const LISTING_RETRY_MAX_DELAY_MS = 4_000;
/** Jittered exponential backoff between listing attempts: after the nth attempt
* fails the next wait is a random span in [0, base * 2^(n-1)] capped at
* LISTING_RETRY_MAX_DELAY_MS. Full jitter de-correlates retries that a shared
* upstream blip fired at once, and the cap keeps the ladder inside the budget. */
function listingRetryDelayMs(failedAttempt: number): number {
const ceiling = Math.min(
LISTING_RETRY_MAX_DELAY_MS,
LISTING_RETRY_BASE_DELAY_MS * 2 ** (failedAttempt - 1),
);
return Math.floor(Math.random() * ceiling);
}
export type VcsProvider = "github" | "gitlab";
export interface RepositoryMetadata {
provider: VcsProvider;
repoPath: string;
name: string;
owner: string;
defaultBranch: string;
description: string;
webUrl: string;
topics: string[];
archived: boolean;
private: boolean;
}
export interface RepositoryDirectory {
listRepositories(): Promise<RepositoryMetadata[]>;
}
export function createRepositoryDirectory(vcs: VcsProviderConfig | VcsConfig): RepositoryDirectory {
if (vcs.kind === "github") return new GitHubRepositoryDirectory(vcs.auth);
return new GitLabRepositoryDirectory(vcs.token, vcs.host);
}
export function createRepositoryDirectoryForProviders(
providers: VcsProviderConfig[],
): RepositoryDirectory {
return {
async listRepositories() {
const { repositories, failures } = await listRepositoriesAcrossProviders(providers);
// Callers of this directory have no partial-catalog contract, so a provider
// that never answered stays terminal for them exactly as before, with its
// own error rather than a wrapper.
if (failures.length > 0) throw failures[0]!.error;
return repositories;
},
};
}
export interface RepositoryListingFailure {
provider: VcsProvider;
message: string;
error: unknown;
}
/**
* Fan out over the configured providers and report what each one did, so a caller
* that can reason about a partial catalog gets the surviving listings plus the
* providers that failed instead of a single rejection standing in for all of them.
* Each provider's listing is retried under a bounded policy first.
*
* Latency budget for whoever tunes GITLAB_PROJECTS_TIMEOUT_MS next: the ladder
* of up to 3 attempts triples the worst case, so a hung provider costs about 55s
* here rather than 18s, for every caller including the dashboard catalog endpoint.
* allSettled also means the slowest provider sets the floor: a fast 401 next to a
* hung provider now surfaces at the hung provider's pace instead of immediately.
*/
export async function listRepositoriesAcrossProviders(
providers: VcsProviderConfig[],
): Promise<{
repositories: RepositoryMetadata[];
failures: RepositoryListingFailure[];
}> {
const settled = await Promise.allSettled(
providers.map((provider) => listRepositoriesWithRetry(provider)),
);
const repositories: RepositoryMetadata[] = [];
const failures: RepositoryListingFailure[] = [];
settled.forEach((result, index) => {
if (result.status === "fulfilled") {
repositories.push(...result.value);
return;
}
failures.push({
provider: providers[index]!.kind,
message: listingErrorMessage(result.reason),
error: result.reason,
});
});
return { repositories, failures };
}
async function listRepositoriesWithRetry(
provider: VcsProviderConfig,
): Promise<RepositoryMetadata[]> {
const directory = createRepositoryDirectory(provider);
let lastError: unknown;
for (let attempt = 1; attempt <= LISTING_MAX_ATTEMPTS; attempt++) {
try {
return await directory.listRepositories();
} catch (err) {
lastError = err;
if (attempt >= LISTING_MAX_ATTEMPTS || !isTransientListingError(err)) break;
await new Promise((resolve) => setTimeout(resolve, listingRetryDelayMs(attempt)));
}
}
throw lastError;
}
/** Retry only what the provider can recover from without us changing anything: a
* timeout or a 5xx. A 401 or 403 is a credential the retry would replay
* unchanged, and every other 4xx is a request this code will keep sending. */
function isTransientListingError(err: unknown): boolean {
if (isAbortError(err)) return true;
if (typeof err !== "object" || err === null) return false;
if ((err as { timedOut?: unknown }).timedOut === true) return true;
const status = (err as { status?: unknown }).status;
return typeof status === "number" && status >= 500 && status < 600;
}
function listingErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
class RepositoryListingError extends Error {
readonly status: number | undefined;
readonly timedOut: boolean;
constructor(message: string, detail: { status?: number; timedOut?: boolean } = {}) {
super(message);
this.name = "RepositoryListingError";
this.status = detail.status;
this.timedOut = detail.timedOut ?? false;
}
}
/**
* Intersect a repository listing with the repositories pinned to a workflow
* definition. Composes AFTER filterAllowedRepositories and can only remove
* entries the server already offered: it never fetches, never builds a path, and
* never re-admits an entry the allowlist dropped, so a pin can never widen
* access. An absent or fully empty scope returns the input untouched, which is
* what keeps a workflow without a pin on exactly its pre-pin behavior.
*/
export function filterPinnedRepositories<
T extends { provider: VcsProvider; repoPath: string },
>(repositories: T[], scope: WorkflowRepositoryScope | undefined): T[] {
const providers = scope?.providers ?? [];
const pinned = scope?.repositories ?? [];
let filtered = repositories;
if (providers.length > 0) {
filtered = filtered.filter((repository) => providers.includes(repository.provider));
}
if (pinned.length > 0) {
const keys = new Set(pinned.map(pinnedRepositoryKey));
filtered = filtered.filter((repository) => keys.has(pinnedRepositoryKey(repository)));
}
return filtered;
}
/**
* Whether the pin already excludes every repository a provider could offer, so
* that provider's catalog cannot change what this run selects. Derived from the
* same intersection filter, so it can never drift from it. The provider narrowing
* in pre-sandbox/steps/repo-selection.ts keeps a provider-pinned run from even
* querying an excluded provider; this answers the case that narrowing leaves
* behind, a pin that names repositories without naming providers, where every
* provider is still queried but only the named ones can survive the filter.
*/
export function pinnedScopeExcludesProvider(
scope: WorkflowRepositoryScope | undefined,
provider: VcsProvider,
): boolean {
const providers = scope?.providers ?? [];
const pinned = scope?.repositories ?? [];
if (providers.length === 0 && pinned.length === 0) return false;
if (pinned.length > 0) {
return !filterPinnedRepositories(pinned, scope).some(
(repository) => repository.provider === provider,
);
}
return !providers.includes(provider);
}
/** Whether one repository identity survives the pin. Derived from the filter so
* trigger admission and repository selection can never drift apart. */
export function isRepositoryWithinPinnedScope(
scope: WorkflowRepositoryScope | undefined,
repository: { provider: VcsProvider; repoPath: string },
): boolean {
return filterPinnedRepositories([repository], scope).length === 1;
}
/** A pinned repoPath is stored in the case the operator picked, so every
* comparison lowercases it, exactly like repositoryKey in
* pre-sandbox/steps/repo-selection.ts and repositoryCatalogKey. */
function pinnedRepositoryKey(repository: {
provider: VcsProvider;
repoPath: string;
}): string {
return `${repository.provider}:${repository.repoPath.toLowerCase()}`;
}
class GitHubRepositoryDirectory implements RepositoryDirectory {
constructor(private auth: Extract<VcsProviderConfig | VcsConfig, { kind: "github" }>["auth"]) {}
async listRepositories(): Promise<RepositoryMetadata[]> {
const octokit = buildOctokit(this.auth) as any;
const repositories = await octokit.paginate(
octokit.apps.listReposAccessibleToInstallation,
{ per_page: 100 },
);
return repositories.map((repo: any) => ({
provider: "github" as const,
repoPath: repo.full_name,
name: repo.name,
owner: repo.owner?.login ?? repo.full_name.split("/")[0],
defaultBranch: repo.default_branch ?? "",
description: repo.description ?? "",
webUrl: repo.html_url,
topics: repo.topics ?? [],
archived: Boolean(repo.archived),
private: Boolean(repo.private),
}));
}
}
class GitLabRepositoryDirectory implements RepositoryDirectory {
constructor(
private token: string,
private host: string,
) {}
async listRepositories(): Promise<RepositoryMetadata[]> {
const projects: any[] = [];
let page = "1";
const baseUrl = this.host.replace(/\/$/, "");
while (page) {
const url = `${baseUrl}/api/v4/projects?membership=true&simple=true&per_page=100&page=${page}`;
const response = await fetch(url, {
headers: { "PRIVATE-TOKEN": this.token },
signal: AbortSignal.timeout(GITLAB_PROJECTS_TIMEOUT_MS),
}).catch((err) => {
if (isAbortError(err)) {
throw new RepositoryListingError(
`GitLab projects list timed out after ${GITLAB_PROJECTS_TIMEOUT_MS}ms`,
{ timedOut: true },
);
}
throw err;
});
if (!response.ok) {
throw new RepositoryListingError(
`GitLab projects list failed: ${response.status} ${response.statusText}`,
{ status: response.status },
);
}
projects.push(...await response.json());
page = response.headers.get("x-next-page") ?? "";
}
return projects.map((project) => ({
provider: "gitlab" as const,
repoPath: project.path_with_namespace,
name: project.name,
owner: project.namespace?.full_path ?? project.path_with_namespace.split("/")[0],
defaultBranch: project.default_branch ?? "",
description: project.description ?? "",
webUrl: project.web_url,
topics: project.topics ?? project.tag_list ?? [],
archived: Boolean(project.archived),
private: project.visibility !== "public",
}));
}
}
function isAbortError(err: unknown): boolean {
return err instanceof DOMException && (err.name === "AbortError" || err.name === "TimeoutError");
}
export interface WorkflowOwnedBranch {
branchName: string;
pr?: {
id: number;
url: string;
branch: string;
};
}
export interface SelectedRepository {
provider: VcsProvider;
repoPath: string;
defaultBranch: string;
selectedRationale: string;
workflowOwnedBranch?: WorkflowOwnedBranch;
/** PR context for a read-only sibling checkout. It never grants write scope. */
reviewPullRequest?: {
id: number;
url: string;
branch: string;
headSha?: string;
};
}