diff --git a/package.json b/package.json index e127e71..0f31840 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@lambdatest/smartui-cli", - "version": "4.1.33", + "version": "4.1.34", "description": "A command line interface (CLI) to run SmartUI tests on LambdaTest", "files": [ "dist/**/*" @@ -53,6 +53,7 @@ "simple-swizzle": "0.2.2" }, "devDependencies": { + "find-free-port": "^2.0.0", "typescript": "^5.3.2" } } diff --git a/src/lib/constants.ts b/src/lib/constants.ts index b81f8dc..ebcb81c 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -46,6 +46,8 @@ export default { EDGE: 'edge', EDGE_CHANNEL: 'msedge', WEBKIT: 'webkit', + MIN_PORT_RANGE: 49100, + MAX_PORT_RANGE: 60000, // discovery browser launch arguments LAUNCH_ARGS: [ diff --git a/src/lib/server.ts b/src/lib/server.ts index 3eca0c9..cc03eb9 100644 --- a/src/lib/server.ts +++ b/src/lib/server.ts @@ -3,10 +3,43 @@ import path from 'path'; import fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify'; import { readFileSync, truncate } from 'fs' import { Context } from '../types.js' +import { Logger } from 'winston' import { validateSnapshot } from './schemaValidation.js' import { pingIntervalId, startPollingForTunnel, stopTunnelHelper, isTunnelPolling } from './utils.js'; +import constants from './constants.js'; +var fp = require("find-free-port") const uploadDomToS3ViaEnv = process.env.USE_LAMBDA_INTERNAL || false; + +// Helper function to find an available port +async function findAvailablePort(server: FastifyInstance, startPort: number, log: Logger): Promise { + let currentPort = startPort; + + // If the default port gives error, use find-free-port with range 49100-60000 + try { + await server.listen({ port: currentPort }); + return currentPort; + } catch (error: any) { + if (error.code === 'EADDRINUSE') { + log.debug(`Port ${currentPort} is in use, finding available port in range 49100-60000`); + + // Use find-free-port to get an available port in the specified range + const availablePorts = await fp(constants.MIN_PORT_RANGE, constants.MAX_PORT_RANGE); + if (availablePorts.length > 0) { + const freePort = availablePorts[0]; + await server.listen({ port: freePort }); + log.debug(`Found and started server on port ${freePort}`); + return freePort; + } else { + throw new Error('No available ports found in range 49100-60000'); + } + } else { + // If it's not a port conflict error, rethrow it + throw error; + } + } +} + export default async (ctx: Context): Promise> => { const server: FastifyInstance = fastify({ @@ -307,12 +340,21 @@ export default async (ctx: Context): Promise