diff --git a/tools/src/commands/dev/config/commands.ts b/tools/src/commands/dev/config/commands.ts index fa98d475d..5da04102f 100644 --- a/tools/src/commands/dev/config/commands.ts +++ b/tools/src/commands/dev/config/commands.ts @@ -1,8 +1,8 @@ import fs from 'fs' -import { PB_BINARY_PATH, PB_DIR, PB_KWARGS } from '@/constants/db' +import { PB_BINARY_PATH, PB_DIR, PB_KWARGS, PB_HOST, PB_PORT } from '@/constants/db' import executeCommand from '@/utils/commands' -import { checkPortInUse, delay, killExistingProcess } from '@/utils/helpers' +import { checkAddressInUse, checkPortInUse, delay, killExistingProcess } from '@/utils/helpers' import logger from '@/utils/logger' /** @@ -17,18 +17,12 @@ interface ServiceConfig { export const SERVICE_COMMANDS: Record = { db: { command: async () => { - const killedProcess = killExistingProcess('./pocketbase serve') - - if (killedProcess) { - await delay(2000) - } - - if (checkPortInUse(8090)) { - logger.error( - 'No Pocketbase instance found running, but port 8090 is already in use.' - ) - process.exit(1) - } + if (checkAddressInUse(PB_HOST, PB_PORT)) { + logger.error( + `Database address ${PB_HOST}:${PB_PORT} is already in use.` + ) + process.exit(1) + } if (!fs.existsSync(PB_BINARY_PATH)) { logger.error( diff --git a/tools/src/constants/db.ts b/tools/src/constants/db.ts index d17937280..6eaf190d1 100644 --- a/tools/src/constants/db.ts +++ b/tools/src/constants/db.ts @@ -27,13 +27,16 @@ export const PB_BINARY_PATH = path.resolve( ) // Remove http:// prefix if present -export const PB_HOST = getEnvVar('PB_HOST').replace(/^http:\/\//, '') +export const PB_URL = getEnvVar('PB_HOST').replace(/^http:\/\//, '') + +// Extract host from PB_HOST +export const [PB_HOST, PB_PORT] = PB_URL.split(':') export const PB_KWARGS = [ `--dir=${PB_DATA_DIR}`, `--migrationsDir=${PB_MIGRATIONS_DIR}`, '--automigrate=0', - `--http ${PB_HOST || 'localhost:8090'}` + `--http ${PB_URL || 'localhost:8090'}` ] // Straightaway exit if PB_DIR is not accessible (skip in Docker mode) diff --git a/tools/src/utils/helpers.ts b/tools/src/utils/helpers.ts index a2e852aa9..a7d52bebe 100644 --- a/tools/src/utils/helpers.ts +++ b/tools/src/utils/helpers.ts @@ -122,6 +122,28 @@ export function checkPortInUse(port: number): boolean { } } +/** + * Checks if a specific port is currently in use. + * + * @param port - The port number to check + * @returns True if the port is in use, false otherwise + */ +export function checkAddressInUse(address: string, port: string): boolean { + logger.debug(`Checking if address ${address}:${port} is in use...`); + + try { + executeCommand('nc', { exitOnError: false }, [ + '-zv', + address, + port, + ]); + + return true; + } catch { + return false; + } +} + /** * Creates a promise that resolves after the specified delay. *