This commit is contained in:
2026-09-29 18:47:41 +08:00
parent 2bf4353b1b
commit a3005d1c02
22 changed files with 147 additions and 669 deletions
-150
View File
@@ -1,150 +0,0 @@
#!/usr/bin/env sh
set -eu
if [ "$#" -ne 4 ]; then
echo "用法: $0 <服务名> <镜像仓库> <镜像标签> <Compose 文件>" >&2
exit 2
fi
SERVICE="$1"
IMAGE_REPOSITORY="$2"
IMAGE_TAG="$3"
COMPOSE_FILE="$4"
IMAGE="$IMAGE_REPOSITORY:$IMAGE_TAG"
REGISTRY_HOST="${IMAGE_REPOSITORY%%/*}"
SSH_TARGET="${TARGET_SSH_TARGET:?TARGET_SSH_TARGET 未设置}"
SSH_KEY="${TARGET_SSH_KEY:?TARGET_SSH_KEY 未设置}"
SSH_KNOWN_HOSTS="${TARGET_SSH_KNOWN_HOSTS:?TARGET_SSH_KNOWN_HOSTS 未设置}"
REMOTE_DIR="${TARGET_DEPLOY_DIR:?TARGET_DEPLOY_DIR 未设置}"
: "${REGISTRY_USER:?REGISTRY_USER 未设置}"
: "${REGISTRY_PASSWORD:?REGISTRY_PASSWORD 未设置}"
run_ssh() {
ssh -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$SSH_TARGET" "$@"
}
run_scp() {
scp -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$@"
}
run_ssh install -d -m 750 "$REMOTE_DIR"
REMOTE_COMPOSE="$REMOTE_DIR/docker-compose.$SERVICE.yml"
run_scp "$COMPOSE_FILE" "$SSH_TARGET:$REMOTE_COMPOSE.tmp"
run_ssh sh -s -- "$REMOTE_COMPOSE.tmp" "$REMOTE_COMPOSE" <<'REMOTE_PREPARE'
set -eu
compose_tmp="$1"
compose_target="$2"
chmod 644 "$compose_tmp"
mv -f "$compose_tmp" "$compose_target"
REMOTE_PREPARE
printf '%s' "$REGISTRY_PASSWORD" | run_ssh docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
trap 'run_ssh docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true' EXIT HUP INT TERM
run_ssh docker pull "$IMAGE"
run_ssh sh -s -- "$REMOTE_DIR" "$SERVICE" "$IMAGE_REPOSITORY" "$IMAGE_TAG" <<'REMOTE_DEPLOY'
set -eu
remote_dir="$1"
service="$2"
image_repository="$3"
image_tag="$4"
compose_file="docker-compose.$service.yml"
project_name="firstleg-prod-$service"
cd "$remote_dir"
export IMAGE_REPOSITORY="$image_repository" IMAGE_TAG="$image_tag"
compose() {
docker compose --project-name "$project_name" -f "$compose_file" "$@"
}
case "$service" in
admin-web)
base_port=9001
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-admin-web.conf
legacy_container=firstleg-prod-admin-web
;;
client-web)
base_port=9002
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-client-web.conf
legacy_container=firstleg-prod-client-web
;;
*) echo "不支持蓝绿部署的前端服务: $service" >&2; exit 2 ;;
esac
state_root=/data/firstleg/deploy/blue-green-state
state_file="$state_root/frontend-$service.active"
routing_network=firstleg-production-routing
mkdir -p "$state_root"
chmod 750 "$state_root"
docker network inspect "$routing_network" >/dev/null 2>&1 || docker network create "$routing_network" >/dev/null
for pair in gateway-active:firstleg-production-gateway gateway-overseas-active:firstleg-production-gateway-overseas; do
alias_name="${pair%%:*}"
container="${pair#*:}"
if docker inspect "$container" >/dev/null 2>&1; then
docker network inspect "$routing_network" --format '{{json .Containers}}' | grep -q "\"$container\"" \
|| docker network connect --alias "$alias_name" "$routing_network" "$container"
fi
done
active_slot=""
active_container=""
active_port=""
if [ -s "$state_file" ]; then
IFS='|' read -r active_slot active_container active_port active_image < "$state_file"
elif docker inspect "$legacy_container" >/dev/null 2>&1; then
active_slot=legacy
active_container="$legacy_container"
active_port="$base_port"
fi
if [ "$active_slot" = blue ]; then target_slot=green; else target_slot=blue; fi
[ "$active_slot" = legacy ] && target_slot=green
if [ "$target_slot" = blue ]; then target_port=$((base_port + 20000)); else target_port=$((base_port + 10000)); fi
candidate="${legacy_container}-${target_slot}"
docker rm -f "$candidate" >/dev/null 2>&1 || true
if ! compose run -d --no-deps --name "$candidate" \
-p "127.0.0.1:$target_port:80" "$service" >/dev/null; then
docker rm -f "$candidate" >/dev/null 2>&1 || true
exit 1
fi
healthy=false
elapsed=0
while [ "$elapsed" -lt 120 ]; do
if docker exec "$candidate" wget -qO- http://127.0.0.1/healthz >/dev/null 2>&1; then
healthy=true
break
fi
sleep 2
elapsed=$((elapsed + 2))
done
if [ "$healthy" != true ]; then
docker logs --tail 100 "$candidate" >&2 || true
docker rm -f "$candidate" >/dev/null 2>&1 || true
exit 1
fi
backup="$nginx_config.blue-green-backup"
cp -f "$nginx_config" "$backup"
if ! sed -i "s#127\.0\.0\.1:${active_port:-$base_port}#127.0.0.1:$target_port#g" "$nginx_config" \
|| cmp -s "$nginx_config" "$backup" || ! nginx -t || ! nginx -s reload; then
cp -f "$backup" "$nginx_config"
nginx -t && nginx -s reload || true
docker rm -f "$candidate" >/dev/null 2>&1 || true
exit 1
fi
rm -f "$backup"
if [ -n "$active_container" ] && docker inspect "$active_container" >/dev/null 2>&1; then
docker stop --time 30 "$active_container" >/dev/null
docker rm "$active_container" >/dev/null
fi
printf '%s|%s|%s|%s\n' "$target_slot" "$candidate" "$target_port" "$image_repository:$image_tag" > "$state_file.tmp"
chmod 640 "$state_file.tmp"
mv -f "$state_file.tmp" "$state_file"
echo "生产前端蓝绿部署成功: service=$service slot=$target_slot port=$target_port image=$image_repository:$image_tag"
REMOTE_DEPLOY
@@ -1,4 +1,3 @@
import { existsSync, readFileSync } from 'node:fs'
import { spawnSync } from 'node:child_process'
function option(name) {
@@ -15,22 +14,13 @@ function normalizeOrigin(value, name) {
return url.origin
}
function acceptancePassword() {
if (process.env.CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD) return process.env.CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD
const file = 'C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env'
if (!existsSync(file)) return ''
const match = readFileSync(file, 'utf8').match(/^CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD=(.*)$/m)
return match?.[1]?.trim() || ''
}
const environment = option('--environment')
if (environment !== 'development') throw new Error('本入口仅允许显式指定 --environment development')
const gateway = normalizeOrigin(option('--gateway') || process.env.ADMIN_DEVELOPMENT_GATEWAY, '--gateway')
const overseasGateway = normalizeOrigin(option('--overseas-gateway') || process.env.ADMIN_DEVELOPMENT_OVERSEAS_GATEWAY, '--overseas-gateway')
const password = acceptancePassword()
if (!password) throw new Error('缺少 CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD 或本机开发验收凭据文件')
if (environment !== 'test') throw new Error('本入口仅允许显式指定 --environment test')
const gateway = normalizeOrigin(option('--gateway') || process.env.ADMIN_TEST_GATEWAY, '--gateway')
const password = process.env.CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD
if (!password) throw new Error('缺少 CHONGCHONG_ADMIN_ACCEPTANCE_PASSWORD')
const result = spawnSync('pnpm', ['exec', 'vitest', 'run', '--config', 'vitest.phase4-development.config.ts'], {
const result = spawnSync('pnpm', ['exec', 'vitest', 'run', '--config', 'vitest.phase4-test.config.ts'], {
cwd: process.cwd(),
stdio: 'inherit',
shell: process.platform === 'win32',
@@ -39,10 +29,8 @@ const result = spawnSync('pnpm', ['exec', 'vitest', 'run', '--config', 'vitest.p
ADMIN_PHASE4_LIVE: '1',
ADMIN_ACCEPTANCE_USERNAME: process.env.ADMIN_ACCEPTANCE_USERNAME || 'platform_admin',
ADMIN_ACCEPTANCE_PASSWORD: password,
ADMIN_DEVELOPMENT_GATEWAY: gateway,
ADMIN_DEVELOPMENT_OVERSEAS_GATEWAY: overseasGateway,
ADMIN_TEST_GATEWAY: gateway,
VITE_API_BASE_URL: `${gateway}/api`,
VITE_OVERSEAS_API_BASE_URL: `${overseasGateway}/api`,
},
})
if (result.error) throw result.error
@@ -2,14 +2,14 @@ import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const runner = readFileSync(new URL('./phase4-development-frontend-acceptance.mjs', import.meta.url), 'utf8')
const suite = readFileSync(new URL('./phase4-development-frontend.acceptance.ts', import.meta.url), 'utf8')
const runner = readFileSync(new URL('./phase4-test-frontend-acceptance.mjs', import.meta.url), 'utf8')
const suite = readFileSync(new URL('./phase4-test-frontend.acceptance.ts', import.meta.url), 'utf8')
test('development runner requires an explicit development environment and gateways', () => {
test('test runner requires an explicit test environment and unified gateway', () => {
assert.match(runner, /--environment/)
assert.match(runner, /environment !== 'development'/)
assert.match(runner, /environment !== 'test'/)
assert.match(runner, /--gateway/)
assert.match(runner, /--overseas-gateway/)
assert.doesNotMatch(runner, /--overseas-gateway|VITE_OVERSEAS/)
assert.match(runner, /shell: process\.platform === 'win32'/)
assert.match(runner, /if \(result\.error\) throw result\.error/)
assert.doesNotMatch(runner, /ADMIN_ACCEPTANCE_PASSWORD\s*[:=]\s*['"][^'"]+['"]/)
@@ -17,7 +17,7 @@ test('development runner requires an explicit development environment and gatewa
test('live suite uses production auth clients and domain adapters', () => {
assert.match(suite, /useAuthStore/)
assert.match(suite, /clearOverseasAccessToken/)
assert.match(suite, /refreshAuthenticatedSession/)
assert.match(suite, /createQuote/)
assert.match(suite, /createUsTruckOrder/)
assert.match(suite, /createLocalLooseboardOrder/)
@@ -8,7 +8,7 @@ import { defineComponent, nextTick } from 'vue'
import { mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { http, ApiResponseError } from '@/shared/api/http'
import { clearOverseasAccessToken, overseasHttp } from '@/shared/api/overseasHttp'
import { refreshAuthenticatedSession } from '@/shared/api/http'
import { useAuthStore } from '@/core/auth/auth'
import { listPlatformTenants } from '@/modules/iam/api/platformIam'
import {
@@ -45,7 +45,7 @@ import InventoryTransactionsView from '@/modules/overseas-warehouse/pages/Invent
import PalletsView from '@/modules/overseas-warehouse/pages/PalletsView.vue'
import QueryToolbar from '@/shared/components/QueryToolbar.vue'
type Region = 'domestic' | 'overseas'
type Region = 'unified'
interface TraceStep { region: Region; method: string; path: string; params: unknown; body: unknown; httpStatus: number; code?: string; requestId?: string; traceId?: string; authorization: boolean }
interface CoverageGap { area: string; reason: string }
@@ -150,7 +150,7 @@ async function masterDataLifecycle() {
}
async function cleanupTransport(path: string, customerId: string, version: number) {
await overseasHttp.patch(`${path}/status`, { version, status: 'CANCELLED', remark: `${marker} cleanup` }, { params: { customerId } })
await http.patch(`${path}/status`, { version, status: 'CANCELLED', remark: `${marker} cleanup` }, { params: { customerId } })
}
async function overseasBusinessLifecycle() {
const customers = (await listPlatformTenants({ page: 1, size: 200, status: 'ACTIVE' })).records.filter(item => item.status === 'ACTIVE')
@@ -355,25 +355,25 @@ async function pageRequestCoverage() {
{ occurredDate: ['2098-01-01', '2098-01-02'], customerName: `${marker}-CUSTOMER`, warehouse: `${marker}-WAREHOUSE`, sku: `${marker}-SKU`, businessType: 'ADJUST', businessOrderNo: `${marker}-BUSINESS`, inboundCode: `${marker}-INBOUND`, inboundOrderNo: `${marker}-INBOUND-ORDER`, outboundOrderNo: `${marker}-OUTBOUND` },
{ customerName: `${marker}-CUSTOMER`, destinationWarehouseCode: `${marker}-WAREHOUSE`, skuCode: `${marker}-SKU`, businessType: 'ADJUST', businessOrderNo: `${marker}-BUSINESS`, inboundCode: `${marker}-INBOUND`, inboundOrderNo: `${marker}-INBOUND-ORDER`, outboundOrderNo: `${marker}-OUTBOUND`, occurredFrom: '2098-01-01T00:00:00', occurredTo: '2098-01-02T23:59:59' })
const pallets = await mountPage(PalletsView, 'GET', '/platform/v1/warehouse-admin/pallets')
await exerciseListSearch(pallets, '/platform/v1/warehouse-admin/pallets',
const pallets = await mountPage(PalletsView, 'GET', '/platform/v1/overseas-warehouse-resources/pallets')
await exerciseListSearch(pallets, '/platform/v1/overseas-warehouse-resources/pallets',
{ warehouseId: '', code: `${marker}-PALLET`, type: 'WOOD', status: 'IDLE' },
{ keyword: `${marker}-PALLET`, palletType: 'WOOD', status: 'IDLE' })
}
describe.skipIf(!enabled).sequential('phase4 development frontend acceptance', () => {
describe.skipIf(!enabled).sequential('phase4 test frontend acceptance', () => {
beforeAll(async () => {
Object.defineProperty(window, 'matchMedia', { writable: true, value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) })
globalThis.ResizeObserver = class { observe() {}; unobserve() {}; disconnect() {} }
installTracingAdapter(http, 'domestic'); installTracingAdapter(overseasHttp, 'overseas')
installTracingAdapter(http, 'unified')
const pinia = createPinia(); setActivePinia(pinia)
const auth = useAuthStore(pinia)
await auth.login(process.env.ADMIN_ACCEPTANCE_USERNAME || 'platform_admin', process.env.ADMIN_ACCEPTANCE_PASSWORD || '')
expect(localStorage.getItem('cc-admin-token')).toBeTruthy()
clearOverseasAccessToken()
await refreshAuthenticatedSession()
await listVehicles({ page: 1, size: 1 })
expect(traces.some(item => item.region === 'domestic' && item.path === '/auth/refresh')).toBe(true)
expect(traces.some(item => item.region === 'overseas' && item.authorization)).toBe(true)
expect(traces.some(item => item.region === 'unified' && item.path === '/auth/refresh')).toBe(true)
expect(traces.some(item => item.region === 'unified' && item.authorization)).toBe(true)
})
it('runs marker-owned adapter lifecycles and real page requests', async () => {
await masterDataLifecycle()
@@ -388,7 +388,7 @@ describe.skipIf(!enabled).sequential('phase4 development frontend acceptance', (
const reportDir = resolve(process.cwd(), 'reports')
mkdirSync(reportDir, { recursive: true })
const report = { generatedAt: new Date().toISOString(), marker, summary: { requests: traces.length, coverageGaps: coverageGaps.length }, traces, coverageGaps, createdResources }
const file = resolve(reportDir, `phase4-frontend-development-${marker.replace(/[^A-Za-z0-9-]/g, '')}.json`)
const file = resolve(reportDir, `phase4-frontend-test-${marker.replace(/[^A-Za-z0-9-]/g, '')}.json`)
writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`, 'utf8')
console.info(`PHASE4_FRONTEND_REPORT=${file}`)
})