-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathrunBuilds.ts
More file actions
455 lines (413 loc) · 12.1 KB
/
runBuilds.ts
File metadata and controls
455 lines (413 loc) · 12.1 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
import { createPatch, applyPatch } from "diff";
import { Stainless } from "@stainless-api/sdk";
import { logger } from "./logger";
import { categorizeOutcome, type Outcomes } from "./outcomes";
import { addBuildIdForTelemetry } from "./wrapAction";
type Build = Stainless.Builds.Build;
const POLLING_INTERVAL_SECONDS = 5;
const MAX_POLLING_SECONDS = 10 * 60; // 10 minutes
export type RunResult = {
baseOutcomes: Outcomes | null;
outcomes: Outcomes;
documentedSpec: string | null;
};
export async function* runBuilds({
stainless,
projectName,
baseBranch,
mergeBranch,
branch,
branchFrom,
oasContent,
configContent,
baseOasContent,
baseConfigContent,
guessConfig = false,
commitMessage,
targetCommitMessages,
allowEmpty = true,
}: {
stainless: Stainless;
projectName: string;
baseBranch?: string;
mergeBranch?: string;
branch: string;
branchFrom?: string;
oasContent?: string;
configContent?: string;
baseOasContent?: string;
baseConfigContent?: string;
guessConfig?: boolean;
commitMessage?: string;
targetCommitMessages?: Record<string, string>;
allowEmpty?: boolean;
}): AsyncGenerator<RunResult> {
if (mergeBranch && (oasContent || configContent)) {
throw new Error(
"Cannot specify both merge_branch and oas_path or config_path",
);
}
if (guessConfig && (configContent || !oasContent)) {
throw new Error(
"If guess_config is true, must have oas_path and no config_path",
);
}
if (branchFrom && mergeBranch) {
throw new Error("Cannot specify both branch_from and merge_branch");
}
if (!branchFrom) {
const build = await stainless.builds.create(
{
project: projectName,
revision: mergeBranch
? `${branch}..${mergeBranch}`
: {
...(oasContent && {
"openapi.yml": {
content: oasContent,
},
}),
...(configContent && {
"openapi.stainless.yml": {
content: configContent,
},
}),
},
branch,
commit_message: commitMessage,
target_commit_messages: targetCommitMessages,
allow_empty: allowEmpty,
},
{
// For very large specs, writing the config files can take a while.
timeout: 3 * 60 * 1000,
},
);
for await (const { outcomes, documentedSpec } of pollBuild({
stainless,
build,
label: "head",
})) {
yield {
baseOutcomes: null,
outcomes,
documentedSpec,
};
}
return;
}
let configPatch: string | undefined;
if (!configContent) {
const hasBranch =
!!branch &&
!!(await stainless.projects.branches.retrieve(branch).catch(() => null));
const hasBaseBranch =
!!baseBranch &&
!!(await stainless.projects.branches
.retrieve(baseBranch)
.catch(() => null));
if (guessConfig) {
logger.debug("Guessing config before branch reset");
// If the `branch` already exists, we should guess against it, in case
// there were changes made via the studio.
try {
if (hasBranch) {
configContent = Object.values(
await stainless.projects.configs.guess({
branch,
spec: oasContent!,
}),
)[0]?.content;
} else {
configContent = Object.values(
await stainless.projects.configs.guess({
branch: branchFrom,
spec: oasContent!,
}),
)[0]?.content;
}
} catch (e) {
logger.warn("Error guessing config, continuing anyways", e);
}
} else if (hasBranch && hasBaseBranch) {
logger.debug("Computing config patch before branch reset");
const oldBaseConfig =
Object.values(
await stainless.projects.configs.retrieve({
branch: baseBranch,
}),
)[0]?.content ?? "";
const oldHeadConfig =
Object.values(
await stainless.projects.configs.retrieve({
branch,
}),
)[0]?.content ?? "";
if (oldBaseConfig !== oldHeadConfig) {
configPatch = createPatch(
"openapi.stainless.yml",
oldBaseConfig,
oldHeadConfig,
);
logger.debug("Created config patch");
}
} else if (hasBranch) {
logger.debug("No base branch found, skipping config patch");
} else {
logger.debug("No existing branch found");
}
}
logger.info(`Hard resetting ${branch} and ${baseBranch} to ${branchFrom}`);
const { config_commit } = await stainless.projects.branches.create({
branch_from: branchFrom,
branch: branch!,
force: true,
});
logger.debug(`Hard reset ${branch}, now at ${config_commit.sha}`);
const { config_commit: base_config_commit } =
await stainless.projects.branches.create({
branch_from: branchFrom,
branch: baseBranch!,
force: true,
});
logger.debug(`Hard reset ${baseBranch}, now at ${base_config_commit.sha}`);
// Apply config patch if we computed one earlier
if (configPatch && !configContent) {
logger.debug("Applying config patch to new base");
const newBaseConfig =
Object.values(
await stainless.projects.configs.retrieve({
branch,
}),
)[0]?.content ?? "";
const patchedConfig = applyPatch(newBaseConfig, configPatch);
if (patchedConfig === false) {
logger.warn("Config patch failed to apply, dropping customizations");
} else {
logger.debug("Config patch applied successfully");
configContent = patchedConfig;
}
}
const { base, head } = await stainless.builds.compare(
{
base: {
revision: {
...(baseOasContent && {
"openapi.yml": {
content: baseOasContent,
},
}),
...(baseConfigContent && {
"openapi.stainless.yml": {
content: baseConfigContent,
},
}),
},
branch: baseBranch!,
commit_message: commitMessage,
},
head: {
revision: {
...(oasContent && {
"openapi.yml": {
content: oasContent,
},
}),
...(configContent && {
"openapi.stainless.yml": {
content: configContent,
},
}),
},
branch,
commit_message: commitMessage,
},
},
{
// For very large specs, writing the config files can take a while.
timeout: 3 * 60 * 1000,
},
);
let lastBaseOutcome: Outcomes | null = null;
let lastOutcome: Outcomes | null = null;
let lastDocumentedSpec: string | null = null;
for await (const { index, value } of combineAsyncIterators(
pollBuild({ stainless, build: base, label: "base" }),
pollBuild({ stainless, build: head, label: "head" }),
)) {
if (index === 0) {
lastBaseOutcome = value.outcomes;
} else {
lastOutcome = value.outcomes;
lastDocumentedSpec = value.documentedSpec;
}
if (lastOutcome) {
yield {
baseOutcomes: lastBaseOutcome,
outcomes: lastOutcome,
documentedSpec: lastDocumentedSpec,
};
}
}
return;
}
const combineAsyncIterators = async function* <T>(
...args: AsyncIterable<T>[]
): AsyncGenerator<{ index: number; value: T }> {
const iters = Array.from(args, (o) => o[Symbol.asyncIterator]());
let count = iters.length;
const never = new Promise<never>(() => {
// never resolve
});
const next = (iter: AsyncIterator<T>, index: number) =>
iter.next().then((result) => ({ index, result }));
const results = iters.map(next);
while (count) {
const { index, result } = await Promise.race(results);
if (result.done) {
results[index] = never;
count--;
} else {
results[index] = next(iters[index], index);
yield { index, value: result.value };
}
}
};
async function* pollBuild({
stainless,
build,
label,
pollingIntervalSeconds = POLLING_INTERVAL_SECONDS,
maxPollingSeconds = MAX_POLLING_SECONDS,
}: {
stainless: Stainless;
build: Build;
label: "base" | "head";
pollingIntervalSeconds?: number;
maxPollingSeconds?: number;
}): AsyncGenerator<{
outcomes: Outcomes;
documentedSpec: string | null;
}> {
const log = logger.child(label);
let documentedSpec: string | null = null;
const buildId = build.id;
const languages = Object.keys(build.targets) as Array<
keyof typeof build.targets
>;
const outcomes: Outcomes = Object.fromEntries(
languages.map((lang) => [
lang,
{ ...build.targets[lang]!, commit: null, diagnostics: [] },
]),
);
if (buildId) {
log.info(
`Created build ${buildId} against ${build.config_commit} for languages: ${languages.join(", ")}`,
);
addBuildIdForTelemetry(buildId);
} else {
logger.info("No new build was created; exiting.");
yield { outcomes, documentedSpec };
return;
}
const pollingStart = Date.now();
while (
(Object.values(outcomes).length < languages.length ||
Object.values(outcomes).some(
(outcome) => categorizeOutcome({ outcome }).isPending,
)) &&
Date.now() - pollingStart < maxPollingSeconds * 1000
) {
let hasChange = false;
const build = await stainless.builds.retrieve(buildId);
for (const language of languages) {
const existing = outcomes[language]!;
const buildOutput = build.targets[language]!;
outcomes[language] = {
...buildOutput,
commit: existing.commit,
diagnostics: existing.diagnostics,
};
if (!existing?.status || existing.status !== buildOutput.status) {
hasChange = true;
log.info(`Build for ${language} has status ${buildOutput.status}`);
}
// Also has a change if any of the checks have changed:
for (const step of ["build", "lint", "test"] as const) {
if (
!existing?.[step] ||
existing[step]?.status !== buildOutput[step]?.status
) {
hasChange = true;
}
}
if (
existing?.commit?.status !== "completed" &&
buildOutput.commit.status === "completed"
) {
log.debug(`Build for ${language} completed`, buildOutput);
// This is the only time we modify `commit` and `diagnostics`.
outcomes[language].commit = buildOutput.commit;
outcomes[language].diagnostics = [];
try {
for await (const diagnostic of stainless.builds.diagnostics.list(
buildId,
{ targets: language },
)) {
outcomes[language].diagnostics.push(diagnostic);
}
} catch (e) {
log.warn("Error getting diagnostics, continuing anyway", e);
}
}
}
if (!documentedSpec && build.documented_spec) {
hasChange = true;
documentedSpec = await Stainless.unwrapFile(build.documented_spec);
}
if (hasChange) {
yield { outcomes, documentedSpec };
}
// wait a bit before polling again
await new Promise((resolve) =>
setTimeout(resolve, pollingIntervalSeconds * 1000),
);
}
const languagesWithoutOutcome = languages.filter(
(language) =>
!outcomes[language] ||
categorizeOutcome({ outcome: outcomes[language]! }).isPending,
);
for (const language of languagesWithoutOutcome) {
log.warn(`Build for ${language} timed out after ${maxPollingSeconds}s`);
const now = new Date().toISOString();
outcomes[language] = {
object: "build_target",
status: "completed",
lint: {
status: "not_started",
},
test: {
status: "not_started",
},
commit: {
status: "completed",
conclusion: "timed_out",
commit: null,
merge_conflict_pr: null,
completed_at: now,
completed: {
conclusion: "timed_out",
commit: null,
merge_conflict_pr: null,
completed_at: now,
},
},
install_url: null,
diagnostics: [],
...(outcomes[language] as Outcomes[string] | undefined),
};
}
return { outcomes, documentedSpec };
}