From c5886b0c551b312999f40268553fd07815753758 Mon Sep 17 00:00:00 2001 From: Davin Shearer <2205472+scholarsmate@users.noreply.github.com> Date: Thu, 25 Apr 2024 09:21:22 -0400 Subject: [PATCH] Update scala from 2.13.12 to 2.13.13 --- packages/client/src/server.ts | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/client/src/server.ts b/packages/client/src/server.ts index c5533b7d..bc10c4ed 100644 --- a/packages/client/src/server.ts +++ b/packages/client/src/server.ts @@ -54,6 +54,47 @@ export function delay(milliseconds: number): Promise { }) } +/** + * Find the first available port in a range, or null if no ports are available + * @param startPort start of the port range + * @param endPort end of the port range + * @returns first available port in the range, or null if no ports are available + */ +export async function findFirstAvailablePort( + startPort: number, + endPort: number +): Promise { + const log = getLogger() + return new Promise((resolve) => { + let currentPort = startPort + + const tryNextPort = () => { + if (currentPort > endPort) { + resolve(null) // No ports available in the range + return + } + + const server = createServer() + server.listen(currentPort, '0.0.0.0', () => { + server.close((err) => { + if (err) { + log.error(`Error closing server on port ${currentPort}: ${err}`) + } + resolve(currentPort) // Found an available port + }) + }) + + server.on('error', (err) => { + log.error(`Error when trying to listen on port ${currentPort}: ${err}`) + ++currentPort + tryNextPort() // Try the next port + }) + } + + tryNextPort() + }) +} + /** * Wait for file to exist * @param filePath path to file to wait for