maestri-remote/.context/skills/command-line-environment/scripts/wait-port.mjs

69 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// Espera uma porta TCP aceitar conexão, tentando uma vez por segundo até o limite de tempo.
//
// Existe para substituir o `until timeout 2 bash -c "echo > /dev/tcp/localhost/5672"; do sleep 1; done`,
// que só roda em bash. Serve para confirmar que um container (RabbitMQ, Redis…) já está ouvindo antes de
// subir a aplicação. Não é para acompanhar deploy nem release: lá a regra é verificação pontual única.
//
// Uso:
// node wait-port.mjs --port <porta> [--host localhost] [--timeout 60]
//
// Saída: uma linha dizendo se a porta abriu e em quanto tempo. Código de saída 0 quando abriu, 1 quando
// o tempo acabou, 2 em erro de uso. Só módulos nativos do Node 18+.
import net from 'node:net';
const USAGE = 'uso: node wait-port.mjs --port <porta> [--host localhost] [--timeout 60]';
function usage(msg) {
if (msg) console.error(`erro: ${msg}`);
console.error(USAGE);
process.exitCode = 2;
}
const args = process.argv.slice(2);
const opts = { host: 'localhost', port: null, timeout: 60 };
// --help/-h: uso no stdout e código 0, antes de validar qualquer parâmetro.
const help = args.some((a) => a === '--help' || a === '-h');
if (help) console.log(USAGE);
let bad = help;
for (let i = 0; i < args.length && !bad; i++) {
const a = args[i];
const v = args[i + 1];
if (a === '--port') { opts.port = Number(v); i++; }
else if (a === '--host') { opts.host = v; i++; }
else if (a === '--timeout') { opts.timeout = Number(v); i++; }
else { usage(`opção desconhecida ${a}`); bad = true; }
}
function tryOnce(host, port) {
return new Promise((resolve) => {
const s = net.connect({ host, port });
const done = (ok, why) => { s.destroy(); resolve({ ok, why }); };
s.setTimeout(2000, () => done(false, 'timeout'));
s.once('connect', () => done(true));
s.once('error', (e) => done(false, e.code || e.message));
});
}
if (!bad) {
if (!Number.isInteger(opts.port) || opts.port < 1 || opts.port > 65535) usage('--port é obrigatório (1–65535)');
else if (!(opts.timeout > 0)) usage('--timeout deve ser um número de segundos maior que zero');
else {
const start = Date.now();
let last = '';
for (;;) {
const r = await tryOnce(opts.host, opts.port);
const secs = ((Date.now() - start) / 1000).toFixed(1);
if (r.ok) { console.log(`${opts.host}:${opts.port} aberta após ${secs}s`); break; }
last = r.why;
if (Date.now() - start >= opts.timeout * 1000) {
console.error(`${opts.host}:${opts.port} não abriu em ${opts.timeout}s (último erro: ${last})`);
process.exitCode = 1;
break;
}
await new Promise((res) => setTimeout(res, 1000));
}
}
}