feat: 启用后端自动启动与 Setup 引导流程增强
主要修改点: 1. 网络绑定扩展至 Server - .env.example: SERVER_HOST/VITE_SERVER_HOST 从 127.0.0.1 改为 0.0.0.0 - server/src/app/core/config.py: 默认 app_host 从 127.0.0.1 改为 0.0.0.0 2. 启动脚本重构(重命名以区分职责) - server/start.sh → server/server_start.sh - web/start.sh → web/web_start.sh - 根目录 start.sh: 更新调用路径(./start.sh → ./server_start.sh, ./web_start.sh) - 根目录 start.sh: 新增 setup_ready() 检测函数 - 根目录 start.sh: server_probe_host() 支持 0.0.0.0 探测转换为 127.0.0.1 - 根目录 start.sh: start_setup_web() 新增 X_FINANCIAL_FORCE_SETUP=true 3. API URL 动态化 (web/src/services/api.js) - 从 localStorage 持久化读取 API Base URL - 新增 setRuntimeApiBaseUrl() / getRuntimeApiBaseUrl() 导出函数 - buildUrl() 改用运行时 runtimeApiBaseUrl 4. 浏览器 Host 智能解析 (web/vite.config.js) - 新增 resolveBrowserApiHost(): 根据 server_host/web_host 配置决定浏览器端使用的 API Host - buildApiBaseUrl() 改用 resolveBrowserApiHost() - 新增后端启动状态管理: backendStartState / cloneBackendStartState() / updateBackendStep() - 后端启动分 5 步追踪: config → deps → server → health → done - 新增 backendStartPromise 避免重复启动 5. Setup 表单逻辑增强 (web/src/composables/useSetupView.js) - 新增 shouldExposeServerHost(): 判断浏览器 host 是否非本地 - 新增 resolveInitialServerHost(): 当浏览器访问且 server_host 为本地时暴露 0.0.0.0 - buildPayload(): 根据 shouldExposeServerHost() 自动将 127.0.0.1/localhost 转为 0.0.0.0 6. Bootstrap API 扩展 (web/src/services/bootstrap.js) - 新增 startBootstrapBackend(): POST /bootstrap/backend 触发后端启动 - 新增 fetchBootstrapBackendStatus(): GET /bootstrap/backend 查询后端状态 7. Session 导航增强 (web/src/composables/useSystemState.js) - 新增 resolveBrowserApiBaseUrl(): 智能解析浏览器端 API Base URL - installSessionNavigation(): 调用 fetchBootstrapState() 同步引导状态 - 新增 reconcileEntryRoute(): 根据引导状态协调路由 - VITE_SERVER_HOST 默认值从 127.0.0.1 改为 0.0.0.0 8. Setup 视图增强 (web/src/views/SetupRouteView.vue) - 向 SetupView 传递启动进度相关 props: startupCountdownSeconds, startupLog, startupSteps, startupVisible, progressMessage 9. CSS 新增 (web/src/assets/styles/views/setup-view.css) - .setup-complete-progress: 进度文字样式 - .setup-modal-backdrop: 模态框遮罩 - .setup-startup-modal: 启动模态框容器 - .setup-startup-head / .setup-startup-body / .setup-startup-spinner: 模态框头部/内容/加载动画 - .setup-startup-steps / .setup-startup-step: 步骤列表及单个步骤 - .setup-startup-step.is-running / .is-success / .is-failed: 步骤状态样式 - .setup-startup-log: 启动日志区域
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import net from 'node:net'
|
||||
@@ -15,6 +16,46 @@ const adminSecretDir = path.join(rootDir, 'server', '.secrets')
|
||||
const adminSecretFile = path.join(adminSecretDir, 'admin.json')
|
||||
const adminScryptOptions = { N: 16384, r: 8, p: 1 }
|
||||
const adminScryptKeyLength = 64
|
||||
let backendStartPromise = null
|
||||
let backendStartState = createBackendStartState()
|
||||
|
||||
function createBackendStartState() {
|
||||
return {
|
||||
running: false,
|
||||
completed: false,
|
||||
failed: false,
|
||||
detail: '',
|
||||
logTail: '',
|
||||
steps: [
|
||||
{ id: 'config', label: '第一步:读取初始化配置', status: 'pending', detail: '等待配置写入完成。' },
|
||||
{ id: 'deps', label: '第二步:安装/检查后端虚拟环境', status: 'pending', detail: '等待执行 server/server_start.sh deps。' },
|
||||
{ id: 'server', label: '第三步:启动 FastAPI 服务', status: 'pending', detail: '等待启动 uvicorn。' },
|
||||
{ id: 'health', label: '第四步:检测后端健康状态', status: 'pending', detail: '等待 /api/v1/health 返回正常。' },
|
||||
{ id: 'done', label: '第五步:配置完成', status: 'pending', detail: '后端就绪后进入登录页。' }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function cloneBackendStartState() {
|
||||
return {
|
||||
...backendStartState,
|
||||
steps: backendStartState.steps.map((step) => ({ ...step }))
|
||||
}
|
||||
}
|
||||
|
||||
function updateBackendStep(id, status, detail = '') {
|
||||
backendStartState.steps = backendStartState.steps.map((step) => {
|
||||
if (step.id !== id) {
|
||||
return step
|
||||
}
|
||||
|
||||
return {
|
||||
...step,
|
||||
status,
|
||||
detail: detail || step.detail
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function ensureEnvFile() {
|
||||
if (fs.existsSync(envFile)) {
|
||||
@@ -177,6 +218,26 @@ function resolveClientHost(host) {
|
||||
return String(host || '').trim()
|
||||
}
|
||||
|
||||
function resolveBrowserApiHost(serverHost, webHost) {
|
||||
const normalizedServerHost = normalizeLoopbackHost(serverHost)
|
||||
const normalizedWebHost = normalizeLoopbackHost(webHost)
|
||||
|
||||
if (
|
||||
(normalizedServerHost === '0.0.0.0' || normalizedServerHost === '127.0.0.1') &&
|
||||
normalizedWebHost &&
|
||||
normalizedWebHost !== '0.0.0.0' &&
|
||||
normalizedWebHost !== '127.0.0.1'
|
||||
) {
|
||||
return String(webHost || '').trim()
|
||||
}
|
||||
|
||||
if (normalizedServerHost === '0.0.0.0') {
|
||||
return '127.0.0.1'
|
||||
}
|
||||
|
||||
return String(serverHost || '').trim()
|
||||
}
|
||||
|
||||
function hostsConflict(left, right) {
|
||||
const normalizedLeft = normalizeLoopbackHost(left)
|
||||
const normalizedRight = normalizeLoopbackHost(right)
|
||||
@@ -273,11 +334,27 @@ function buildCorsOrigins(payload) {
|
||||
|
||||
function buildApiBaseUrl(payload, currentEnv) {
|
||||
const apiPrefix = currentEnv.API_V1_PREFIX || '/api/v1'
|
||||
const host = resolveClientHost(payload.server_host)
|
||||
const host = resolveBrowserApiHost(payload.server_host, payload.web_host)
|
||||
const port = String(payload.server_port || '').trim()
|
||||
return `http://${host}:${port}${apiPrefix}`
|
||||
}
|
||||
|
||||
function buildServerHealthUrl(env) {
|
||||
const apiPrefix = env.API_V1_PREFIX || '/api/v1'
|
||||
const host = resolveClientHost(env.SERVER_HOST || '127.0.0.1')
|
||||
const port = String(env.SERVER_PORT || 8000).trim()
|
||||
return `http://${host}:${port}${apiPrefix}/health`
|
||||
}
|
||||
|
||||
function buildBrowserReachableServerHealthUrl(env) {
|
||||
const apiPrefix = env.API_V1_PREFIX || '/api/v1'
|
||||
const serverHost = String(env.SERVER_HOST || '127.0.0.1').trim()
|
||||
const webHost = String(env.WEB_HOST || '').trim()
|
||||
const host = resolveBrowserApiHost(serverHost, webHost)
|
||||
const port = String(env.SERVER_PORT || 8000).trim()
|
||||
return `http://${host}:${port}${apiPrefix}/health`
|
||||
}
|
||||
|
||||
function buildClientEnvUpdates(payload, apiBaseUrl) {
|
||||
return {
|
||||
VITE_SETUP_COMPLETED: 'true',
|
||||
@@ -298,22 +375,24 @@ function buildClientEnvUpdates(payload, apiBaseUrl) {
|
||||
}
|
||||
|
||||
function normalizeState(env) {
|
||||
const adminConfigured = Boolean(readAdminSecret())
|
||||
|
||||
return {
|
||||
initialized: String(env.SETUP_COMPLETED || '').toLowerCase() === 'true',
|
||||
initialized: String(env.SETUP_COMPLETED || '').toLowerCase() === 'true' && adminConfigured,
|
||||
company: {
|
||||
name: env.COMPANY_NAME || '',
|
||||
code: env.COMPANY_CODE || '',
|
||||
admin_email: env.ADMIN_EMAIL || ''
|
||||
},
|
||||
admin: {
|
||||
configured: Boolean(readAdminSecret())
|
||||
configured: adminConfigured
|
||||
},
|
||||
web: {
|
||||
host: env.WEB_HOST || '0.0.0.0',
|
||||
port: Number(env.WEB_PORT || 5173)
|
||||
},
|
||||
server: {
|
||||
host: env.SERVER_HOST || '127.0.0.1',
|
||||
host: env.SERVER_HOST || '0.0.0.0',
|
||||
port: Number(env.SERVER_PORT || 8000)
|
||||
},
|
||||
database: {
|
||||
@@ -375,10 +454,22 @@ function validateRuntimePayload(payload) {
|
||||
}
|
||||
|
||||
function resolveRuntimePayload(payload, currentEnv) {
|
||||
const webHost = String(payload.web_host || currentEnv.WEB_HOST || '0.0.0.0').trim()
|
||||
const serverHost = String(payload.server_host || currentEnv.SERVER_HOST || '0.0.0.0').trim()
|
||||
const normalizedWebHost = normalizeLoopbackHost(webHost)
|
||||
const normalizedServerHost = normalizeLoopbackHost(serverHost)
|
||||
|
||||
return {
|
||||
...payload,
|
||||
web_host: String(payload.web_host || currentEnv.WEB_HOST || '0.0.0.0').trim(),
|
||||
web_port: Number(payload.web_port || currentEnv.WEB_PORT || 5173)
|
||||
web_host: webHost,
|
||||
web_port: Number(payload.web_port || currentEnv.WEB_PORT || 5173),
|
||||
server_host:
|
||||
normalizedWebHost &&
|
||||
normalizedWebHost !== '127.0.0.1' &&
|
||||
normalizedWebHost !== '0.0.0.0' &&
|
||||
normalizedServerHost === '127.0.0.1'
|
||||
? '0.0.0.0'
|
||||
: serverHost
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,10 +603,178 @@ async function testDatabaseConnection(payload) {
|
||||
}
|
||||
}
|
||||
|
||||
async function probeBackendHealth(env) {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 2000)
|
||||
|
||||
try {
|
||||
const response = await fetch(buildServerHealthUrl(env), {
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
return false
|
||||
}
|
||||
|
||||
const payload = await response.json().catch(() => null)
|
||||
return payload?.status === 'ok'
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
async function probeBrowserReachableBackendHealth(env) {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 2000)
|
||||
|
||||
try {
|
||||
const response = await fetch(buildBrowserReachableServerHealthUrl(env), {
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
return false
|
||||
}
|
||||
|
||||
const payload = await response.json().catch(() => null)
|
||||
return payload?.status === 'ok'
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForBackendReady(env) {
|
||||
const timeoutSeconds = Number(env.SERVER_STARTUP_TIMEOUT || 300)
|
||||
const maxAttempts = Number.isFinite(timeoutSeconds) && timeoutSeconds > 0 ? timeoutSeconds : 300
|
||||
let localOnlyAttempts = 0
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
||||
const localReady = await probeBackendHealth(env)
|
||||
const browserReady = await probeBrowserReachableBackendHealth(env)
|
||||
|
||||
if (localReady && browserReady) {
|
||||
return {
|
||||
ok: true,
|
||||
detail: 'FastAPI 后端已启动。'
|
||||
}
|
||||
}
|
||||
|
||||
if (localReady && !browserReady) {
|
||||
localOnlyAttempts += 1
|
||||
|
||||
if (localOnlyAttempts >= 5) {
|
||||
throw new Error(
|
||||
'FastAPI 仅在本机地址可用,浏览器访问地址不可达。通常是旧后端仍以 127.0.0.1 启动并占用端口,请停止旧后端后重新完成初始化。'
|
||||
)
|
||||
}
|
||||
} else {
|
||||
localOnlyAttempts = 0
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
}
|
||||
|
||||
throw new Error(`FastAPI 未在 ${maxAttempts}s 内完成启动,请查看 server/logs/bootstrap-backend.log。`)
|
||||
}
|
||||
|
||||
function readBackendLogTail(logFile) {
|
||||
if (!fs.existsSync(logFile)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(logFile, 'utf8')
|
||||
const lines = content.trimEnd().split(/\r?\n/u)
|
||||
return lines.slice(-30).join('\n')
|
||||
}
|
||||
|
||||
function completeBackendStartup(detail) {
|
||||
backendStartState.running = false
|
||||
backendStartState.completed = true
|
||||
backendStartState.failed = false
|
||||
backendStartState.detail = detail
|
||||
updateBackendStep('config', 'success', '初始化配置已写入。')
|
||||
updateBackendStep('deps', 'success', '后端依赖和虚拟环境检查完成。')
|
||||
updateBackendStep('server', 'success', 'FastAPI 进程已启动。')
|
||||
updateBackendStep('health', 'success', '健康检查通过。')
|
||||
updateBackendStep('done', 'success', '配置成功,准备进入登录页。')
|
||||
}
|
||||
|
||||
function failBackendStartup(error, logFile) {
|
||||
backendStartState.running = false
|
||||
backendStartState.completed = false
|
||||
backendStartState.failed = true
|
||||
backendStartState.detail = error instanceof Error ? error.message : 'FastAPI 后端启动失败。'
|
||||
backendStartState.logTail = readBackendLogTail(logFile)
|
||||
updateBackendStep('done', 'error', backendStartState.detail)
|
||||
}
|
||||
|
||||
async function startBackendAndWait() {
|
||||
const env = readEnvState()
|
||||
const logDir = path.join(rootDir, 'server', 'logs')
|
||||
const logFile = path.join(logDir, 'bootstrap-backend.log')
|
||||
|
||||
if ((await probeBackendHealth(env)) && (await probeBrowserReachableBackendHealth(env))) {
|
||||
backendStartState = createBackendStartState()
|
||||
completeBackendStartup('FastAPI 后端已就绪。')
|
||||
backendStartState.logTail = readBackendLogTail(logFile)
|
||||
return cloneBackendStartState()
|
||||
}
|
||||
|
||||
if (!backendStartPromise) {
|
||||
backendStartState = createBackendStartState()
|
||||
backendStartState.running = true
|
||||
backendStartState.detail = '正在启动 FastAPI 后端。'
|
||||
updateBackendStep('config', 'success', '初始化配置已写入。')
|
||||
updateBackendStep('deps', 'running', '正在创建/检查虚拟环境并安装依赖。')
|
||||
updateBackendStep('server', 'pending', '等待依赖检查完成后启动。')
|
||||
updateBackendStep('health', 'pending', '等待 FastAPI 响应。')
|
||||
|
||||
backendStartPromise = (async () => {
|
||||
fs.mkdirSync(logDir, { recursive: true })
|
||||
|
||||
const stdout = fs.openSync(logFile, 'a')
|
||||
const stderr = fs.openSync(logFile, 'a')
|
||||
const child = spawn('bash', [path.join(rootDir, 'start.sh'), 'server'], {
|
||||
cwd: rootDir,
|
||||
detached: true,
|
||||
stdio: ['ignore', stdout, stderr]
|
||||
})
|
||||
|
||||
child.unref()
|
||||
updateBackendStep('server', 'running', '后端启动命令已提交,等待 uvicorn 监听端口。')
|
||||
updateBackendStep('health', 'running', '正在轮询 /api/v1/health。')
|
||||
|
||||
try {
|
||||
await waitForBackendReady(env)
|
||||
completeBackendStartup('FastAPI 后端已启动。')
|
||||
} catch (error) {
|
||||
failBackendStartup(error, logFile)
|
||||
} finally {
|
||||
backendStartState.logTail = readBackendLogTail(logFile)
|
||||
}
|
||||
|
||||
return cloneBackendStartState()
|
||||
})().finally(() => {
|
||||
backendStartPromise = null
|
||||
})
|
||||
}
|
||||
|
||||
backendStartState.logTail = readBackendLogTail(logFile)
|
||||
return cloneBackendStartState()
|
||||
}
|
||||
|
||||
function localSetupPlugin() {
|
||||
return {
|
||||
name: 'local-setup-api',
|
||||
configureServer(server) {
|
||||
server.watcher.unwatch(envFile)
|
||||
server.watcher.unwatch(envExampleFile)
|
||||
server.watcher.unwatch(path.join(rootDir, 'server', 'logs'))
|
||||
|
||||
server.middlewares.use('/__setup/auth/login', async (req, res) => {
|
||||
try {
|
||||
if (req.method !== 'POST') {
|
||||
@@ -615,6 +874,36 @@ function localSetupPlugin() {
|
||||
}
|
||||
})
|
||||
|
||||
server.middlewares.use('/__setup/bootstrap/backend', async (req, res) => {
|
||||
try {
|
||||
if (req.method === 'GET') {
|
||||
const logFile = path.join(rootDir, 'server', 'logs', 'bootstrap-backend.log')
|
||||
backendStartState.logTail = readBackendLogTail(logFile)
|
||||
sendJson(res, 200, cloneBackendStartState())
|
||||
return
|
||||
}
|
||||
|
||||
if (req.method !== 'POST') {
|
||||
sendJson(res, 405, { detail: 'Method not allowed' })
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await startBackendAndWait()
|
||||
sendJson(res, 200, result)
|
||||
} catch (error) {
|
||||
sendJson(res, 500, {
|
||||
ok: false,
|
||||
detail: error instanceof Error ? error.message : 'FastAPI 后端启动失败。'
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
sendJson(res, 500, {
|
||||
detail: error instanceof Error ? error.message : '后端启动桥接服务异常。'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
server.middlewares.use('/__setup/bootstrap', async (req, res) => {
|
||||
try {
|
||||
if (req.method === 'GET') {
|
||||
@@ -684,5 +973,14 @@ function localSetupPlugin() {
|
||||
|
||||
export default defineConfig({
|
||||
envDir: '..',
|
||||
server: {
|
||||
watch: {
|
||||
ignored: [
|
||||
envFile,
|
||||
envExampleFile,
|
||||
path.join(rootDir, 'server', 'logs', '**')
|
||||
]
|
||||
}
|
||||
},
|
||||
plugins: [vue(), localSetupPlugin()]
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user