import assert from 'node:assert/strict' import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { existsSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, join, resolve } from 'node:path' import { spawnSync } from 'node:child_process' import test from 'node:test' const repositoryRoot = resolve(import.meta.dirname, '..') const deployScript = resolve(repositoryRoot, 'deploy/scripts/deploy-built-service.sh') const shell = process.platform === 'win32' ? 'C:/Program Files/Git/bin/bash.exe' : '/bin/sh' const mockDocker = `#!/usr/bin/env sh set -eu printf '%s\\n' "$*" >> "$MOCK_LOG" command="$1" shift case "$command" in login|logout|pull) exit 0 ;; compose) action='' for argument in "$@"; do case "$argument" in ps|up) action="$argument" ;; esac done case "$action" in ps) echo mock-container ;; up) service='' for argument in "$@"; do service="$argument"; done if [ "$IMAGE_TAG" = "\${MOCK_FAIL_UP_TAG:-never}" ]; then exit 3 fi printf '%s\\n' "$IMAGE_REPOSITORY/$service:$IMAGE_TAG" > "$MOCK_CURRENT_IMAGE" if [ "$IMAGE_TAG" = "\${MOCK_FAIL_TAG:-never}" ]; then printf '%s\\n' unhealthy > "$MOCK_HEALTH_STATE" elif [ "$IMAGE_TAG" = "\${MOCK_RESTART_TAG:-never}" ]; then printf '%s\\n' starting > "$MOCK_HEALTH_STATE" printf '%s\\n' restarting > "$MOCK_RUNTIME_STATE" else printf '%s\\n' "\${MOCK_HEALTH_SUCCESS:-healthy}" > "$MOCK_HEALTH_STATE" printf '%s\\n' running > "$MOCK_RUNTIME_STATE" fi ;; esac ;; inspect) case "$2" in *Config.Image*) cat "$MOCK_CURRENT_IMAGE" ;; *State.Health*) cat "$MOCK_HEALTH_STATE" ;; *State.Status*) cat "$MOCK_RUNTIME_STATE" ;; *) exit 2 ;; esac ;; logs) echo 'mock startup failure' ;; *) echo "unexpected docker command: $command $*" >&2 exit 2 ;; esac ` async function runDeployment({ imageTag, failingTag, failingStartTag, restartingTag, allowRollback = true, environment = 'test', service = 'audit-service', missingHealth = false }) { const temporaryDirectory = await mkdtemp(join(tmpdir(), 'firstleg-rollback-')) const mockBin = join(temporaryDirectory, 'bin') const dockerPath = join(mockBin, 'docker') const envFile = join(temporaryDirectory, 'deployment.env') const logFile = join(temporaryDirectory, 'docker.log') const currentImageFile = join(temporaryDirectory, 'current-image') const healthStateFile = join(temporaryDirectory, 'health-state') const runtimeStateFile = join(temporaryDirectory, 'runtime-state') await mkdir(mockBin) await writeFile(dockerPath, mockDocker, 'utf8') await chmod(dockerPath, 0o755) await writeFile(envFile, ['NACOS_SERVER_ADDR=nacos:8848','NACOS_NAMESPACE=test-id','NACOS_USERNAME=fixture','NACOS_PASSWORD=fixture','REDIS_HOST=redis','REDIS_PORT=6379','REDIS_DATABASE=0','REDIS_TOKEN_KEY_PREFIX=baiyue:auth','INTERNAL_SERVICE_TOKEN=fixture','JWT_RSA_JWK_SET=fixture','JWT_CURRENT_KID=fixture','ROCKETMQ_NAME_SERVER=namesrv:9876','MQ_TOPIC_PREFIX=test-','AUDIT_DB_URL=jdbc:mysql://mysql/audit','AUDIT_DB_USERNAME=fixture','AUDIT_DB_PASSWORD=fixture',''].join('\n'), 'utf8') await writeFile(logFile, '', 'utf8') await writeFile(currentImageFile, 'registry.local/group/firstleg/audit-service:oldgood\n', 'utf8') await writeFile(healthStateFile, 'healthy\n', 'utf8') await writeFile(runtimeStateFile, 'running\n', 'utf8') const result = spawnSync(shell, [ deployScript.replaceAll('\\', '/'), environment, 'registry.local/group/firstleg', imageTag, service, envFile.replaceAll('\\', '/') ], { cwd: repositoryRoot, encoding: 'utf8', env: { ...process.env, PATH: `${mockBin}${delimiter}${process.env.PATH ?? ''}`, TARGET_IS_LOCAL: 'true', ALLOW_SAME_CONTRACT_ROLLBACK: String(allowRollback), REGISTRY_USER: 'ci-user', REGISTRY_PASSWORD: 'ci-password', DEPLOY_HEALTH_TIMEOUT_SECONDS: '2', DEPLOY_HEALTH_POLL_SECONDS: '1', MOCK_HEALTH_SUCCESS: missingHealth ? 'no-health:running' : 'healthy', MOCK_LOG: logFile, MOCK_CURRENT_IMAGE: currentImageFile, MOCK_HEALTH_STATE: healthStateFile, MOCK_FAIL_TAG: failingTag ?? 'never', MOCK_FAIL_UP_TAG: failingStartTag ?? 'never', MOCK_RESTART_TAG: restartingTag ?? 'never', MOCK_RUNTIME_STATE: runtimeStateFile } }) const dockerLog = await readFile(logFile, 'utf8') const currentImage = (await readFile(currentImageFile, 'utf8')).trim() await rm(temporaryDirectory, { recursive: true, force: true }) return { ...result, dockerLog, currentImage } } test('successful deployment keeps the new healthy image', async (context) => { if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) const result = await runDeployment({ imageTag: 'newgood' }) assert.equal(result.status, 0, result.stderr) assert.match(result.stdout, /部署前运行镜像: registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.match(result.stdout, /新镜像健康检查通过: registry\.local\/group\/firstleg\/audit-service:newgood/) assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:newgood') }) test('unhealthy deployment restores the previous healthy image and still fails the job', async (context) => { if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) const result = await runDeployment({ imageTag: 'newbad', failingTag: 'newbad' }) const output = `${result.stdout}\n${result.stderr}` assert.equal(result.status, 1, output) assert.match(output, /新镜像健康检查失败: registry\.local\/group\/firstleg\/audit-service:newbad/) assert.match(output, /新镜像容器最近日志(最多 200 行):/) assert.match(output, /mock startup failure/) assert.match(result.dockerLog, /logs --tail 200 mock-container/) assert.match(output, /开始自动回滚到: registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.match(result.dockerLog, /pull registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood') }) test('failed compose start also restores the previous healthy image', async (context) => { if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) const result = await runDeployment({ imageTag: 'newbroken', failingStartTag: 'newbroken' }) const output = `${result.stdout}\n${result.stderr}` assert.equal(result.status, 1, output) assert.match(output, /新镜像启动命令失败: registry\.local\/group\/firstleg\/audit-service:newbroken/) assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood') }) test('restart loops fail fast and restore the previous image', async (context) => { if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`) const result = await runDeployment({ imageTag: 'restarting', restartingTag: 'restarting' }) const output = `${result.stdout}\n${result.stderr}` assert.equal(result.status, 1, output) assert.match(output, /容器未保持运行,立即停止等待: restarting/) assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/) assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood') }) test('architecture switch failure does not roll back one old service', async () => { const result = await runDeployment({imageTag:'newbad', failingTag:'newbad', allowRollback:false}) assert.equal(result.status,1) assert.doesNotMatch(result.dockerLog,/pull .*:oldgood/) assert.match(result.stderr,/Automatic rollback disabled/) }) test('non TEST environments and retired services fail before Docker', async () => { for(const options of [{environment:'production'},{environment:'development'},{service:'event-bridge-service'},{service:'gateway-overseas'}]){ const result=await runDeployment({imageTag:'newgood',...options}) assert.equal(result.status,2) assert.equal(result.dockerLog,'') } }) test('running without HEALTHCHECK cannot be counted as deployed',async()=>{ const result=await runDeployment({imageTag:'newgood',missingHealth:true,allowRollback:false}) assert.equal(result.status,1) assert.match(result.stderr,/Missing HEALTHCHECK/) }) test('SQL initializer rejects absent authorization before any Docker call',()=>{ const result=spawnSync(shell,[resolve(repositoryRoot,'deploy/scripts/initialize-test-databases.sh').replaceAll('\\','/')],{encoding:'utf8',env:{...process.env,ALLOW_TEST_SCHEMA_INITIALIZATION:'false'}}) assert.equal(result.status,2) assert.match(result.stderr,/Explicit TEST SQL authorization required/) })