generated from actions/typescript-action
-
Notifications
You must be signed in to change notification settings - Fork 9
/
api.ts
278 lines (241 loc) · 7.45 KB
/
api.ts
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
import * as core from "@actions/core";
import * as github from "@actions/github";
import { type ActionConfig, getConfig } from "./action.ts";
type Octokit = ReturnType<(typeof github)["getOctokit"]>;
let config: ActionConfig;
let octokit: Octokit;
export enum WorkflowRunStatus {
Queued = "queued",
InProgress = "in_progress",
Completed = "completed",
}
export enum WorkflowRunConclusion {
Success = "success",
Failure = "failure",
Neutral = "neutral",
Cancelled = "cancelled",
Skipped = "skipped",
TimedOut = "timed_out",
ActionRequired = "action_required",
}
export function init(cfg?: ActionConfig): void {
config = cfg ?? getConfig();
octokit = github.getOctokit(config.token);
}
export interface WorkflowRunState {
status: WorkflowRunStatus | null;
conclusion: WorkflowRunConclusion | null;
}
export async function getWorkflowRunState(
runId: number,
): Promise<WorkflowRunState> {
try {
// https://docs.github.com/en/rest/reference/actions#get-a-workflow-run
const response = await octokit.rest.actions.getWorkflowRun({
owner: config.owner,
repo: config.repo,
run_id: runId,
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to get Workflow Run state, expected 200 but received ${response.status}`,
);
}
core.debug(
`Fetched Run:\n` +
` Repository: ${config.owner}/${config.repo}\n` +
` Run ID: ${runId}\n` +
` Status: ${response.data.status}\n` +
` Conclusion: ${response.data.conclusion}`,
);
return {
status: response.data.status as WorkflowRunStatus | null,
conclusion: response.data.conclusion as WorkflowRunConclusion | null,
};
} catch (error) {
if (error instanceof Error) {
core.error(
`getWorkflowRunState: An unexpected error has occurred: ${error.message}`,
);
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
error.stack && core.debug(error.stack);
}
throw error;
}
}
export interface WorkflowRunJob {
id: number;
name: string;
status: "queued" | "in_progress" | "completed" | "waiting";
conclusion: string | null;
steps: WorkflowRunJobStep[];
url: string | null;
}
export interface WorkflowRunJobStep {
name: string;
status: string;
conclusion: string | null;
number: number;
}
type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;
type ListJobsForWorkflowRunResponse = Awaited<
ReturnType<Octokit["rest"]["actions"]["listJobsForWorkflowRun"]>
>;
async function getWorkflowRunJobs(
runId: number,
): Promise<ListJobsForWorkflowRunResponse> {
// https://docs.github.com/en/rest/reference/actions#list-jobs-for-a-workflow-run
const response = await octokit.rest.actions.listJobsForWorkflowRun({
owner: config.owner,
repo: config.repo,
run_id: runId,
filter: "latest",
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to get Jobs for Workflow Run, expected 200 but received ${response.status}`,
);
}
return response;
}
export async function getWorkflowRunFailedJobs(
runId: number,
): Promise<WorkflowRunJob[]> {
try {
const response = await getWorkflowRunJobs(runId);
const fetchedFailedJobs = response.data.jobs.filter(
(job) => job.conclusion === "failure",
);
if (fetchedFailedJobs.length <= 0) {
core.warning(`Failed to find failed Jobs for Workflow Run ${runId}`);
return [];
}
const jobs: WorkflowRunJob[] = fetchedFailedJobs.map((job) => {
const steps = job.steps?.map((step) => ({
name: step.name,
status: step.status,
conclusion: step.conclusion,
number: step.number,
}));
return {
id: job.id,
name: job.name,
status: job.status,
conclusion: job.conclusion,
steps: steps ?? [],
url: job.html_url,
};
});
const runJobs = jobs.map((job) => job.name);
core.debug(
`Fetched Jobs for Run:\n` +
` Repository: ${config.owner}/${config.repo}\n` +
` Run ID: ${config.runId}\n` +
` Jobs: [${runJobs.join(", ")}]`,
);
for (const job of jobs) {
const steps = job.steps.map((step) => `${step.number}: ${step.name}`);
core.debug(
` Job: ${job.name}\n` +
` ID: ${job.id}\n` +
` Status: ${job.status}\n` +
` Conclusion: ${job.conclusion}\n` +
` Steps: [${steps.join(", ")}]`,
);
}
return jobs;
} catch (error) {
if (error instanceof Error) {
core.error(
`getWorkflowRunJobFailures: An unexpected error has occurred: ${error.message}`,
);
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
error.stack && core.debug(error.stack);
}
throw error;
}
}
export async function getWorkflowRunActiveJobUrl(
runId: number,
): Promise<string | undefined> {
try {
const response = await getWorkflowRunJobs(runId);
const fetchedInProgressJobs = response.data.jobs.filter(
(job) => job.status === "in_progress" || job.status === "completed",
);
const inProgressJobs = fetchedInProgressJobs.map(
(job) => `${job.name} (${job.status})`,
);
core.debug(
`Fetched Jobs for Run:\n` +
` Repository: ${config.owner}/${config.repo}\n` +
` Run ID: ${config.runId}\n` +
` Jobs: [${inProgressJobs.join(", ")}]`,
);
if (fetchedInProgressJobs.length <= 0) {
return undefined;
}
return (
fetchedInProgressJobs[0]?.html_url ?? "GitHub failed to return the URL"
);
} catch (error) {
if (error instanceof Error) {
core.error(
`getWorkflowRunActiveJobUrl: An unexpected error has occurred: ${error.message}`,
);
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
error.stack && core.debug(error.stack);
}
throw error;
}
}
export async function getWorkflowRunActiveJobUrlRetry(
runId: number,
timeout: number,
): Promise<string> {
const startTime = Date.now();
let elapsedTime = Date.now() - startTime;
while (elapsedTime < timeout) {
elapsedTime = Date.now() - startTime;
core.debug(
`No 'in_progress' or 'completed' Jobs found for Workflow Run ${runId}, retrying...`,
);
const url = await getWorkflowRunActiveJobUrl(runId);
if (url) {
return url;
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
core.debug(`Timed out while trying to fetch URL for Workflow Run ${runId}`);
return "Unable to fetch URL";
}
export async function retryOnError<T>(
func: () => Promise<T>,
name: string,
timeout = 5000,
): Promise<T> {
const startTime = Date.now();
let elapsedTime = Date.now() - startTime;
while (elapsedTime < timeout) {
elapsedTime = Date.now() - startTime;
try {
return await func();
} catch (error) {
if (error instanceof Error) {
// We now exceed the time, so throw the error up
if (Date.now() - startTime >= timeout) {
throw error;
}
core.warning(
"retryOnError: An unexpected error has occurred:\n" +
` name: ${name}\n` +
` error: ${error.message}`,
);
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
throw new Error(`Timeout exceeded while attempting to retry ${name}`);
}