<# scripts/start_local.ps1 用途:本地一键启动 HXOPS 前后端与后台 worker。 依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。 逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口 → 执行 DB 迁移(flask db upgrade)→ 再分别在新 PowerShell 窗口启动各服务。 Worker 使用 backend/ 根目录的并发入口(worker_kb.py / worker_shipping.py),内部通过 multiprocessing 自分叉子进程池;并发数由 -KbConcurrency / -ShippingConcurrency 透传到环境变量。 #> param( [ValidateSet("sqlite", "postgres")] [string]$DbMode = "sqlite", [string]$DatabaseUrl = "", [int]$KbConcurrency = 1, [int]$ShippingConcurrency = 1, [switch]$SkipInstall, [switch]$SkipMigrate, [switch]$SkipWorker, [switch]$IncludeRpaWorker, [switch]$NoHotReload ) $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.py")), [regex]::Escape((Join-Path $BackendPath "worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "worker_shipping.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")), [regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py")) ) # 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。 # 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。 # 清理阶段必须全部覆盖,避免历史残留进程导致的「多实例重复领取 job / 端口占用」。 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 # XFA 自动标注把 OCR 作为强制视觉交叉证据,shipping Worker 必须安装完整运行时。 & $venvPy -m pip install -r requirements-ocr.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 Invoke-DbMigrate { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl ) Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan Set-Location $BackendPath $venvPy = Join-Path $BackendPath ".venv\Scripts\python.exe" $env:FLASK_APP = "run.py" $env:FLASK_ENV = "development" $env:ENV_NAME = "dev" if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) { $env:DATABASE_URL = $DbUrl } & $venvPy -m flask db upgrade if ($LASTEXITCODE -ne 0) { throw "[db-migrate] flask db upgrade failed with exit code $LASTEXITCODE" } Write-Host "[db-migrate] migration completed." -ForegroundColor Green } 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, [bool]$DisableHotReload = $false ) $dbExport = "" if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) { $escaped = $DbUrl.Replace("'", "''") $dbExport = "`$env:DATABASE_URL='$escaped'; " } if ($DisableHotReload) { $reloaderEnv = "`$env:WERKZEUG_RUN_MAIN='true'; " } else { $reloaderEnv = "" } $cmd = "$dbExport$reloaderEnv 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 Import-DotEnvFilesToCurrentShell { param([string[]]$Paths) foreach ($path in $Paths) { if (-not (Test-Path $path)) { Write-Host "[env] skip (not found): $path" -ForegroundColor DarkGray continue } Write-Host "[env] loading: $path" -ForegroundColor Cyan 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) } Set-Item -Path "env:$name" -Value $value -ErrorAction SilentlyContinue } } } } 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, [int]$Concurrency = 1 ) $envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl $envPrefix += " `$env:ENV_NAME='dev'; `$env:KB_WORKER_CONCURRENCY='$Concurrency';" Start-WorkerWindow ` -Title "kb-worker (concurrency=$Concurrency)" ` -WorkingDirectory $BackendPath ` -EnvPrefix $envPrefix ` -Command ".\.venv\Scripts\python.exe .\worker_kb.py" } function Start-ShippingWorkerWindow { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl, [int]$Concurrency = 1 ) $envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl $envPrefix += " `$env:ENV_NAME='dev'; `$env:SHIPPING_NOTICE_WORKER_CONCURRENCY='$Concurrency';" Start-WorkerWindow ` -Title "shipping-worker (concurrency=$Concurrency)" ` -WorkingDirectory $BackendPath ` -EnvPrefix $envPrefix ` -Command ".\.venv\Scripts\python.exe .\worker_shipping.py" } function Start-ScheduleWorkerWindow { param( [string]$BackendPath, [string]$Mode, [string]$DbUrl ) Start-WorkerWindow ` -Title "schedule-worker" ` -WorkingDirectory $BackendPath ` -EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) ` -Command ".\.venv\Scripts\python.exe .\workers\worker_scheduler.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:SHIPPING_NOTICE_RPA_WORKER_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, [bool]$DisableHotReload = $false ) if ($DisableHotReload) { $envArg = "`$env:VITE_HMR='false'; " } else { $envArg = "" } $cmd = "$envArg 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" } $envFiles = @( (Join-Path $repoRoot ".env.shared"), (Join-Path $repoRoot ".env.dev"), (Join-Path $repoRoot ".env.local") ) # 优先级加载:.env.shared → .env.dev → .env.local(后者覆盖前者) # 显式传参 -DatabaseUrl 的优先级最高,最后覆盖。 Import-DotEnvFilesToCurrentShell -Paths $envFiles $effectiveDbUrl = $DatabaseUrl if ([string]::IsNullOrWhiteSpace($effectiveDbUrl)) { $effectiveDbUrl = $env:DATABASE_URL } if (-not [string]::IsNullOrWhiteSpace($DatabaseUrl)) { $env:DATABASE_URL = $DatabaseUrl Write-Host "[env] DATABASE_URL overridden from -DatabaseUrl parameter." -ForegroundColor DarkGray } $pythonCmd = Get-PythonCommand $doInstall = -not $SkipInstall.IsPresent Write-Host "== HXOPS local startup ==" -ForegroundColor Green Write-Host "mode: $DbMode" -ForegroundColor Green if (-not $SkipWorker.IsPresent) { Write-Host "kb concurrency: $KbConcurrency | shipping concurrency: $ShippingConcurrency" -ForegroundColor Green } if ($DbMode -eq "postgres") { if (-not [string]::IsNullOrWhiteSpace($effectiveDbUrl)) { $masked = $effectiveDbUrl -replace '(?<=://[^:]+:)[^@]+', '******' Write-Host "postgres DATABASE_URL: $masked" -ForegroundColor DarkGray } else { Write-Warning "DbMode=postgres but no DATABASE_URL found in env files or -DatabaseUrl parameter. Relying on app default." } } Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $effectiveDbUrl -DoInstall $doInstall if (-not $SkipMigrate.IsPresent) { Invoke-DbMigrate -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl } else { Write-Host "[db-migrate] skipped (-SkipMigrate)." -ForegroundColor DarkGray } Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall $windowCount = 2 Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl if (-not $SkipWorker.IsPresent) { Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl Start-ScheduleWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl $windowCount += 3 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, schedule-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green } 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