Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (55 loc) · 2.05 KB
/
Copy pathindex.js
File metadata and controls
63 lines (55 loc) · 2.05 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
const fs = require('fs');
// Read an action input. GitHub passes each one as an INPUT_<NAME> env var.
function getInput(name, fallback) {
const value = process.env[`INPUT_${name.toUpperCase()}`];
return value && value.trim() !== '' ? value.trim() : fallback;
}
// Send an output back to the workflow so later steps can use it.
function setOutput(name, value) {
if (process.env.GITHUB_OUTPUT) {
fs.appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);
}
}
// The actual check. Kept separate from the I/O above so it is easy to test.
// `fetchFn` is swappable so tests can run offline. Returns status + timing.
async function checkUrl(url, expectedStatus, timeoutMs, fetchFn = fetch) {
const start = Date.now();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchFn(url, { signal: controller.signal });
return {
status: response.status,
durationMs: Date.now() - start,
ok: response.status === expectedStatus,
};
} finally {
clearTimeout(timer);
}
}
async function run() {
const url = getInput('url');
const expectedStatus = Number(getInput('expected-status', '200'));
const timeoutMs = Number(getInput('timeout-ms', '5000'));
try {
const result = await checkUrl(url, expectedStatus, timeoutMs);
setOutput('status', result.status);
setOutput('duration-ms', result.durationMs);
if (result.ok) {
console.log(`OK: ${url} returned ${result.status} in ${result.durationMs}ms`);
} else {
// `::error::` shows up as a red annotation in the workflow.
console.log(`::error::${url} returned ${result.status}, expected ${expectedStatus}`);
process.exitCode = 1;
}
} catch (error) {
// Timed out, or could not connect (bad DNS, refused, etc.).
console.log(`::error::Could not reach ${url}: ${error.message}`);
process.exitCode = 1;
}
}
// Run only when called directly, not when a test imports this file.
if (require.main === module) {
run();
}
module.exports = { checkUrl };