#!/usr/bin/env node /** * nats-server 바이너리를 현재 플랫폼/아키텍처에 맞게 공식 릴리스에서 내려받아 * 프로젝트 bin/ 에 배치한다. * * node scripts/fetch-nats-server.js # 없으면 다운로드 * node scripts/fetch-nats-server.js --force # 항상 재다운로드 * * 임베디드 NATS 모드(bada-nats-manager._startEmbeddedServer)가 bin/nats-server 를 * 우선 탐색하므로, 이 스크립트 실행 후 Swarm 상호 학습이 실제 분산 NATS 경유로 동작한다. * (멀티프로세스 검증: test/e2e-swarm-multiprocess.test.js) */ const fs = require('fs'); const path = require('path'); const os = require('os'); const https = require('https'); const { execFileSync } = require('child_process'); const VERSION = process.env.NATS_SERVER_VERSION || 'v2.10.22'; const BIN_DIR = path.join(__dirname, '..', 'bin'); function resolveTarget() { const platformMap = { darwin: 'darwin', linux: 'linux', win32: 'windows' }; const archMap = { x64: 'amd64', arm64: 'arm64' }; const goOs = platformMap[process.platform]; const goArch = archMap[process.arch]; if (!goOs || !goArch) { throw new Error(`Unsupported platform/arch: ${process.platform}/${process.arch}`); } const isWin = goOs === 'windows'; const ext = isWin ? 'zip' : 'tar.gz'; const stem = `nats-server-${VERSION}-${goOs}-${goArch}`; const url = `https://github.com/nats-io/nats-server/releases/download/${VERSION}/${stem}.${ext}`; const binaryName = isWin ? 'nats-server.exe' : 'nats-server'; return { url, stem, ext, isWin, binaryName }; } function download(url, dest, redirects = 0) { return new Promise((resolve, reject) => { if (redirects > 5) return reject(new Error('Too many redirects')); https.get(url, { headers: { 'User-Agent': 'bada-fetch-nats' } }, (res) => { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { res.resume(); return resolve(download(res.headers.location, dest, redirects + 1)); } if (res.statusCode !== 200) { res.resume(); return reject(new Error(`Download failed (${res.statusCode}) for ${url}`)); } const file = fs.createWriteStream(dest); res.pipe(file); file.on('finish', () => file.close(resolve)); file.on('error', reject); }).on('error', reject); }); } async function main() { const force = process.argv.includes('--force'); const { url, stem, isWin, binaryName } = resolveTarget(); const finalPath = path.join(BIN_DIR, binaryName); if (fs.existsSync(finalPath) && !force) { console.log(`[fetch-nats] Already present: ${finalPath} (use --force to re-download)`); return; } fs.mkdirSync(BIN_DIR, { recursive: true }); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nats-dl-')); const archivePath = path.join(tmpDir, `${stem}.${isWin ? 'zip' : 'tar.gz'}`); console.log(`[fetch-nats] Downloading ${url}`); await download(url, archivePath); console.log('[fetch-nats] Extracting...'); if (isWin) { // PowerShell Expand-Archive (Windows 기본 제공) execFileSync('powershell', ['-NoProfile', '-Command', `Expand-Archive -Path '${archivePath}' -DestinationPath '${tmpDir}' -Force`], { stdio: 'inherit' }); } else { execFileSync('tar', ['-xzf', archivePath, '-C', tmpDir], { stdio: 'inherit' }); } const extractedBinary = path.join(tmpDir, stem, binaryName); if (!fs.existsSync(extractedBinary)) { throw new Error(`Extracted binary not found at ${extractedBinary}`); } fs.copyFileSync(extractedBinary, finalPath); if (!isWin) fs.chmodSync(finalPath, 0o755); // 동작 확인 try { const out = execFileSync(finalPath, ['--version'], { encoding: 'utf-8' }).trim(); console.log(`[fetch-nats] Installed: ${finalPath} (${out})`); } catch (e) { console.log(`[fetch-nats] Installed: ${finalPath} (version check skipped: ${e.message})`); } try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (_) { /* best-effort cleanup */ } } main().catch((err) => { console.error(`[fetch-nats] FAILED: ${err.message}`); console.error('[fetch-nats] Swarm은 nats-server 없이 메모리 fallback으로 계속 동작합니다.'); process.exit(1); });