import { createHash } from 'node:crypto'; import { readFile, readdir } from 'node:fs/promises'; import { join, relative, sep } from 'node:path'; const repositoryRoot = process.cwd(); const target = requiredNacosTarget('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(`配置路径必须是 /${group}/.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}`); } } 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); } } return files.sort(); } 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'); }