verify-remote-ssh-runtime.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { spawn } from "node:child_process";
  2. import { createServer } from "node:net";
  3. export function run(command, args, { input, allowFailure = false, quiet = false } = {}) {
  4. return new Promise((resolvePromise, rejectPromise) => {
  5. const child = spawn(command, args, {
  6. stdio: [input ? "pipe" : "ignore", "pipe", "pipe"],
  7. });
  8. let stdout = "";
  9. let stderr = "";
  10. child.stdout.on("data", (chunk) => {
  11. stdout += chunk;
  12. });
  13. child.stderr.on("data", (chunk) => {
  14. stderr += chunk;
  15. });
  16. if (input) {
  17. child.stdin.write(input);
  18. child.stdin.end();
  19. }
  20. child.once("error", rejectPromise);
  21. child.once("exit", (code) => {
  22. if (code === 0 || allowFailure) {
  23. resolvePromise({ code: code ?? 1, stdout, stderr });
  24. } else {
  25. if (!quiet) console.error(stderr || stdout);
  26. rejectPromise(new Error(`${command} ${args.join(" ")} exited with code ${code ?? "null"}`));
  27. }
  28. });
  29. });
  30. }
  31. export async function findFreePort() {
  32. return await new Promise((resolvePromise, rejectPromise) => {
  33. const server = createServer();
  34. server.once("error", rejectPromise);
  35. server.listen(0, "127.0.0.1", () => {
  36. const { port } = server.address();
  37. server.close(() => resolvePromise(port));
  38. });
  39. });
  40. }
  41. export async function retry(description, attempts, delayMs, action) {
  42. let lastError;
  43. for (let attempt = 1; attempt <= attempts; attempt += 1) {
  44. try {
  45. return await action();
  46. } catch (error) {
  47. lastError = error;
  48. await new Promise((resolvePromise) => setTimeout(resolvePromise, delayMs));
  49. }
  50. }
  51. throw new Error(`${description} failed after ${attempts} attempts: ${lastError}`);
  52. }
  53. export function assert(condition, message) {
  54. if (!condition) throw new Error(`Assertion failed: ${message}`);
  55. }