forked from patrickedqvist/wait-for-vercel-preview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction.js
377 lines (316 loc) · 9.03 KB
/
action.js
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
// @ts-check
// Dependencies are compiled using https://github.com/vercel/ncc
const core = require('@actions/core');
const github = require('@actions/github');
const axios = require('axios');
const setCookieParser = require('set-cookie-parser');
const calculateIterations = (maxTimeoutSec, checkIntervalInMilliseconds) =>
Math.floor(maxTimeoutSec / (checkIntervalInMilliseconds / 1000));
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const waitForUrl = async ({
url,
maxTimeout,
checkIntervalInMilliseconds,
vercelPassword,
path,
}) => {
const iterations = calculateIterations(
maxTimeout,
checkIntervalInMilliseconds
);
for (let i = 0; i < iterations; i++) {
try {
let headers = {};
if (vercelPassword) {
const jwt = await getPassword({
url,
vercelPassword,
});
headers = {
Cookie: `_vercel_jwt=${jwt}`,
};
core.setOutput('vercel_jwt', jwt);
}
let checkUri = new URL(path, url);
await axios.get(checkUri.toString(), {
headers,
});
console.log('Received success status code');
return;
} catch (e) {
// https://axios-http.com/docs/handling_errors
if (e.response) {
console.log(
`GET status: ${e.response.status}. Attempt ${i} of ${iterations}`
);
} else if (e.request) {
console.log(
`GET error. A request was made, but no response was received. Attempt ${i} of ${iterations}`
);
console.log(e.message);
} else {
console.log(e);
}
await wait(checkIntervalInMilliseconds);
}
}
core.setFailed(`Timeout reached: Unable to connect to ${url}`);
};
/**
* See https://vercel.com/docs/errors#errors/bypassing-password-protection-programmatically
* @param {{url: string; vercelPassword: string }} options vercel password options
* @returns {Promise<string>}
*/
const getPassword = async ({ url, vercelPassword }) => {
console.log('requesting vercel JWT');
const data = new URLSearchParams();
data.append('_vercel_password', vercelPassword);
const response = await axios({
url,
method: 'post',
data: data.toString(),
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
maxRedirects: 0,
validateStatus: (status) => {
// Vercel returns 303 with the _vercel_jwt
return status >= 200 && status < 307;
},
});
const setCookieHeader = response.headers['set-cookie'];
if (!setCookieHeader) {
throw new Error('no vercel JWT in response');
}
const cookies = setCookieParser(setCookieHeader);
const vercelJwtCookie = cookies.find(
(cookie) => cookie.name === '_vercel_jwt'
);
if (!vercelJwtCookie || !vercelJwtCookie.value) {
throw new Error('no vercel JWT in response');
}
console.log('received vercel JWT');
return vercelJwtCookie.value;
};
const waitForStatus = async ({
token,
owner,
repo,
deployment_id,
maxTimeout,
allowInactive,
checkIntervalInMilliseconds,
}) => {
const octokit = new github.getOctokit(token);
const iterations = calculateIterations(
maxTimeout,
checkIntervalInMilliseconds
);
for (let i = 0; i < iterations; i++) {
try {
const statuses = await octokit.rest.repos.listDeploymentStatuses({
owner,
repo,
deployment_id,
});
const status = statuses.data.length > 0 && statuses.data[0];
if (!status) {
throw new StatusError('No status was available');
}
if (status && allowInactive === true && status.state === 'inactive') {
return status;
}
if (status && status.state !== 'success') {
throw new StatusError('No status with state "success" was available');
}
if (status && status.state === 'success') {
return status;
}
throw new StatusError('Unknown status error');
} catch (e) {
console.log(
`Deployment unavailable or not successful, retrying (attempt ${
i + 1
} / ${iterations})`
);
if (e instanceof StatusError) {
if (e.message.includes('No status with state "success"')) {
// TODO: does anything actually need to be logged in this case?
} else {
console.log(e.message);
}
} else {
console.log(e);
}
await wait(checkIntervalInMilliseconds);
}
}
core.setFailed(
`Timeout reached: Unable to wait for an deployment to be successful`
);
};
class StatusError extends Error {
constructor(message) {
super(message);
}
}
/**
* Waits until the github API returns a deployment for
* a given actor.
*
* Accounts for race conditions where this action starts
* before the actor's action has started.
*
* @returns
*/
const waitForDeploymentToStart = async ({
octokit,
owner,
repo,
sha,
environment,
actorName = 'vercel[bot]',
maxTimeout = 20,
checkIntervalInMilliseconds = 2000,
}) => {
const iterations = calculateIterations(
maxTimeout,
checkIntervalInMilliseconds
);
for (let i = 0; i < iterations; i++) {
try {
const deployments = await octokit.rest.repos.listDeployments({
owner,
repo,
sha,
environment,
});
const deployment =
deployments.data.length > 0 &&
deployments.data.find((deployment) => {
return deployment.creator.login === actorName;
});
if (deployment) {
return deployment;
}
console.log(
`Could not find any deployments for actor ${actorName}, retrying (attempt ${
i + 1
} / ${iterations})`
);
} catch(e) {
console.log(
`Error while fetching deployments, retrying (attempt ${
i + 1
} / ${iterations})`
);
console.error(e)
}
await wait(checkIntervalInMilliseconds);
}
return null;
};
async function getShaForPullRequest({ octokit, owner, repo, number }) {
const PR_NUMBER = github.context.payload.pull_request.number;
if (!PR_NUMBER) {
core.setFailed('No pull request number was found');
return;
}
// Get information about the pull request
const currentPR = await octokit.rest.pulls.get({
owner,
repo,
pull_number: PR_NUMBER,
});
if (currentPR.status !== 200) {
core.setFailed('Could not get information about the current pull request');
return;
}
// Get Ref from pull request
const prSHA = currentPR.data.head.sha;
return prSHA;
}
const run = async () => {
try {
// Inputs
const GITHUB_TOKEN = core.getInput('token', { required: true });
const VERCEL_PASSWORD = core.getInput('vercel_password');
const ENVIRONMENT = core.getInput('environment');
const MAX_TIMEOUT = Number(core.getInput('max_timeout')) || 60;
const ALLOW_INACTIVE = Boolean(core.getInput('allow_inactive')) || false;
const PATH = core.getInput('path') || '/';
const CHECK_INTERVAL_IN_MS =
(Number(core.getInput('check_interval')) || 2) * 1000;
// Fail if we have don't have a github token
if (!GITHUB_TOKEN) {
core.setFailed('Required field `token` was not provided');
}
const octokit = github.getOctokit(GITHUB_TOKEN);
const context = github.context;
const owner = context.repo.owner;
const repo = context.repo.repo;
/**
* @type {string}
*/
let sha;
if (github.context.payload && github.context.payload.pull_request) {
sha = await getShaForPullRequest({
octokit,
owner,
repo,
number: github.context.payload.pull_request.number,
});
} else if (github.context.sha) {
sha = github.context.sha;
}
if (!sha) {
core.setFailed('Unable to determine SHA. Exiting...');
return;
}
// Get deployments associated with the pull request.
const deployment = await waitForDeploymentToStart({
octokit,
owner,
repo,
sha: sha,
environment: ENVIRONMENT,
actorName: 'vercel[bot]',
maxTimeout: MAX_TIMEOUT,
checkIntervalInMilliseconds: CHECK_INTERVAL_IN_MS,
});
if (!deployment) {
core.setFailed('no vercel deployment found, exiting...');
return;
}
const status = await waitForStatus({
owner,
repo,
deployment_id: deployment.id,
token: GITHUB_TOKEN,
maxTimeout: MAX_TIMEOUT,
allowInactive: ALLOW_INACTIVE,
checkIntervalInMilliseconds: CHECK_INTERVAL_IN_MS,
});
// Get target url
const targetUrl = status.target_url;
if (!targetUrl) {
core.setFailed(`no target_url found in the status check`);
return;
}
console.log('target url »', targetUrl);
// Set output
core.setOutput('url', targetUrl);
// Wait for url to respond with a success
console.log(`Waiting for a status code 200 from: ${targetUrl}`);
await waitForUrl({
url: targetUrl,
maxTimeout: MAX_TIMEOUT,
checkIntervalInMilliseconds: CHECK_INTERVAL_IN_MS,
vercelPassword: VERCEL_PASSWORD,
path: PATH,
});
} catch (error) {
core.setFailed(error.message);
}
};
exports.run = run;