feat: auto-discovery

This commit is contained in:
2025-08-25 12:05:51 +02:00
parent f72e4ba220
commit 5977a37d6c
8 changed files with 552 additions and 3 deletions

102
test/demo-frontend.js Normal file
View File

@@ -0,0 +1,102 @@
#!/usr/bin/env node
/**
* Demo script for Frontend Discovery Integration
* Shows how the frontend displays primary node information
*/
const http = require('http');
const BASE_URL = 'http://localhost:3001';
function makeRequest(path, method = 'GET') {
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);
});
req.end();
});
}
async function showFrontendIntegration() {
console.log('🚀 Frontend Discovery Integration Demo');
console.log('=====================================');
console.log('This demo shows how the frontend displays primary node information.');
console.log('Open http://localhost:3001 in your browser to see the UI.');
console.log('');
try {
// Check if backend is running
const healthResponse = await makeRequest('/api/health');
console.log('✅ Backend is running');
// Get discovery information
const discoveryResponse = await makeRequest('/api/discovery/nodes');
console.log('\n📡 Discovery Status:');
console.log(` Primary Node: ${discoveryResponse.data.primaryNode || 'None'}`);
console.log(` Total Nodes: ${discoveryResponse.data.totalNodes}`);
console.log(` Client Initialized: ${discoveryResponse.data.clientInitialized}`);
if (discoveryResponse.data.nodes.length > 0) {
console.log('\n🌐 Discovered Nodes:');
discoveryResponse.data.nodes.forEach((node, index) => {
console.log(` ${index + 1}. ${node.ip}:${node.port} (${node.isPrimary ? 'PRIMARY' : 'secondary'})`);
console.log(` Last Seen: ${node.lastSeen}`);
});
}
console.log('\n🎯 Frontend Display:');
console.log(' The frontend will show:');
if (discoveryResponse.data.primaryNode) {
const status = discoveryResponse.data.clientInitialized ? '✅' : '⚠️';
const nodeCount = discoveryResponse.data.totalNodes > 1 ? ` (${discoveryResponse.data.totalNodes} nodes)` : '';
console.log(` ${status} ${discoveryResponse.data.primaryNode}${nodeCount}`);
} else if (discoveryResponse.data.totalNodes > 0) {
const firstNode = discoveryResponse.data.nodes[0];
console.log(` ⚠️ ${firstNode.ip} (No Primary)`);
} else {
console.log(' 🔍 No Nodes Found');
}
console.log('\n💡 To test 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. Send discovery messages: npm run test-discovery broadcast');
console.log(' 4. Watch the primary node display update in real-time');
} catch (error) {
console.error('❌ Error:', error.message);
console.log('\n💡 Make sure the backend is running: npm start');
}
}
// Run the demo
showFrontendIntegration().catch(console.error);

View File

@@ -0,0 +1,137 @@
#!/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);