UNPKG

nginx-testing

Version:

Support for integration/acceptance testing of nginx configuration.

57 lines 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.waitForHttpPortOpen = void 0; const http = require("node:http"); const logger_1 = require("../logger"); /** * Waits until the specified port is open and accepting an HTTP request, or the * `timeout` expires. Resolves to `true` on success, `false` on connection refused, * connection reset and connection timeout. Rejects on unexpected errors. * * @param requestOpts Request options; typically `hostname` and `port` should be provided. * @param timeoutMsec Connection timeout in milliseconds; attempts to open the socket will be * terminated _after_ this time has passed. * @param intervalMsec Checking interval in milliseconds. */ const waitForHttpPortOpen = (requestOpts, timeoutMsec, intervalMsec = 100) => new Promise((resolve, reject) => { requestOpts = { method: 'HEAD', path: '/', ...requestOpts }; const expectedErrorCodes = ['ECONNREFUSED', 'ECONNTIMEOUT', 'ECONNRESET']; const startTime = Date.now(); const loop = () => { logger_1.log.debug(`Trying to connect ${JSON.stringify(requestOpts)}`); return checkHttpWithTimeout(requestOpts, timeoutMsec) .then(() => resolve(true)) .catch(err => { logger_1.log.debug(`Got error ${err.code}: ${err}`); if (expectedErrorCodes.includes(err.code)) { if (Date.now() - startTime > timeoutMsec) { logger_1.log.debug(`Timed out after ${Date.now() - startTime}ms`); return resolve(false); } else { return setTimeout(loop, intervalMsec); } } return reject(err); }); }; loop(); }); exports.waitForHttpPortOpen = waitForHttpPortOpen; const checkHttpWithTimeout = (opts, timeout) => new Promise((resolve, reject) => { const req = http.request({ ...opts, timeout }); req .on('close', resolve) .on('error', (err) => { req.destroy(); return reject(err); }) .on('timeout', () => { req.destroy(); const err = Error('Connection timeout'); err.code = 'ECONNTIMEOUT'; return reject(err); }) .end(); }); //# sourceMappingURL=waitForHttpPortOpen.js.map