#!/usr/bin/env node /** * Test script for Random Primary Node Selection * Demonstrates how the random selection works */ const http = require('http'); const BASE_URL = 'http://localhost:3001'; function makeRequest(path, method = 'POST', body = null) { return new Promise((resolve, reject) => { const options = { hostname: 'localhost', port: 3001, path: path, method: method, headers: { 'Content-Type': 'application/json' } }; const req = http.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { try { const jsonData = JSON.parse(data); resolve({ status: res.statusCode, data: jsonData }); } catch (error) { resolve({ status: res.statusCode, data: data }); } }); }); req.on('error', (error) => { reject(error); }); if (body) { req.write(JSON.stringify(body)); } req.end(); }); } async function testRandomSelection() { console.log('🎲 Testing Random Primary Node Selection'); console.log('======================================'); console.log(''); try { // First, check current discovery status console.log('1. Checking current discovery status...'); const discoveryResponse = await makeRequest('/api/discovery/nodes', 'GET'); if (discoveryResponse.status !== 200) { console.log('❌ Failed to get discovery status'); return; } const discovery = discoveryResponse.data; console.log(` Current Primary: ${discovery.primaryNode || 'None'}`); console.log(` Total Nodes: ${discovery.totalNodes}`); console.log(` Client Initialized: ${discovery.clientInitialized}`); if (discovery.nodes.length === 0) { console.log('\n💡 No nodes discovered yet. Send some discovery messages first:'); console.log(' npm run test-discovery broadcast'); return; } console.log('\n2. Testing random primary node selection...'); // Store current primary for comparison const currentPrimary = discovery.primaryNode; const availableNodes = discovery.nodes.map(n => n.ip); console.log(` Available nodes: ${availableNodes.join(', ')}`); console.log(` Current primary: ${currentPrimary}`); // Perform random selection const randomResponse = await makeRequest('/api/discovery/random-primary', 'POST', { timestamp: new Date().toISOString() }); if (randomResponse.status === 200) { const result = randomResponse.data; console.log('\n✅ Random selection successful!'); console.log(` New Primary: ${result.primaryNode}`); console.log(` Previous Primary: ${currentPrimary}`); console.log(` Message: ${result.message}`); console.log(` Total Nodes: ${result.totalNodes}`); console.log(` Client Initialized: ${result.clientInitialized}`); // Verify the change if (result.primaryNode !== currentPrimary) { console.log('\n🎯 Primary node successfully changed!'); } else { console.log('\n⚠️ Primary node remained the same (only one node available)'); } } else { console.log('\n❌ Random selection failed:'); console.log(` Status: ${randomResponse.status}`); console.log(` Error: ${randomResponse.data.error || 'Unknown error'}`); } // Show updated status console.log('\n3. Checking updated discovery status...'); const updatedResponse = await makeRequest('/api/discovery/nodes', 'GET'); if (updatedResponse.status === 200) { const updated = updatedResponse.data; console.log(` Current Primary: ${updated.primaryNode}`); console.log(` Client Base URL: ${updated.clientBaseUrl}`); } console.log('\n💡 To test in the frontend:'); console.log(' 1. Open http://localhost:3001 in your browser'); console.log(' 2. Look at the cluster header for primary node info'); console.log(' 3. Click the 🎲 button to randomly select a new primary node'); console.log(' 4. Watch the display change in real-time'); } catch (error) { console.error('\n❌ Test failed:', error.message); console.log('\n💡 Make sure the backend is running: npm start'); } } // Run the test testRandomSelection().catch(console.error);