<# scripts/start_local.ps1 用途:本地一键启动 HXOPS 前后端与后台 worker。 依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。 逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。 #> param( [ValidateSet("sqlite", "postgres")] [string]$DbMode = "sqlite", [string]$DatabaseUrl = "", [switch]$SkipInstall, [switch]$SkipWorker, [switch]$SkipRpaWorker ) $ErrorActionPreference = "Stop" $script:LocalFrontendPort = 8881 $script:LocalBackendPort = 5052 function Stop-ProcessSafe { param( [int]$ProcessId, [string]$Label ) if ($ProcessId -le 0) { return } $proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue if (-not $proc) { return } Write-Host "[$Label] stopping PID $ProcessId ($($proc.ProcessName))" -ForegroundColor Yellow Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue } function Stop-PortListeners { param( [int]$Port, [string]$Label ) $pids = @( Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique ) foreach ($processId in $pids) { Stop-ProcessSafe -ProcessId $processId -Label $Label } } function Stop-StaleHxopsPythonProcesses { param( [string]$RepoRoot, [string]$BackendPath ) $patterns = @( [regex]::Escape((Join-Path $BackendPath "run.py")), [regex]::Escape((Join-Path $BackendPath "worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")), [regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py")) ) Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $cmd = $_.CommandLine if ([string]::IsNullOrWhiteSpace($cmd)) { return } foreach ($pattern in $patterns) { if ($cmd -match $pattern) { Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-python" return } } } } function Stop-StaleHxopsFrontendProcesses { param([string]$FrontendPath) $frontendPattern = [regex]::Escape($FrontendPath) Get-CimInstance Win32_Process -Filter "Name='node.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $cmd = $_.CommandLine if ([string]::IsNullOrWhiteSpace($cmd)) { return } if ($cmd -match $frontendPattern -and $cmd -match 'vite') { Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-frontend" } } } function Stop-LocalHxopsStack { param( [string]$RepoRoot, [string]$BackendPath, [string]$FrontendPath ) Write-Host "[cleanup] stopping stale hxops local processes..." -ForegroundColor Yellow Stop-StaleHxopsPythonProcesses -RepoRoot $RepoRoot -BackendPath $BackendPath Stop-StaleHxopsFrontendProcesses -FrontendPath $FrontendPath Stop-PortListeners -Port $script:LocalBackendPort -Label "backend-port" Stop-PortListeners -Port $script:LocalFrontendPort -Label "frontend-port" # Vite 端口被占用时可能漂移到 8882+,一并清理本机 node 监听 for ($port = $script:LocalFrontendPort + 1; $port -le ($script:LocalFrontendPort + 10); $port++) { $pids = @( Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue | Where-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName -eq 'node' } | Select-Object -ExpandProperty OwningProcess -Unique ) foreach ($processId in $pids) { Stop-ProcessSafe -ProcessId $processId -Label "stale-vite-$port" } } Start-Sleep -Milliseconds 800 } function Test-CommandExists { param([string]$Name) return $null -ne (Get-Command $Name -ErrorAction SilentlyContinue) } function Get-PythonCommand { $candidates = @( "py -3.12", "py -3.11", "py -3", "python" ) foreach ($candidate in $candidates) { try { $parts = $candidate.Split(" ", 2) $exe = $parts[0] $args = if ($parts.Count -gt 1) { $parts[1] } else { "" } if (-not (Test-CommandExists $exe)) { continue } if ([string]::IsNullOrWhiteSpace($args)) { & $exe --version | Out-Null } else { & $exe $args --version | Out-Null } return $candidate } catch { continue } } throw "Python was not found. Please install Python 3.11+." } function Ensure-Backend { param( [string]$BackendPath, [string]$PyCmd, [string]$Mode, [string]$DbUrl, [bool]$DoInstall ) Write-Host "[backend] preparing..." -ForegroundColor Cyan Set-Location $BackendPath if (-not (Test-Path ".\venv\Scripts\python.exe")) { Write-Host "[backend] creating virtualenv..." -ForegroundColor Yellow if ($PyCmd -like "py *") { $parts = $PyCmd.Split(" ", 2) & $parts[0] $parts[1] -m venv venv } else { & $PyCmd -m venv venv } } $venvPy = Join-Path $BackendPath "venv\Scripts\python.exe" if ($DoInstall) { Write-Host "[backend] installing python dependencies..." -ForegroundColor Yellow & $venvPy -m pip install --upgrade pip & $venvPy -m pip install -r requirements.txt } if ($Mode -eq "sqlite") { Write-Host "[backend] initializing sqlite data..." -ForegroundColor Yellow & $venvPy .\init_local_db.py } else { if (-not [string]::IsNullOrWhiteSpace($DbUrl)) { $env:DATABASE_URL = $DbUrl Write-Host "[backend] DATABASE_URL set from parameter." -ForegroundColor Yellow } elseif (-not $env:DATABASE_URL) { Write-Warning "DbMode=postgres but DATABASE_URL is not set. Using app default from backend/app/config.py." } Write-Host "[backend] initializing postgres data..." -ForegroundColor Yellow & $venvPy .\init_db.py & $venvPy .\fix_admin.py } } function Ensure-Frontend { param( [string]$FrontendPath, [bool]$DoInstall ) if (-not (Test-CommandExists "npm")) { throw "npm was not found. Please install Node.js (with npm)." } Write-Host "[frontend] preparing..." -ForegroundColor Cyan Set-Location $FrontendPath if ($DoInstall) { Write-Host "[frontend] installing npm dependencies..." -ForegroundColor Yellow npm install } } function Start-BackendWindow { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl ) $dbExport = "" if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) { $escaped = $DbUrl.Replace("'", "''") $dbExport = "`$env:DATABASE_URL='$escaped'; " } $cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py" Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null } function Get-DatabaseUrlExport { param( [string]$Mode, [string]$DbUrl ) if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) { $escaped = $DbUrl.Replace("'", "''") return "`$env:DATABASE_URL='$escaped'; " } return "" } function Get-DotEnvExportPrefix { param([string[]]$Paths) $exports = @() foreach ($path in $Paths) { if (-not (Test-Path $path)) { continue } foreach ($line in Get-Content $path) { if ($line -match '^\s*#' -or $line -match '^\s*$') { continue } if ($line -match '^\s*([^=]+)=(.*)$') { $name = $matches[1].Trim() $value = $matches[2].Trim() if ($value.Length -ge 2 -and ( ($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")) )) { $value = $value.Substring(1, $value.Length - 2) } $escaped = $value.Replace("'", "''") $exports += "`$env:$name='$escaped';" } } } return ($exports -join ' ') } function Start-WorkerWindow { param( [string]$Title, [string]$WorkingDirectory, [string]$Command, [string]$EnvPrefix = "" ) $cmd = "$EnvPrefix Set-Location '$WorkingDirectory'; Write-Host '[$Title] started' -ForegroundColor Cyan; $Command" Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null } function Start-KbWorkerWindow { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl ) Start-WorkerWindow ` -Title "kb-worker" ` -WorkingDirectory $BackendPath ` -EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) ` -Command ".\venv\Scripts\python.exe .\worker_kb.py" } function Start-ShippingWorkerWindow { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl ) Start-WorkerWindow ` -Title "shipping-worker" ` -WorkingDirectory $BackendPath ` -EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) ` -Command ".\venv\Scripts\python.exe .\workers\worker_shipping_notice.py" } function Start-FreightRpaWorkerWindow { param( [string]$RepoRoot, [string]$BackendPath, [string[]]$EnvFiles ) $envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles $envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:FREIGHT_RPA_MOCK='true';" Start-WorkerWindow ` -Title "freight-rpa-worker" ` -WorkingDirectory $RepoRoot ` -EnvPrefix $envPrefix ` -Command "& '$BackendPath\venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py" } function Start-FrontendWindow { param([string]$FrontendPath) $cmd = "Set-Location '$FrontendPath'; npm run dev" Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null } $repoRoot = Split-Path -Parent $PSScriptRoot $backendDir = Join-Path $repoRoot "backend" $frontendDir = Join-Path $repoRoot "frontend" if (-not (Test-Path $backendDir)) { throw "backend directory not found: $backendDir" } if (-not (Test-Path $frontendDir)) { throw "frontend directory not found: $frontendDir" } $pythonCmd = Get-PythonCommand $doInstall = -not $SkipInstall.IsPresent Write-Host "== HXOPS local startup ==" -ForegroundColor Green Write-Host "mode: $DbMode" -ForegroundColor Green Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall $envFiles = @( (Join-Path $repoRoot ".env.shared"), (Join-Path $repoRoot ".env.dev"), (Join-Path $repoRoot ".env.local") ) $windowCount = 2 Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl if (-not $SkipWorker.IsPresent) { Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl $windowCount += 2 if (-not $SkipRpaWorker.IsPresent) { Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles $windowCount += 1 } } Start-FrontendWindow -FrontendPath $frontendDir $windowCount += 1 Write-Host "" Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green if (-not $SkipWorker.IsPresent) { Write-Host "Workers: kb-worker, shipping-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray } Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green Write-Host "Backend URL: http://127.0.0.1:5052" -ForegroundColor Green Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green