-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathado-rest.ts
More file actions
588 lines (544 loc) · 21.9 KB
/
Copy pathado-rest.ts
File metadata and controls
588 lines (544 loc) · 21.9 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
/**
* Minimal, self-contained Azure DevOps REST client for the deterministic
* executor E2E harness.
*
* Uses the global `fetch` (Node 20+) with Basic auth (empty user + token),
* matching how the `ado-aw` Rust executor authenticates
* (`reqwest ... .basic_auth("", Some(token))`). Endpoints and api-versions are
* chosen to line up with the executors under test so setup/assert/cleanup hit
* the same surfaces the executor writes to.
*
* This is a **test harness** module and does not ship in `ado-script.zip`.
*/
export interface AdoRestOptions {
orgUrl: string;
project: string;
token: string;
log?: (msg: string) => void;
}
interface RequestOptions {
method?: string;
/** JSON body (serialised) unless `rawBody`/`contentType` override it. */
body?: unknown;
/** Raw request body string (used for JSON-Patch payloads). */
rawBody?: string;
contentType?: string;
/** Treat 404 as `undefined` instead of throwing. */
allow404?: boolean;
accept?: string;
/** Extra request headers (e.g. `If-Match` for a conditional wiki PUT). */
headers?: Record<string, string>;
}
export class AdoRest {
private readonly base: string;
private readonly project: string;
private readonly authHeader: string;
private readonly log: (msg: string) => void;
private readonly timeoutMs: number;
constructor(opts: AdoRestOptions) {
this.base = opts.orgUrl.replace(/\/+$/, "");
this.project = opts.project;
this.authHeader = "Basic " + Buffer.from(":" + opts.token).toString("base64");
this.log = opts.log ?? (() => {});
this.timeoutMs = Number(process.env.EXECUTOR_E2E_REST_TIMEOUT_MS) || 30_000;
}
/** Percent-encode a single path segment (project names may contain spaces). */
private static seg(value: string): string {
return encodeURIComponent(value);
}
/**
* Centralised fetch: injects the ADO auth header and a per-request timeout
* (AbortSignal) so a single hung endpoint can never block the whole suite.
* All REST access — including {@link getWikiPage}, which needs the raw
* Response for its ETag — goes through here, so auth stays in one place.
*/
private async authedFetch(
path: string,
init: { method?: string; headers?: Record<string, string>; body?: string } = {},
): Promise<Response> {
const url = path.startsWith("http") ? path : `${this.base}/${path}`;
return fetch(url, {
method: init.method ?? "GET",
headers: { Authorization: this.authHeader, ...init.headers },
body: init.body,
signal: AbortSignal.timeout(this.timeoutMs),
});
}
private async request<T>(path: string, opts: RequestOptions = {}): Promise<T | undefined> {
const headers: Record<string, string> = { Accept: opts.accept ?? "application/json", ...opts.headers };
let body: string | undefined;
if (opts.rawBody !== undefined) {
body = opts.rawBody;
if (opts.contentType) headers["Content-Type"] = opts.contentType;
} else if (opts.body !== undefined) {
body = JSON.stringify(opts.body);
headers["Content-Type"] = opts.contentType ?? "application/json";
}
const res = await this.authedFetch(path, { method: opts.method ?? "GET", headers, body });
if (res.status === 404 && opts.allow404) return undefined;
if (!res.ok) {
const text = await res.text().catch(() => "<no body>");
throw new Error(`ADO ${opts.method ?? "GET"} ${path} -> HTTP ${res.status}: ${text}`);
}
if (res.status === 204) return undefined;
const text = await res.text();
if (!text) return undefined;
const ct = res.headers.get("content-type") ?? "";
if (ct.includes("application/json")) return JSON.parse(text) as T;
// Non-empty, non-JSON body (e.g. an XML/HTML error page) — surface it
// loudly rather than silently casting garbage to T.
throw new Error(
`ADO ${opts.method ?? "GET"} ${path} returned unexpected content-type '${ct}': ${text.slice(0, 200)}`,
);
}
private projPath(rest: string): string {
return `${AdoRest.seg(this.project)}/${rest}`;
}
// ---- Connection / identity -------------------------------------------
/** Resolve the collection host base (org URL trimmed). */
get orgBase(): string {
return this.base;
}
// ---- Work items -------------------------------------------------------
async createWorkItem(
type: string,
fields: Record<string, unknown>,
): Promise<{ id: number }> {
const ops = Object.entries(fields).map(([field, value]) => ({
op: "add",
path: `/fields/${field}`,
value,
}));
const path = this.projPath(`_apis/wit/workitems/$${encodeURIComponent(type)}?api-version=7.1`);
const res = await this.request<{ id: number }>(path, {
method: "POST",
rawBody: JSON.stringify(ops),
contentType: "application/json-patch+json",
});
if (!res) throw new Error("createWorkItem returned no body");
return res;
}
async getWorkItem(id: number): Promise<{ id: number; fields: Record<string, unknown> }> {
const path = this.projPath(`_apis/wit/workitems/${id}?api-version=7.1`);
const res = await this.request<{ id: number; fields: Record<string, unknown> }>(path);
if (!res) throw new Error(`getWorkItem(${id}) returned no body`);
return res;
}
async getWorkItemComments(id: number): Promise<{ text: string; id: number }[]> {
const path = this.projPath(
`_apis/wit/workItems/${id}/comments?api-version=7.1-preview.4`,
);
const res = await this.request<{ comments?: { text: string; id: number }[] }>(path);
return res?.comments ?? [];
}
async getWorkItemRelations(
id: number,
): Promise<{ rel: string; url: string; attributes?: Record<string, unknown> }[]> {
const path = this.projPath(
`_apis/wit/workitems/${id}?$expand=relations&api-version=7.1`,
);
const res = await this.request<{
relations?: { rel: string; url: string; attributes?: Record<string, unknown> }[];
}>(path);
return res?.relations ?? [];
}
/** Delete a work item (moves it to the recycle bin). Best-effort. */
async deleteWorkItem(id: number): Promise<void> {
const path = this.projPath(`_apis/wit/workitems/${id}?api-version=7.1`);
await this.request(path, { method: "DELETE", allow404: true });
}
// ---- Git: repositories, refs, tags -----------------------------------
async getRepository(repo: string): Promise<{ id: string; defaultBranch?: string }> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}?api-version=7.1`,
);
const res = await this.request<{ id: string; defaultBranch?: string }>(path);
if (!res) throw new Error(`repository '${repo}' not found`);
return res;
}
/** Resolve the object id (commit sha) a ref currently points at. */
async getRefObjectId(repo: string, refFilter: string): Promise<string | undefined> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/refs?filter=${encodeURIComponent(refFilter)}&api-version=7.1`,
);
const res = await this.request<{ value?: { name: string; objectId: string }[] }>(path);
// `filter` is a prefix match (heads/main also matches heads/main-foo), so
// select the exact ref by name rather than trusting the first result.
const fullName = `refs/${refFilter}`;
return res?.value?.find((r) => r.name === fullName)?.objectId;
}
/** Delete a ref (branch or tag) by setting its newObjectId to zeros. */
async deleteRef(repo: string, refName: string): Promise<void> {
const oldId = await this.getRefObjectId(repo, refName.replace(/^refs\//, ""));
if (!oldId) return;
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/refs?api-version=7.1`,
);
await this.request(path, {
method: "POST",
body: [
{
name: refName.startsWith("refs/") ? refName : `refs/${refName}`,
oldObjectId: oldId,
newObjectId: "0000000000000000000000000000000000000000",
},
],
allow404: true,
});
}
/**
* Create a branch AND a single commit on it in one Push, adding one file.
* Returns the new commit id. Gives PR scenarios a real diff vs. the base.
*/
async pushAddFileBranch(
repo: string,
branchName: string,
baseCommitId: string,
filePath: string,
content: string,
comment: string,
): Promise<string> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pushes?api-version=7.1`,
);
const res = await this.request<{ commits?: { commitId: string }[] }>(path, {
method: "POST",
body: {
// Creating a NEW branch: oldObjectId must be zeros (the ref does not
// exist yet) and the commit must declare parents:[baseCommitId] so it
// is a child of the base — mirrors the Rust executor's push in
// src/safe_outputs/create_pull_request.rs.
refUpdates: [
{
name: branchName.startsWith("refs/") ? branchName : `refs/heads/${branchName}`,
oldObjectId: "0000000000000000000000000000000000000000",
},
],
commits: [
{
comment,
parents: [baseCommitId],
changes: [
{
changeType: "add",
item: { path: filePath.startsWith("/") ? filePath : `/${filePath}` },
newContent: { content, contentType: "rawtext" },
},
],
},
],
},
});
const commitId = res?.commits?.[0]?.commitId;
if (!commitId) throw new Error("pushAddFileBranch returned no commit id");
return commitId;
}
/**
* Create a NEW branch and a single commit adding one OR MORE files in one
* push. Returns the new commit id.
*
* Prefer this over calling {@link pushAddFileBranch} in a loop: that helper
* always uses new-branch semantics (`oldObjectId` = zeros), so a second call
* against the now-existing branch would be rejected by ADO with a ref
* conflict. Batching every file into a single commit sidesteps that entirely
* and still produces a real diff vs. the base for PR scenarios.
*/
async pushAddFilesBranch(
repo: string,
branchName: string,
baseCommitId: string,
files: Record<string, string>,
comment: string,
): Promise<string> {
const entries = Object.entries(files);
if (entries.length === 0) throw new Error("pushAddFilesBranch requires at least one file");
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pushes?api-version=7.1`,
);
const res = await this.request<{ commits?: { commitId: string }[] }>(path, {
method: "POST",
body: {
refUpdates: [
{
name: branchName.startsWith("refs/") ? branchName : `refs/heads/${branchName}`,
oldObjectId: "0000000000000000000000000000000000000000",
},
],
commits: [
{
comment,
parents: [baseCommitId],
changes: entries.map(([filePath, content]) => ({
changeType: "add",
item: { path: filePath.startsWith("/") ? filePath : `/${filePath}` },
newContent: { content, contentType: "rawtext" },
})),
},
],
},
});
const commitId = res?.commits?.[0]?.commitId;
if (!commitId) throw new Error("pushAddFilesBranch returned no commit id");
return commitId;
}
// ---- Git: pull requests & threads ------------------------------------
async createPullRequest(
repo: string,
sourceRef: string,
targetRef: string,
title: string,
description: string,
isDraft?: boolean,
): Promise<{ pullRequestId: number }> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullrequests?api-version=7.1`,
);
const body: Record<string, unknown> = {
sourceRefName: sourceRef.startsWith("refs/") ? sourceRef : `refs/heads/${sourceRef}`,
targetRefName: targetRef.startsWith("refs/") ? targetRef : `refs/heads/${targetRef}`,
title,
description,
};
if (isDraft !== undefined) body.isDraft = isDraft;
const res = await this.request<{ pullRequestId: number }>(path, {
method: "POST",
body,
});
if (!res) throw new Error("createPullRequest returned no body");
return res;
}
async getPullRequest(
repo: string,
prId: number,
): Promise<{ pullRequestId: number; status: string; title: string; description?: string }> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}?api-version=7.1`,
);
const res = await this.request<{
pullRequestId: number;
status: string;
title: string;
description?: string;
}>(path);
if (!res) throw new Error(`getPullRequest(${prId}) returned no body`);
return res;
}
async createThread(
repo: string,
prId: number,
content: string,
): Promise<{ id: number }> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}/threads?api-version=7.1`,
);
const res = await this.request<{ id: number }>(path, {
method: "POST",
body: { comments: [{ parentCommentId: 0, content, commentType: 1 }], status: 1 },
});
if (!res) throw new Error("createThread returned no body");
return res;
}
async getThread(
repo: string,
prId: number,
threadId: number,
): Promise<{ id: number; status?: string | number; comments?: { id: number; content?: string | null }[] }> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}/threads/${threadId}?api-version=7.1`,
);
const res = await this.request<{
id: number;
status?: string | number;
comments?: { id: number; content?: string | null }[];
}>(path);
if (!res) throw new Error(`getThread(${threadId}) returned no body`);
return res;
}
async listThreads(
repo: string,
prId: number,
): Promise<{ id: number; comments?: { content?: string }[] }[]> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}/threads?api-version=7.1`,
);
const res = await this.request<{ value?: { id: number; comments?: { content?: string }[] }[] }>(
path,
);
return res?.value ?? [];
}
async listReviewers(
repo: string,
prId: number,
): Promise<{ id: string; vote: number; displayName?: string }[]> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}/reviewers?api-version=7.1`,
);
const res = await this.request<{
value?: { id: string; vote: number; displayName?: string }[];
}>(path);
return res?.value ?? [];
}
/** Abandon a PR (status=abandoned). Best-effort cleanup. */
async abandonPullRequest(repo: string, prId: number): Promise<void> {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}?api-version=7.1`,
);
await this.request(path, { method: "PATCH", body: { status: "abandoned" }, allow404: true });
}
/**
* Attach one or more labels (tags) to a PR. ADO's label endpoint takes a
* single `{ name }` per POST, so this loops. Used by the trigger E2E harness
* to exercise the gate's `label_set_match` predicate against real PR labels.
*/
async setPullRequestLabels(repo: string, prId: number, labels: string[]): Promise<void> {
for (const name of labels) {
const path = this.projPath(
`_apis/git/repositories/${AdoRest.seg(repo)}/pullRequests/${prId}/labels?api-version=7.1`,
);
try {
await this.request(path, { method: "POST", body: { name } });
} catch (err) {
// Name the specific label that failed so a partial-attach surfaces as a
// clear setup error rather than a confusing downstream gate mismatch.
const message = err instanceof Error ? err.message : String(err);
throw new Error(`setPullRequestLabels: failed to attach label '${name}' to PR ${prId}: ${message}`);
}
}
}
// ---- Wiki -------------------------------------------------------------
async listWikis(): Promise<{ name: string; id: string; type?: string }[]> {
const path = this.projPath(`_apis/wiki/wikis?api-version=7.1`);
const res = await this.request<{ value?: { name: string; id: string; type?: string }[] }>(
path,
);
return res?.value ?? [];
}
async getWikiPage(
wiki: string,
pagePath: string,
): Promise<{ content?: string; eTag?: string } | undefined> {
const path = this.projPath(
`_apis/wiki/wikis/${AdoRest.seg(wiki)}/pages?path=${encodeURIComponent(pagePath)}&includeContent=true&api-version=7.1`,
);
// Routed through authedFetch (not request()) because we need the raw
// Response to read the ETag; auth + timeout stay centralised.
const res = await this.authedFetch(path, { headers: { Accept: "application/json" } });
if (res.status === 404) return undefined;
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`getWikiPage HTTP ${res.status}: ${text}`);
}
const eTag = res.headers.get("etag") ?? undefined;
const json = (await res.json()) as { content?: string };
return { content: json.content, eTag };
}
/**
* Create or update a wiki page. ADO requires an `If-Match` ETag to overwrite
* an EXISTING page (it returns HTTP 412 for an unconditional PUT to a page
* that already exists); creating a new page must omit `If-Match`. Callers
* updating a page should first {@link getWikiPage} and pass its `eTag`.
*/
async putWikiPage(
wiki: string,
pagePath: string,
content: string,
eTag?: string,
): Promise<void> {
const path = this.projPath(
`_apis/wiki/wikis/${AdoRest.seg(wiki)}/pages?path=${encodeURIComponent(pagePath)}&api-version=7.1`,
);
await this.request(path, {
method: "PUT",
body: { content },
headers: eTag ? { "If-Match": eTag } : undefined,
});
}
async deleteWikiPage(wiki: string, pagePath: string): Promise<void> {
const path = this.projPath(
`_apis/wiki/wikis/${AdoRest.seg(wiki)}/pages?path=${encodeURIComponent(pagePath)}&api-version=7.1`,
);
await this.request(path, { method: "DELETE", allow404: true });
}
// ---- Builds -----------------------------------------------------------
async getBuildTags(buildId: number): Promise<string[]> {
const path = this.projPath(`_apis/build/builds/${buildId}/tags?api-version=7.1`);
const res = await this.request<{ value?: string[] } | string[]>(path);
if (Array.isArray(res)) return res;
return res?.value ?? [];
}
async removeBuildTag(buildId: number, tag: string): Promise<void> {
const path = this.projPath(
`_apis/build/builds/${buildId}/tags/${AdoRest.seg(tag)}?api-version=7.1`,
);
await this.request(path, { method: "DELETE", allow404: true });
}
async getBuild(buildId: number): Promise<{ id: number; status?: string; result?: string }> {
const path = this.projPath(`_apis/build/builds/${buildId}?api-version=7.1`);
const res = await this.request<{ id: number; status?: string; result?: string }>(path);
if (!res) throw new Error(`getBuild(${buildId}) returned no body`);
return res;
}
async cancelBuild(buildId: number): Promise<void> {
const path = this.projPath(`_apis/build/builds/${buildId}?api-version=7.1`);
await this.request(path, { method: "PATCH", body: { status: "cancelling" }, allow404: true });
}
/**
* Queue a new build of a registered definition. `sourceBranch` selects the
* branch to build (used by the trigger E2E harness to point a queued build
* at a PR's source branch so `exec-context-pr-synth` can discover the open
* PR). `templateParameters` supplies the victim pipeline's runtime
* parameters (e.g. the base64 GATE_SPEC / PR_SYNTH_SPEC under test).
*
* Returns the new build id. Note: a build queued via this REST call has
* `Build.Reason = Manual`; the victim relies on the synthetic-PR flag (set
* by `exec-context-pr-synth` from a real open PR) — not the build reason —
* to drive full PR-gate evaluation.
*/
async queueBuild(
definitionId: number,
opts: { sourceBranch?: string; templateParameters?: Record<string, string> } = {},
): Promise<{ id: number }> {
const path = this.projPath(`_apis/build/builds?api-version=7.1`);
const body: Record<string, unknown> = { definition: { id: definitionId } };
if (opts.sourceBranch) {
body.sourceBranch = opts.sourceBranch.startsWith("refs/")
? opts.sourceBranch
: `refs/heads/${opts.sourceBranch}`;
}
if (opts.templateParameters && Object.keys(opts.templateParameters).length > 0) {
body.templateParameters = opts.templateParameters;
}
const res = await this.request<{ id: number }>(path, { method: "POST", body });
if (!res) throw new Error(`queueBuild(${definitionId}) returned no body`);
return res;
}
/**
* Poll a build until it reaches `status === "completed"` (or the timeout
* elapses). Returns the terminal `{ status, result }`. `result` is one of
* `succeeded` | `partiallySucceeded` | `failed` | `canceled`.
*
* Timeout/poll defaults are generic (15 min / 10 s). Callers that need
* suite-specific tuning pass explicit `opts` — env-var knobs belong in the
* caller, not this shared client.
*/
async waitForBuild(
buildId: number,
opts: { timeoutMs?: number; pollMs?: number } = {},
): Promise<{ status: string; result?: string }> {
const timeoutMs = opts.timeoutMs ?? 900_000;
const pollMs = opts.pollMs ?? 10_000;
const deadline = Date.now() + timeoutMs;
for (;;) {
const build = await this.getBuild(buildId);
if (build.status === "completed") {
return { status: build.status, result: build.result };
}
if (Date.now() >= deadline) {
throw new Error(
`waitForBuild(${buildId}) timed out after ${timeoutMs}ms (last status='${build.status ?? "?"}')`,
);
}
await new Promise((r) => setTimeout(r, pollMs));
}
}
}