(url, event, context)
| 41 | } |
| 42 | |
| 43 | const portsHandler = async (url, event, context) => { |
| 44 | const { hostname: domain } = parseTarget(url); |
| 45 | |
| 46 | const delay = (ms) => new Promise((res) => setTimeout(res, ms)); |
| 47 | const timeout = delay(9000); |
| 48 | |
| 49 | const openPorts = []; |
| 50 | const failedPorts = []; |
| 51 | |
| 52 | const promises = PORTS.map((port) => |
| 53 | checkPort(port, domain) |
| 54 | .then(() => { |
| 55 | openPorts.push(port); |
| 56 | return { status: 'fulfilled', port }; |
| 57 | }) |
| 58 | .catch(() => { |
| 59 | failedPorts.push(port); |
| 60 | return { status: 'rejected', port }; |
| 61 | }), |
| 62 | ); |
| 63 | |
| 64 | let timeoutReached = false; |
| 65 | |
| 66 | for (const promise of promises) { |
| 67 | const result = await Promise.race([ |
| 68 | promise, |
| 69 | timeout.then(() => ({ status: 'timeout', timeout: true })), |
| 70 | ]); |
| 71 | if (result.status === 'timeout') { |
| 72 | timeoutReached = true; |
| 73 | if (result.timeout) { |
| 74 | // Add the ports not checked yet to the failedPorts array |
| 75 | const checkedPorts = [...openPorts, ...failedPorts]; |
| 76 | const portsNotChecked = PORTS.filter((port) => !checkedPorts.includes(port)); |
| 77 | failedPorts.push(...portsNotChecked); |
| 78 | } |
| 79 | break; |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | if (timeoutReached) { |
| 84 | return errorResponse('The function timed out before completing.'); |
| 85 | } |
| 86 | |
| 87 | // Sort openPorts and failedPorts before returning |
| 88 | openPorts.sort((a, b) => a - b); |
| 89 | failedPorts.sort((a, b) => a - b); |
| 90 | |
| 91 | return { openPorts, failedPorts }; |
| 92 | }; |
| 93 | |
| 94 | const errorResponse = (message, statusCode = 444) => { |
| 95 | return { error: message }; |
nothing calls this directly
no test coverage detected