fix(cli): enhance database boot with address check and logging

This commit is contained in:
lukashow
2026-02-03 20:47:27 +08:00
committed by melvinchia3636
parent cf820b099e
commit 53c16a51f0
3 changed files with 35 additions and 16 deletions

View File

@@ -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<string, ServiceConfig> = {
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(

View File

@@ -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)

View File

@@ -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.
*