重整三环境发布与回退工作流
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s

This commit is contained in:
2026-10-15 11:26:28 +08:00
parent 28510db233
commit ac84f8f206
22 changed files with 819 additions and 496 deletions
+65 -123
View File
@@ -1,133 +1,75 @@
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
import { join, relative, sep } from 'node:path';
import { atomicWrite, envName, listYamlFiles, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
const repositoryRoot = process.cwd();
const target = requiredNacosTarget('NACOS_ENVIRONMENT');
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const configRoot = join(repositoryRoot, 'nacos', 'namespaces', target.environment);
const configFiles = await collectYamlFiles(configRoot);
if (configFiles.length === 0) {
throw new Error(`nacos/namespaces/${target.environment} 下没有可发布的 YAML 配置`);
}
for (const destination of target.destinations) {
await publishDestination(destination, configFiles);
}
async function publishDestination(destination, files) {
const nacosUrls = requiredEnvironment(`${destination.prefix}_URLS`).split(',').map((value) => normalizeNacosBaseUrl(value.trim())).filter(Boolean);
if (nacosUrls.length < destination.verificationNodeCount) {
throw new Error(`${destination.name} 至少需要 ${destination.verificationNodeCount} 个 Nacos 地址用于发布校验`);
}
const username = requiredEnvironment(`${destination.prefix}_USERNAME`);
const password = requiredEnvironment(`${destination.prefix}_PASSWORD`);
const token = await login(nacosUrls[0], username, password);
for (const filePath of files) {
const root = join(repositoryRoot, 'nacos', 'namespaces', destination.environment);
const relativePath = relative(root, filePath).split(sep);
if (relativePath.length !== 3 || relativePath[1] !== group) {
throw new Error(`配置路径必须是 <namespace>/${group}/<dataId>.yaml:${relativePath.join('/')}`);
}
const [namespace, , dataId] = relativePath;
const content = await readFile(filePath, 'utf8');
await publish(nacosUrls[0], token, namespace, group, dataId, content);
await verify(nacosUrls.slice(0, destination.verificationNodeCount), token, namespace, group, dataId, content);
console.log(`已发布并校验 ${destination.name}/${namespace}/${group}/${dataId}`);
const root = process.cwd();
const configRoot = join(root, 'nacos', 'namespaces', environment);
const files = await listYamlFiles(configRoot);
if (!files.length) throw new Error(`没有可发布的 ${environment} YAML 配置`);
const destinations = (environment === 'prod' ? [['NACOS_PROD', 'prod-center1', 2], ['NACOS_DR', 'prod-center2', 1]] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment, 1]]).map(([prefix, id, nodes]) => {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (urls.length < nodes) throw new Error(`${prefix} Nacos 地址不足`);
return { prefix, id, urls, token: null, nodes };
});
for (const destination of destinations) destination.token = await login(destination.urls[0], required(`${destination.prefix}_USERNAME`), required(`${destination.prefix}_PASSWORD`));
const groupName = group;
const runId = process.env.GITHUB_RUN_ID || 'manual';
const commitSha = process.env.GITHUB_SHA || 'unknown';
const recordRoot = recordsRoot(environment);
const snapshotId = `${new Date().toISOString().replaceAll(/[:.]/g, '-')}-${runId}`;
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${runId}`;
const snapshot = snapshotRoot(environment, snapshotId);
const activeSnapshotId = `active-${releaseId}`;
const activeSnapshot = snapshotRoot(environment, activeSnapshotId);
await mkdir(snapshot, { recursive: true });
await mkdir(activeSnapshot, { recursive: true });
const entries = [];
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
const entry = { namespace, dataId, sha256: sha256(content), previousSha256: {}, previousExists: {} };
entries.push(entry);
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`);
if (!response.ok && response.status !== 404) throw new Error(`读取当前 Nacos 配置失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
const oldContent = await response.text();
entry.previousExists[destination.id] = response.status !== 404;
entry.previousSha256[destination.id] = sha256(oldContent);
await atomicWrite(join(snapshot, destination.id, namespace, groupName, dataId), oldContent);
await atomicWrite(join(activeSnapshot, destination.id, namespace, groupName, dataId), content);
}
}
function requiredEnvironment(name) {
const value = process.env[name];
if (!value) {
throw new Error(`缺少环境变量 ${name}`);
}
return value;
}
function normalizeNacosBaseUrl(value) {
return value.replace(/\/+$/, '').replace(/\/nacos$/, '');
}
function requiredNacosTarget(name) {
const value = requiredEnvironment(name);
const destinations = {
dev: [{ name: 'dev', environment: 'dev', prefix: 'NACOS_DEV', verificationNodeCount: 1 }],
sit: [{ name: 'sit', environment: 'sit', prefix: 'NACOS_SIT', verificationNodeCount: 1 }],
'prod-center1': [{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }],
'prod-center2': [{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }],
'prod-both': [
{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 },
{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 },
],
}[value];
if (!destinations) {
throw new Error(`不支持的 Nacos 发布目标:${value}`);
}
return { environment: destinations[0].environment, destinations };
}
async function collectYamlFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const entryPath = join(directory, entry.name);
if (entry.isDirectory()) {
files.push(...await collectYamlFiles(entryPath));
} else if (entry.isFile() && entry.name.endsWith('.yaml')) {
files.push(entryPath);
await writeJson(join(recordRoot, 'pending-nacos.json'), { environment, snapshotId, activeSnapshotId, commitSha, runId, releaseId, files: entries, createdAt: new Date().toISOString() });
try {
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(destination.token)}`, { method: 'POST', body: new URLSearchParams({ dataId, group: groupName, tenant: namespace, type: 'yaml', content }) });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') throw new Error(`发布失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
await verify(destination, namespace, dataId, content);
}
}
return files.sort();
const previous = await optionalJson(join(recordRoot, 'latest-success-nacos.json'));
const record = { environment, status: 'success', commitSha, runId, releaseId, snapshotId, activeSnapshotId, previousReleaseId: previous?.releaseId || null, files: entries, publishedAt: new Date().toISOString() };
await writeJson(join(recordRoot, 'latest-success-nacos.json'), record);
await writeJson(join(recordRoot, 'nacos', `${releaseId}.json`), record);
await rm(join(recordRoot, 'pending-nacos.json'), { force: true });
console.log(`已发布并校验 ${environment} Nacos,回退快照 ${snapshotId}`);
} catch (error) {
console.error(error.message);
console.error(`AUTO_ROLLBACK_SNAPSHOT_ID=${snapshotId}`);
throw error;
}
async function login(baseUrl, user, secret) {
const body = new URLSearchParams({ username: user, password: secret });
const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body });
if (!response.ok) {
throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`);
}
const payload = await response.json();
if (!payload.accessToken) {
throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`);
}
return payload.accessToken;
}
async function publish(baseUrl, token, namespace, configGroup, dataId, content) {
const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content });
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') {
throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`);
}
}
async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) {
const expectedHash = sha256(expectedContent);
for (const baseUrl of baseUrls) {
const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace });
let lastStatus = 0;
let lastContent = '';
for (let attempt = 1; attempt <= 3; attempt += 1) {
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`);
const content = await response.text();
lastStatus = response.status;
lastContent = content;
if (response.ok && sha256(content) === expectedHash) {
break;
}
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
if (lastStatus !== 200 || sha256(lastContent) !== expectedHash) {
throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${lastStatus} ${lastContent.slice(0, 200)}`);
}
}
}
function sha256(value) {
return createHash('sha256').update(value, 'utf8').digest('hex');
}
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
function info(file) { const parts = relative(configRoot, file).split(sep); if (parts.length !== 2) throw new Error(`配置路径无效:${file}`); return { namespace: parts[0], dataId: parts[1] }; }
async function optionalJson(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }
async function verify(destination, namespace, dataId, expected) { const expectedHash = sha256(expected); for (const base of destination.urls) { let status = 0; let content = ''; for (let attempt = 0; attempt < 3; attempt += 1) { const response = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); status = response.status; content = await response.text(); if (status === 200 && sha256(content) === expectedHash) break; await new Promise((resolve) => setTimeout(resolve, 1000)); } if (status !== 200 || sha256(content) !== expectedHash) throw new Error(`Nacos 校验失败:${destination.prefix}/${base}/${namespace}/${dataId}`); } }