1 parent
519e2b4a5f
commit
d7837de561
45 files changed
+1588
-109
No files matched your search
@@ -0,0 +1,91 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { lstat, mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runtimeRoot, sourceRoot } from './runtime-config.mjs'
|
||||
|
||||
const receiptPath = path.join(sourceRoot, 'out', 'build-state.json')
|
||||
const skipped = new Set(['node_modules', 'dist', 'dist-ssr', 'output', 'bundled', '__pycache__', '.git'])
|
||||
const sourceDirectories = ['backend', 'frontend', 'plugins/pmail_telegram_push', 'deploy']
|
||||
|
||||
export async function sourceFingerprint(root = sourceRoot) {
|
||||
const hash = createHash('sha256')
|
||||
async function visit(relative) {
|
||||
const entries = await readdir(path.join(root, relative), { withFileTypes: true })
|
||||
entries.sort((left, right) => left.name.localeCompare(right.name, 'en'))
|
||||
for (const entry of entries) {
|
||||
if (skipped.has(entry.name) || entry.name.startsWith('.tmp-') || entry.name === 'auto-imports.d.ts' || entry.name === 'components.d.ts') continue
|
||||
const name = `${relative}/${entry.name}`
|
||||
if (entry.isDirectory()) {
|
||||
await visit(name)
|
||||
} else if (!/\.(exe|log|pid|db|tsbuildinfo)$/.test(entry.name)) {
|
||||
if (!entry.isFile()) throw new Error(`源码包含链接或特殊文件:${name}`)
|
||||
hash.update(name).update('\0').update(await readFile(path.join(root, name))).update('\0')
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const directory of sourceDirectories) await visit(directory)
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
export async function fileDigest(filename) {
|
||||
const info = await lstat(filename)
|
||||
if (!info.isFile() || info.isSymbolicLink() || info.size === 0) throw new Error('编译产物为空或不是普通文件')
|
||||
return createHash('sha256').update(await readFile(filename)).digest('hex')
|
||||
}
|
||||
|
||||
const artifacts = [
|
||||
['out/backend/smail.exe', 'smail.exe'],
|
||||
['out/backend/smail-admin.exe', 'smail-admin.exe'],
|
||||
['out/plugins/spam_block.exe', null],
|
||||
['out/plugins/pmail_telegram_push.exe', null],
|
||||
['out/plugins/wechat_push.exe', null]
|
||||
]
|
||||
|
||||
export async function sealBuild(expectedFingerprint) {
|
||||
const actual = await sourceFingerprint()
|
||||
if (!expectedFingerprint || actual !== expectedFingerprint) throw new Error('编译期间源码发生变化,请重新编译,拒绝部署不一致产物')
|
||||
const files = await Promise.all(artifacts.map(async ([source, target]) => ({
|
||||
source, target, sha256: await fileDigest(path.join(sourceRoot, source))
|
||||
})))
|
||||
const receipt = {
|
||||
sourceFingerprint: actual,
|
||||
gitHash: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: sourceRoot, encoding: 'utf8', windowsHide: true }).trim(),
|
||||
builtAt: new Date().toISOString(),
|
||||
files
|
||||
}
|
||||
await mkdir(path.dirname(receiptPath), { recursive: true })
|
||||
await writeFile(`${receiptPath}.tmp`, JSON.stringify(receipt, null, 2) + '\n')
|
||||
await rename(`${receiptPath}.tmp`, receiptPath)
|
||||
return receipt
|
||||
}
|
||||
|
||||
export async function verifyBuild({ deployed = false } = {}) {
|
||||
const receipt = JSON.parse(await readFile(receiptPath, 'utf8'))
|
||||
if (receipt.sourceFingerprint !== await sourceFingerprint()) throw new Error('源码已变化,必须重新编译后才能启动')
|
||||
if (JSON.stringify(receipt.files.map(item => [item.source, item.target])) !== JSON.stringify(artifacts)) {
|
||||
throw new Error('编译清单不完整,请重新编译')
|
||||
}
|
||||
for (const item of receipt.files) {
|
||||
if (await fileDigest(path.join(sourceRoot, item.source)) !== item.sha256) throw new Error(`编译产物校验失败:${item.source}`)
|
||||
if (deployed && item.target && await fileDigest(path.join(runtimeRoot, item.target)) !== item.sha256) {
|
||||
throw new Error(`部署产物不是最新编译结果:${item.target}`)
|
||||
}
|
||||
}
|
||||
return receipt
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
switch (process.argv[2]) {
|
||||
case 'fingerprint': console.log(await sourceFingerprint()); break
|
||||
case 'seal': await sealBuild(process.argv[3]); break
|
||||
case 'verify': await verifyBuild({ deployed: process.argv.includes('--deployed') }); break
|
||||
default: throw new Error('用法:build-state.mjs fingerprint|seal|verify')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error.message)
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
+43
-4
@@ -2,24 +2,63 @@
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$fingerprint = & node (Join-Path $PSScriptRoot 'build-state.mjs') fingerprint
|
||||
if ($LASTEXITCODE -ne 0) { throw '无法计算源码指纹' }
|
||||
$output = Join-Path $root 'out\backend'
|
||||
New-Item -ItemType Directory -Path $output -Force | Out-Null
|
||||
if (-not $SkipFrontend) {
|
||||
# 只归档确定的编译目录,不删除文件;防止历史散列资源持续进入 Go 嵌入包。
|
||||
$archive = Join-Path $root ('out\build-history\' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff'))
|
||||
$generated = @{
|
||||
'frontend' = 'out\frontend'
|
||||
'embedded-frontend' = 'backend\listen\http_server\dist'
|
||||
'telegram-ui' = 'out\plugins\telegram-ui'
|
||||
'embedded-telegram' = 'plugins\pmail_telegram_push\hook\dist'
|
||||
'embedded-plugins' = 'backend\cmd\smail\bundled'
|
||||
}
|
||||
foreach ($name in $generated.Keys) {
|
||||
$source = [IO.Path]::GetFullPath((Join-Path $root $generated[$name]))
|
||||
$target = [IO.Path]::GetFullPath((Join-Path $archive $name))
|
||||
$boundary = [IO.Path]::GetFullPath($root).TrimEnd('\') + '\'
|
||||
if (-not $source.StartsWith($boundary, [StringComparison]::OrdinalIgnoreCase) -or -not $target.StartsWith($boundary, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw '编译归档路径越过项目目录,已停止'
|
||||
}
|
||||
if (Test-Path -LiteralPath $source) {
|
||||
$info = Get-Item -LiteralPath $source -Force
|
||||
if (-not $info.PSIsContainer -or $info.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '编译目录无效或为链接,禁止归档' }
|
||||
New-Item -ItemType Directory -Path $archive -Force | Out-Null
|
||||
Move-Item -LiteralPath $source -Destination $target -ErrorAction Stop
|
||||
}
|
||||
}
|
||||
Push-Location (Join-Path $root 'frontend')
|
||||
try {
|
||||
& npm.cmd run build
|
||||
if ($LASTEXITCODE -ne 0) { throw '前端构建失败' }
|
||||
} finally { Pop-Location }
|
||||
}
|
||||
& node (Join-Path $PSScriptRoot 'build-plugins.mjs') --dev
|
||||
if ($LASTEXITCODE -ne 0) { throw '插件构建失败' }
|
||||
$bundle = Join-Path $root 'backend\cmd\smail\bundled'
|
||||
New-Item -ItemType Directory -Path $bundle -Force | Out-Null
|
||||
foreach ($name in @('spam_block.exe', 'pmail_telegram_push.exe', 'wechat_push.exe')) {
|
||||
Copy-Item -LiteralPath (Join-Path $root "out\plugins\$name") -Destination (Join-Path $bundle $name) -ErrorAction Stop
|
||||
}
|
||||
Push-Location (Join-Path $root 'backend')
|
||||
try {
|
||||
& go build -o (Join-Path $output 'smail-dev.exe') .
|
||||
$gitHash = (& git rev-parse HEAD).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw '无法读取构建提交信息' }
|
||||
$buildTime = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
|
||||
$goVersion = (& go version).Trim()
|
||||
$flags = "-s -w -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.Version=dev-$($fingerprint.Substring(0, 12))' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.GitHash=$gitHash' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.BuildTime=$buildTime' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.GoVersion=$goVersion'"
|
||||
& go build -tags bundled -trimpath -ldflags $flags -o (Join-Path $output 'smail.exe') ./cmd/smail
|
||||
if ($LASTEXITCODE -ne 0) { throw '开发后端构建失败' }
|
||||
& go build -o (Join-Path $output 'smail-admin.exe') ./cmd/smail-admin
|
||||
& go build -trimpath -ldflags $flags -o (Join-Path $output 'smail-admin.exe') ./cmd/smail-admin
|
||||
if ($LASTEXITCODE -ne 0) { throw '管理工具构建失败' }
|
||||
& go build -o (Join-Path $output 'smail-config.exe') ./cmd/smail-config
|
||||
if ($LASTEXITCODE -ne 0) { throw '配置工具构建失败' }
|
||||
} finally { Pop-Location }
|
||||
& node (Join-Path $PSScriptRoot 'build-plugins.mjs') --dev
|
||||
if ($LASTEXITCODE -ne 0) { throw '插件构建失败' }
|
||||
if (-not $SkipFrontend) {
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') seal $fingerprint
|
||||
if ($LASTEXITCODE -ne 0) { throw '编译产物封存失败,禁止部署或启动旧包' }
|
||||
}
|
||||
Write-Output '构建完成:out/frontend、out/backend 和 out/plugins,包含三个内置插件。正式发行请使用 Makefile 的跨平台构建目标。'
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cp, lstat, mkdir, readdir, rename } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { buildPlan, root } from './build-plugins.mjs'
|
||||
|
||||
const plan = buildPlan({ target: process.argv[2] })
|
||||
const destination = path.join(root, 'backend/cmd/smail/bundled')
|
||||
for (const item of plan) {
|
||||
const info = await lstat(item.output)
|
||||
if (!info.isFile() || info.isSymbolicLink()) throw new Error('待嵌入插件不是普通文件')
|
||||
}
|
||||
try {
|
||||
await readdir(destination)
|
||||
const history = path.join(root, 'out/build-history', `plugins-${Date.now()}`)
|
||||
await mkdir(path.dirname(history), { recursive: true })
|
||||
const info = await lstat(destination)
|
||||
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('嵌入目录无效')
|
||||
await rename(destination, history)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error
|
||||
}
|
||||
await mkdir(destination, { recursive: true })
|
||||
for (const item of plan) await cp(item.output, path.join(destination, path.basename(item.output)), { force: false })
|
||||
console.log('三个插件已准备嵌入主程序。')
|
||||
@@ -0,0 +1,9 @@
|
||||
import { assertDeploymentLayout } from './runtime-config.mjs'
|
||||
|
||||
try {
|
||||
assertDeploymentLayout()
|
||||
console.log('模拟部署配置、证书与账号库路径检查通过。')
|
||||
} catch (error) {
|
||||
console.error(`yunx-test 尚未完成安全迁移,禁止启动:${error.message}`)
|
||||
process.exitCode = 1
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$runtime = Join-Path $root 'yunx-test'
|
||||
$boundary = [IO.Path]::GetFullPath($root).TrimEnd('\') + '\'
|
||||
foreach ($directory in @($runtime, (Join-Path $root 'out'))) {
|
||||
if (-not [IO.Path]::GetFullPath($directory).StartsWith($boundary, [StringComparison]::OrdinalIgnoreCase)) { throw '部署目录越过项目边界' }
|
||||
if (Test-Path -LiteralPath $directory) {
|
||||
$info = Get-Item -LiteralPath $directory -Force
|
||||
if (-not $info.PSIsContainer -or $info.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '部署目录不能是链接或文件' }
|
||||
}
|
||||
}
|
||||
$binary = Join-Path $runtime 'smail.exe'
|
||||
$running = Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq $binary }
|
||||
if ($running) { throw 'yunx-test 后端仍在运行,请先停止后端再部署,禁止覆盖正在运行的程序' }
|
||||
New-Item -ItemType Directory -Path (Join-Path $root 'out') -Force | Out-Null
|
||||
$lock = $null
|
||||
try {
|
||||
$lock = [IO.File]::Open((Join-Path $root 'out\deployment.lock'), [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
|
||||
|
||||
# 完整构建成功后才允许更新运行包,失败时不回退使用历史产物。
|
||||
& (Join-Path $PSScriptRoot 'build.ps1')
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') verify
|
||||
if ($LASTEXITCODE -ne 0) { throw '编译产物校验失败,未部署' }
|
||||
|
||||
New-Item -ItemType Directory -Path $runtime -Force | Out-Null
|
||||
$receipt = Get-Content -LiteralPath (Join-Path $root 'out\build-state.json') -Encoding UTF8 -Raw | ConvertFrom-Json
|
||||
$backup = Join-Path $root ('out\deployment-history\' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff'))
|
||||
foreach ($item in $receipt.files) {
|
||||
if (-not $item.target) { continue }
|
||||
$target = Join-Path $runtime $item.target
|
||||
if (Test-Path -LiteralPath $target) {
|
||||
$info = Get-Item -LiteralPath $target -Force
|
||||
if ($info.Attributes -band [IO.FileAttributes]::ReparsePoint -or $info.PSIsContainer) { throw '部署程序不能是链接或目录' }
|
||||
New-Item -ItemType Directory -Path $backup -Force | Out-Null
|
||||
Copy-Item -LiteralPath $target -Destination (Join-Path $backup $item.target) -ErrorAction Stop
|
||||
}
|
||||
Copy-Item -LiteralPath (Join-Path $root $item.source) -Destination $target -ErrorAction Stop
|
||||
}
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') verify --deployed
|
||||
if ($LASTEXITCODE -ne 0) { throw '部署校验失败,禁止启动;旧程序备份保留在 out/deployment-history' }
|
||||
Write-Output '最新编译包已部署到 yunx-test;配置、证书、数据库未被构建过程覆盖。'
|
||||
} finally {
|
||||
if ($lock) { $lock.Dispose() }
|
||||
}
|
||||
+5
-5
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'
|
||||
import { buildPlan, root, targets } from './build-plugins.mjs'
|
||||
|
||||
export function packagePlan(target) {
|
||||
const pluginPlan = buildPlan({ target })
|
||||
buildPlan({ target })
|
||||
const [goos, goarch] = target.split('_')
|
||||
const extension = goos === 'windows' ? '.exe' : ''
|
||||
const suffix = `${goos === 'darwin' ? 'mac' : goos}_${goarch}${extension}`
|
||||
@@ -13,9 +13,7 @@ export function packagePlan(target) {
|
||||
...['smail', 'smail-admin'].map(name => ({
|
||||
source: path.join(root, 'out', 'backend', `${name}_${suffix}`),
|
||||
target: path.join(directory, `${name}${extension}`)
|
||||
})),
|
||||
...pluginPlan.map(item => ({ source: item.output, target: path.join(directory, 'plugins', path.basename(item.output)) })),
|
||||
{ source: path.join(root, 'README.md'), target: path.join(directory, 'README.md') }
|
||||
}))
|
||||
]
|
||||
}
|
||||
|
||||
@@ -28,7 +26,9 @@ export async function packageRelease(selectedTargets = targets) {
|
||||
await copyFile(item.source, item.target)
|
||||
}
|
||||
for (const target of selectedTargets) {
|
||||
await writeFile(path.join(root, 'out', 'package', target, 'release.json'), JSON.stringify({
|
||||
for (const name of ['config', 'ssl', 'data', 'log']) await mkdir(path.join(root, 'out', 'package', target, name), { recursive: true })
|
||||
await mkdir(path.join(root, 'out', 'release-receipts'), { recursive: true })
|
||||
await writeFile(path.join(root, 'out', 'release-receipts', `${target}.json`), JSON.stringify({
|
||||
version: process.env.SMAIL_VERSION || 'dev', gitHash: process.env.GIT_HASH || '',
|
||||
protocolVersion: 1, target, plugins: buildPlan({ target }).map(item => item.id), createdAt: new Date().toISOString()
|
||||
}, null, 2) + '\n')
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const sourceRoot = fileURLToPath(new URL('../', import.meta.url))
|
||||
export const runtimeRoot = path.join(sourceRoot, 'yunx-test')
|
||||
|
||||
export function assertDeploymentLayout(root = runtimeRoot) {
|
||||
const allowed = new Set(['config', 'data', 'ssl', 'log', 'smail', 'smail-admin', 'smail.exe', 'smail-admin.exe'])
|
||||
for (const item of readdirSync(root, { withFileTypes: true })) {
|
||||
if (!allowed.has(item.name) || item.isSymbolicLink()) throw new Error('部署根目录包含额外项目或链接')
|
||||
}
|
||||
const names = ['config.json', 'smtp.json', 'email.json', 'ssl.json', 'plugins.json']
|
||||
if (JSON.stringify(readdirSync(path.join(root, 'config')).sort()) !== JSON.stringify(names.sort())) {
|
||||
throw new Error('config 只能包含指定的五个配置文件')
|
||||
}
|
||||
const config = JSON.parse(readFileSync(resolveRuntimeFile(root, 'config/config.json'), 'utf8'))
|
||||
for (const name of ['smtp', 'email', 'ssl', 'plugins']) {
|
||||
resolveRuntimeFile(root, `config/${name}.json`)
|
||||
}
|
||||
if (config.setupState === 'ready') {
|
||||
for (const name of ['credential.key', 'external-email-encryption.key', 'external-email-fingerprint.key']) {
|
||||
resolveRuntimeFile(root, `ssl/${name}`)
|
||||
}
|
||||
if (config.database?.type === 'sqlite') resolveRuntimeFile(root, `data/${config.database.localRef}`)
|
||||
}
|
||||
const ssl = JSON.parse(readFileSync(resolveRuntimeFile(root, 'config/ssl.json'), 'utf8')).tls
|
||||
for (const reference of [ssl?.certificateRef, ssl?.privateKeyRef]) {
|
||||
if (!reference?.startsWith('ssl/')) throw new Error('证书引用尚未迁移到 ssl,拒绝使用旧目录启动')
|
||||
resolveRuntimeFile(root, reference)
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
export function resolveRuntimeFile(root, reference) {
|
||||
if (typeof reference !== 'string' || !reference || path.isAbsolute(reference)) {
|
||||
throw new Error('运行文件必须使用部署目录内的相对引用')
|
||||
}
|
||||
const resolvedRoot = realpathSync(root)
|
||||
const absolute = path.resolve(root, reference)
|
||||
const info = lstatSync(absolute)
|
||||
if (!info.isFile() || info.isSymbolicLink()) throw new Error('运行文件必须是普通文件')
|
||||
const target = realpathSync(absolute)
|
||||
const relative = path.relative(resolvedRoot, target)
|
||||
if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
|
||||
throw new Error('运行文件不能越过部署目录')
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// 仅供 Node/Vite 服务端读取,不能把包含凭据的配置对象暴露给浏览器。
|
||||
export function readDevelopmentRuntime(root = runtimeRoot) {
|
||||
const read = name => JSON.parse(readFileSync(resolveRuntimeFile(root, `config/${name}.json`), 'utf8'))
|
||||
const config = read('config')
|
||||
const ssl = read('ssl')
|
||||
const webDomain = config.domains?.web
|
||||
if (typeof webDomain !== 'string' || !/^[a-z0-9.-]+(?::\d+)?$/i.test(webDomain)) {
|
||||
throw new Error('请先在 yunx-test/config/config.json 配置有效的 Web 域名')
|
||||
}
|
||||
const certificatePath = resolveRuntimeFile(root, ssl.tls?.certificateRef)
|
||||
const privateKeyPath = resolveRuntimeFile(root, ssl.tls?.privateKeyRef)
|
||||
return {
|
||||
origin: `https://${webDomain}`,
|
||||
certificatePath,
|
||||
privateKeyPath,
|
||||
generation: config.generation
|
||||
}
|
||||
}
|
||||
+33
-17
@@ -1,11 +1,12 @@
|
||||
param(
|
||||
[ValidateSet('backend', 'frontend')][string]$Service = 'backend',
|
||||
[switch]$SkipBuild
|
||||
[ValidateSet('backend', 'frontend', 'all')][string]$Service = 'all',
|
||||
[switch]$Restart
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$logs = Join-Path $root 'test-log\runtime'
|
||||
$runtime = Join-Path $root 'yunx-test'
|
||||
$logs = Join-Path $runtime 'log'
|
||||
New-Item -ItemType Directory -Path $logs -Force | Out-Null
|
||||
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss-fff'
|
||||
$previousRoot = $env:SMAIL_ROOT
|
||||
@@ -13,8 +14,21 @@ $previousHTTPPortOverride = $env:SMAIL_HTTP_PORT_OVERRIDE
|
||||
$previousHTTPTLSModeOverride = $env:SMAIL_HTTP_TLS_MODE_OVERRIDE
|
||||
$previousSetupPort = $env:setup_port
|
||||
try {
|
||||
if ($Service -eq 'backend') {
|
||||
$binary = Join-Path $root 'out\backend\smail-dev.exe'
|
||||
& node (Join-Path $PSScriptRoot 'check-runtime.mjs')
|
||||
if ($LASTEXITCODE -ne 0) { throw '请先完成 yunx-test 运行数据迁移,不能自动创建另一份账号库' }
|
||||
if ($Restart) {
|
||||
# 只停止本部署的已确认进程,不能按进程名称或端口盲目结束其他项目。
|
||||
$expected = Join-Path $runtime 'smail.exe'
|
||||
$vitePath = Join-Path $root 'frontend\node_modules\vite\bin\vite.js'
|
||||
$processes = Get-CimInstance Win32_Process | Where-Object {
|
||||
($Service -in @('backend', 'all') -and $_.ExecutablePath -eq $expected) -or
|
||||
($Service -in @('frontend', 'all') -and $_.Name -eq 'node.exe' -and $_.CommandLine.Contains($vitePath))
|
||||
}
|
||||
foreach ($item in $processes) { Stop-Process -Id $item.ProcessId -ErrorAction Stop }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
if ($Service -in @('backend', 'all')) {
|
||||
$binary = Join-Path $runtime 'smail.exe'
|
||||
if (Get-NetTCPConnection -State Listen -LocalPort 5201 -ErrorAction SilentlyContinue) { throw '5201 端口已占用,请先确认并停止旧后端' }
|
||||
$running = Get-CimInstance Win32_Process | Where-Object {
|
||||
$_.ExecutablePath -and $_.ExecutablePath -eq $binary
|
||||
@@ -27,32 +41,31 @@ try {
|
||||
throw 'backend/config 中仍有运行文件,请先停止后端并完成根目录 config 迁移'
|
||||
}
|
||||
}
|
||||
# 默认先编译当前工作区,不再把历史 smail-dev.exe 当成最新后端。
|
||||
# 不编译前端,保留 Vite 热更新;缺少首次嵌入资源时要求显式完整构建。
|
||||
if (-not $SkipBuild) {
|
||||
& (Join-Path $PSScriptRoot 'build.ps1') -SkipFrontend
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw '请先运行 deploy/build.ps1 编译后端' }
|
||||
& (Join-Path $PSScriptRoot 'deploy-runtime.ps1')
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') verify --deployed
|
||||
if ($LASTEXITCODE -ne 0) { throw '运行包不是最新编译结果,拒绝启动' }
|
||||
# SMAIL_ROOT 是 config 的父目录,不能指向 config 本身或编译输出目录。
|
||||
$env:SMAIL_ROOT = $root
|
||||
$env:SMAIL_ROOT = $runtime
|
||||
$env:SMAIL_HTTP_PORT_OVERRIDE = '5201'
|
||||
$env:SMAIL_HTTP_TLS_MODE_OVERRIDE = 'proxy'
|
||||
$env:setup_port = '5201'
|
||||
$arguments = @('--dev-disable-admin-reset')
|
||||
Write-Output '开发启动:后端 API 仅监听 5201;沿用 config/config.json 和现有数据库;明确停用管理员恢复通道,不请求权限提升。'
|
||||
if ($SkipBuild) { Write-Warning '已跳过编译,请自行确认二进制与当前源码一致。' }
|
||||
# 插件从 out/plugins 加载;SMAIL_ROOT 下 config 保存配置,data 保存账号、密钥和证书。
|
||||
Write-Output '开发启动:后端监听 5201,运行根目录固定为 yunx-test;明确停用管理员恢复通道,不请求权限提升。'
|
||||
# 插件产物仍须核验;插件打包迁移未完成时不能省略这些构建输入。
|
||||
foreach ($name in @('spam_block.exe', 'pmail_telegram_push.exe', 'wechat_push.exe')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $root "out\plugins\$name") -PathType Leaf)) {
|
||||
throw '内置插件产物不完整,请先运行 deploy/build.ps1'
|
||||
}
|
||||
}
|
||||
$workingDirectory = Join-Path $root 'out'
|
||||
$workingDirectory = $runtime
|
||||
} else {
|
||||
foreach ($port in @(80, 443)) {
|
||||
if (Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction SilentlyContinue) { throw "$port 端口已占用,请先确认并停止旧前端或旧后端" }
|
||||
}
|
||||
$binary = (Get-Command node -ErrorAction Stop).Source
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') verify --deployed
|
||||
if ($LASTEXITCODE -ne 0) { throw '请先使用 -Service all 或 backend 重新编译部署,前端不能搭配旧后端启动' }
|
||||
$env:SMAIL_ROOT = $runtime
|
||||
$vite = Join-Path $root 'frontend\node_modules\vite\bin\vite.js'
|
||||
if (-not (Test-Path -LiteralPath $vite)) { throw '请先安装 frontend 的依赖' }
|
||||
$arguments = @(('"{0}"' -f $vite), '--host', '127.0.0.1', '--port', '443', '--strictPort')
|
||||
@@ -65,7 +78,7 @@ try {
|
||||
Start-Sleep -Seconds 3
|
||||
$process.Refresh()
|
||||
if ($process.HasExited) { throw "服务启动失败;标准输出:$stdout;错误日志:$stderr" }
|
||||
Write-Output "$Service 已启动,进程编号:$($process.Id);日志目录:test-log/runtime"
|
||||
Write-Output "$Service 已启动,进程编号:$($process.Id);日志目录:yunx-test/log"
|
||||
Write-Output "运行文件:$binary;标准输出:$stdout;错误日志:$stderr"
|
||||
} finally {
|
||||
$env:SMAIL_ROOT = $previousRoot
|
||||
@@ -73,3 +86,6 @@ try {
|
||||
$env:SMAIL_HTTP_TLS_MODE_OVERRIDE = $previousHTTPTLSModeOverride
|
||||
$env:setup_port = $previousSetupPort
|
||||
}
|
||||
if ($Service -eq 'all') {
|
||||
& $PSCommandPath -Service frontend
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
param([switch]$Restart)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$runtime = Join-Path $root 'yunx-test'
|
||||
$binary = Join-Path $runtime 'smail.exe'
|
||||
& node (Join-Path $PSScriptRoot 'check-runtime.mjs')
|
||||
if ($LASTEXITCODE -ne 0) { throw '模拟部署目录未准备完成' }
|
||||
if ($Restart) {
|
||||
Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq $binary } | ForEach-Object {
|
||||
Stop-Process -Id $_.ProcessId -ErrorAction Stop
|
||||
}
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
& (Join-Path $PSScriptRoot 'deploy-runtime.ps1')
|
||||
& node (Join-Path $PSScriptRoot 'build-state.mjs') verify --deployed
|
||||
if ($LASTEXITCODE -ne 0) { throw '运行包不是最新源码的构建结果' }
|
||||
$previous = @{}
|
||||
foreach ($name in @('SMAIL_ROOT', 'SMAIL_HTTP_PORT_OVERRIDE', 'SMAIL_HTTP_TLS_MODE_OVERRIDE', 'setup_port', 'SMAIL_DEV_DISABLE_ADMIN_RESET')) {
|
||||
$previous[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
|
||||
[Environment]::SetEnvironmentVariable($name, $null, 'Process')
|
||||
}
|
||||
try {
|
||||
$env:SMAIL_ROOT = $runtime
|
||||
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss-fff'
|
||||
$process = Start-Process -FilePath $binary -WorkingDirectory $runtime -WindowStyle Hidden -PassThru `
|
||||
-RedirectStandardOutput (Join-Path $runtime "log\production-$stamp.stdout.log") `
|
||||
-RedirectStandardError (Join-Path $runtime "log\production-$stamp.stderr.log")
|
||||
Start-Sleep -Seconds 3
|
||||
$process.Refresh()
|
||||
if ($process.HasExited) { throw '生产模拟启动失败,请检查 yunx-test/log;不会自动豁免管理员恢复通道保护' }
|
||||
Write-Output "生产模拟已启动:$($process.Id),使用嵌入前端和 yunx-test 配置,管理员恢复通道保持保护。"
|
||||
} finally {
|
||||
foreach ($name in $previous.Keys) { [Environment]::SetEnvironmentVariable($name, $previous[$name], 'Process') }
|
||||
}
|
||||
Reference in new issue
Block a user