Compare commits

...

2 Commits

Author SHA1 Message Date
b4bd459d27 feat: primary node switching in topology graph 2025-10-24 22:44:44 +02:00
fa6777a042 feat: live topology view through websocket updates 2025-10-24 21:54:00 +02:00
8 changed files with 1291 additions and 251 deletions

View File

@@ -0,0 +1,248 @@
# Topology Component WebSocket Integration
## Summary
Enhanced the topology graph component to support real-time node additions and removals via WebSocket connections. The topology view now automatically updates when nodes join or leave the cluster without requiring manual refresh. Existing nodes update their properties (status, labels) smoothly in place without being removed and re-added.
## Changes Made
### 1. TopologyViewModel (`spore-ui/public/scripts/view-models.js`)
Added `setupWebSocketListeners()` method to the TopologyViewModel class:
- **Listens to `clusterUpdate` events**: When cluster membership changes, the topology graph is automatically rebuilt with the new node data
- **Listens to `nodeDiscovery` events**: When a new node is discovered or becomes stale, triggers a topology update
- **Listens to connection status**: Automatically refreshes topology when WebSocket reconnects
- **Async graph updates**: Rebuilds graph data asynchronously from WebSocket data to avoid blocking the UI
Enhanced `buildEnhancedGraphData()` method to preserve node state:
- **Position preservation**: Existing nodes retain their x, y coordinates across updates
- **Velocity preservation**: D3 simulation velocity (vx, vy) is maintained for smooth physics
- **Fixed position preservation**: Manually dragged nodes (fx, fy) stay in place
- **New nodes only**: Only newly discovered nodes get random initial positions
- **Result**: Nodes no longer "jump" or get removed/re-added when their properties update
### 2. TopologyGraphComponent (`spore-ui/public/scripts/components/TopologyGraphComponent.js`)
#### Added WebSocket Setup
- Added `setupWebSocketListeners()` method that calls the view model's WebSocket setup during component initialization
- Integrated into the `initialize()` lifecycle method
#### Improved Dynamic Updates (D3.js Enter/Exit Pattern)
Refactored the graph rendering to use D3's data binding patterns for smooth transitions:
- **`updateLinks()`**: Uses enter/exit pattern to add/remove links with fade transitions
- **`updateNodes()`**: Uses enter/exit pattern to add/remove nodes with fade transitions
- New nodes fade in (300ms transition)
- Removed nodes fade out (300ms transition)
- Existing nodes smoothly update their properties
- **`updateLinkLabels()`**: Dynamically updates link latency labels
- **`updateSimulation()`**: Handles D3 force simulation updates
- Creates new simulation on first render
- Updates existing simulation with new node/link data on subsequent renders
- Maintains smooth physics-based layout
- **`addLegend()`**: Fixed to prevent duplicate legend creation
#### Key Improvements
- **Incremental updates**: Instead of recreating the entire graph, only modified nodes/links are added or removed
- **Smooth animations**: 300ms fade transitions for adding/removing elements
- **In-place updates**: Existing nodes update their properties without being removed/re-added
- **Preserved interactions**: Click, hover, and drag interactions work seamlessly with dynamic updates
- **Efficient rendering**: D3's data binding with key functions ensures optimal DOM updates
- **Intelligent simulation**: Uses different alpha values (0.1 for updates, 0.3 for additions/removals) to minimize disruption
- **Drag-aware updates**: WebSocket updates are deferred while dragging and applied after drag completes
- **Uninterrupted dragging**: Drag operations are never interrupted by incoming updates
- **Rearrange button**: Convenient UI control to reset node layout and clear manual positioning
## How It Works
### Data Flow
```
WebSocket Server (spore-ui backend)
↓ (cluster_update / node_discovery events)
WebSocketClient (api-client.js)
↓ (emits clusterUpdate / nodeDiscovery events)
TopologyViewModel.setupWebSocketListeners()
↓ (builds graph data, updates state)
TopologyGraphComponent subscriptions
↓ (renderGraph() called automatically)
├─ If dragging: queue update in pendingUpdate
└─ If not dragging: apply update immediately
D3.js enter/exit pattern
↓ (smooth visual updates)
Updated Topology Graph
```
### Simplified Update Architecture
**Core Principle**: The D3 simulation is the single source of truth for positions.
#### How It Works:
1. **Drag Deferral**:
- `isDragging` flag blocks updates during drag
- Updates queued in `pendingUpdate` and applied after drag ends
- Dragged positions saved in `draggedNodePositions` Map for persistence
2. **Position Merging** (in `updateNodes()`):
- When simulation exists: copy live positions from simulation nodes to new data
- This preserves ongoing animations and velocities
- Then apply dragged positions (if any) as overrides
- Result: Always use most current position state
3. **Smart Simulation Updates** (in `updateSimulation()`):
- **Structural changes** (nodes added/removed): restart with alpha=0.3
- **Property changes** (status, labels): DON'T restart - just update data
- Simulation continues naturally for property-only changes
- No unnecessary disruptions to ongoing animations
This ensures:
- ✅ Simulation is authoritative for positions
- ✅ No position jumping during animations
- ✅ Property updates don't disrupt node movement
- ✅ Dragged positions always respected
- ✅ Simple, clean logic with one source of truth
### WebSocket Events Handled
1. **`clusterUpdate`** (from `cluster_update` message type)
- Payload: `{ members: [...], primaryNode: string, totalNodes: number, timestamp: string }`
- Action: Rebuilds graph with current cluster state
2. **`nodeDiscovery`** (from `node_discovery` message type)
- Payload: `{ action: 'discovered' | 'stale', nodeIp: string, timestamp: string }`
- Action: Triggers topology refresh after 500ms delay
3. **`connected`** (WebSocket connection established)
- Action: Triggers topology refresh after 1000ms delay
4. **`disconnected`** (WebSocket connection lost)
- Action: Logs disconnection (no action taken)
## Benefits
1. **Real-time Updates**: Topology reflects cluster state changes immediately
2. **Smooth Transitions**: Nodes and links fade in/out gracefully
3. **Better UX**: No manual refresh needed
4. **Efficient**: Only updates changed elements, not entire graph
5. **Resilient**: Automatically refreshes on reconnection
6. **Consistent**: Uses same WebSocket infrastructure as ClusterStatusComponent
## Testing
To test the WebSocket integration:
1. **Start the application**:
```bash
cd spore-ui
node index-standalone.js
```
2. **Open the UI** and navigate to the Topology view
3. **Add a node**: Start a new SPORE device on the network
- Watch it appear in the topology graph within seconds
- Node should fade in smoothly
4. **Remove a node**: Stop a SPORE device
- Watch it fade out from the topology graph
- Connected links should also disappear
5. **Status changes**: Change node status (active → inactive → dead)
- Node colors should update automatically
- Status indicators should change
6. **Drag during updates**:
- Start dragging a node
- While dragging, trigger a cluster update (add/remove/change another node)
- Drag should continue smoothly without interruption
- After releasing, the update should be applied immediately
- **Important**: The dragged node should stay at its final position, not revert
7. **Position persistence after drag**:
- Drag a node to a new position and release
- Trigger multiple WebSocket updates (status changes, new nodes, etc.)
- The dragged node should remain in its new position through all updates
- Only when the node is removed should its position be forgotten
8. **Update during animation**:
- Let the graph settle (simulation running, nodes animating to stable positions)
- While nodes are still moving, trigger a WebSocket update (status change)
- **Expected**: Nodes should continue their smooth animation without jumping
- **No flickering**: Positions should not snap back and forth
- Animation should feel continuous and natural
9. **Single node scenario**:
- Start with multiple nodes in the topology
- Remove nodes one by one until only one remains
- **Expected**: Single node stays visible, no "loading" message
- Graph should render correctly with just one node
- Remove the last node
- **Expected**: "No cluster members found" message appears
10. **Rearrange nodes**:
- Drag nodes to custom positions manually
- Click the "Rearrange" button in the top-left corner
- **Expected**: All nodes reset to physics-based positions
- Dragged positions cleared, simulation restarts
- Nodes animate to a clean, evenly distributed layout
11. **WebSocket reconnection**:
- Disconnect from network briefly
- Reconnect
- Topology should refresh automatically
## Technical Notes
### Architecture
- **Single Source of Truth**: D3 simulation manages all position state
- **Key Functions**: D3 data binding uses node IPs as keys to track identity
- **Transition Duration**: 300ms for fade in/out animations
### Position Management (Simplified!)
- **updateNodes()**: Copies live positions from simulation to new data before binding
- **No complex syncing**: Simulation state flows naturally to new data
- **Dragged positions**: Override via `draggedNodePositions` Map (always respected)
### Simulation Behavior
- **Structural changes** (add/remove nodes): Restart with alpha=0.3
- **Property changes** (status, labels): No restart - data updated in-place
- **Drag operations**: Simulation updates blocked entirely
- **Result**: Smooth animations for property updates, controlled restart for structure changes
### Drag Management
- **isDragging flag**: Blocks all updates during drag
- **pendingUpdate**: Queues one update, applied 50ms after drag ends
- **draggedNodePositions Map**: Persists manual positions across all updates
- **Cleanup**: Map entries removed when nodes deleted
### Performance
- **No unnecessary restarts**: Property-only updates don't disrupt simulation
- **Efficient merging**: Position data copied via Map lookup (O(n))
- **Memory efficient**: Only active nodes tracked, old entries cleaned up
- **Smooth animations**: Velocity and momentum preserved across updates
### Edge Cases Handled
- **Single node**: Graph renders correctly with just one node
- **Transient states**: Loading/no-data states don't clear existing SVG
- **Update races**: SVG preserved even if loading state triggered during render
- **Empty to non-empty**: Smooth transition from loading to first node
## Future Enhancements
Possible improvements for future iterations:
1. **Diff-based updates**: Only rebuild graph when node/link structure actually changes
2. **Visual indicators**: Show "new node" or "leaving node" badges temporarily
3. **Connection health**: Real-time latency updates on links without full rebuild
4. **Throttling**: Debounce rapid successive updates
5. **Persistent layout**: Save and restore user-arranged topology layouts
6. **Zoom to node**: Auto-zoom to newly added nodes with animation
## Related Files
- `spore-ui/public/scripts/view-models.js` - TopologyViewModel class
- `spore-ui/public/scripts/components/TopologyGraphComponent.js` - Topology visualization component
- `spore-ui/public/scripts/api-client.js` - WebSocketClient class
- `spore-ui/index-standalone.js` - WebSocket server implementation

View File

@@ -54,6 +54,14 @@
</a>
</div>
<div class="nav-right">
<div class="random-primary-switcher">
<button class="random-primary-toggle" id="random-primary-toggle" title="Select random primary node">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20">
<path d="M1 4v6h6M23 20v-6h-6" />
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" />
</svg>
</button>
</div>
<div class="theme-switcher">
<button class="theme-toggle" id="theme-toggle" title="Toggle theme">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

View File

@@ -72,6 +72,13 @@ class ApiClient {
});
}
async setPrimaryNode(ip) {
return this.request(`/api/discovery/primary/${encodeURIComponent(ip)}`, {
method: 'POST',
body: { timestamp: new Date().toISOString() }
});
}
async getNodeStatus(ip) {
return this.request(`/api/node/status/${encodeURIComponent(ip)}`, { method: 'GET' });
}

View File

@@ -77,6 +77,65 @@ document.addEventListener('DOMContentLoaded', async function() {
clusterStatusComponent.mount();
logger.debug('App: Cluster status component initialized');
// Set up random primary node button
logger.debug('App: Setting up random primary node button...');
const randomPrimaryBtn = document.getElementById('random-primary-toggle');
if (randomPrimaryBtn) {
randomPrimaryBtn.addEventListener('click', async function() {
try {
// Add spinning animation
randomPrimaryBtn.classList.add('spinning');
randomPrimaryBtn.disabled = true;
logger.debug('App: Selecting random primary node...');
await clusterViewModel.selectRandomPrimaryNode();
// Show success state briefly
logger.info('App: Random primary node selected successfully');
// Refresh topology to show new primary node connections
// Wait a bit for the backend to update, then refresh topology
setTimeout(async () => {
logger.debug('App: Refreshing topology after primary node change...');
try {
await topologyViewModel.updateNetworkTopology();
logger.debug('App: Topology refreshed successfully');
} catch (error) {
logger.error('App: Failed to refresh topology:', error);
}
}, 1000);
// Also refresh cluster view to update member list with new primary
setTimeout(async () => {
logger.debug('App: Refreshing cluster view after primary node change...');
try {
if (clusterViewModel.updateClusterMembers) {
await clusterViewModel.updateClusterMembers();
}
logger.debug('App: Cluster view refreshed successfully');
} catch (error) {
logger.error('App: Failed to refresh cluster view:', error);
}
}, 1000);
// Remove spinning animation after delay
setTimeout(() => {
randomPrimaryBtn.classList.remove('spinning');
randomPrimaryBtn.disabled = false;
}, 1500);
} catch (error) {
logger.error('App: Failed to select random primary node:', error);
randomPrimaryBtn.classList.remove('spinning');
randomPrimaryBtn.disabled = false;
// Show error notification (could be enhanced with a toast notification)
alert('Failed to select random primary node: ' + error.message);
}
});
logger.debug('App: Random primary node button configured');
}
// Set up navigation event listeners
logger.debug('App: Setting up navigation...');
app.setupNavigation();

File diff suppressed because it is too large Load Diff

View File

@@ -588,10 +588,69 @@ class TopologyViewModel extends ViewModel {
});
}
// Set up WebSocket event listeners for real-time topology updates
setupWebSocketListeners() {
if (!window.wsClient) {
logger.warn('TopologyViewModel: WebSocket client not available');
return;
}
// Listen for cluster updates
window.wsClient.on('clusterUpdate', (data) => {
logger.debug('TopologyViewModel: Received WebSocket cluster update:', data);
// Update topology from WebSocket data
if (data.members && Array.isArray(data.members)) {
logger.debug(`TopologyViewModel: Updating topology with ${data.members.length} members, primary: ${data.primaryNode}`);
// Build enhanced graph data from updated members with primary node info
this.buildEnhancedGraphData(data.members, data.primaryNode).then(({ nodes, links }) => {
this.batchUpdate({
nodes: nodes,
links: links,
primaryNode: data.primaryNode,
lastUpdateTime: data.timestamp || new Date().toISOString()
});
}).catch(error => {
logger.error('TopologyViewModel: Failed to build graph data from websocket update:', error);
});
} else {
logger.warn('TopologyViewModel: Received cluster update but no valid members array:', data);
}
});
// Listen for node discovery events
window.wsClient.on('nodeDiscovery', (data) => {
logger.debug('TopologyViewModel: Received WebSocket node discovery event:', data);
// Node discovery events are logged but no action needed
// The subsequent clusterUpdate event will provide the updated member list
// and update the topology through the websocket data flow
if (data.action === 'discovered') {
logger.debug('TopologyViewModel: Node discovered, waiting for clusterUpdate event');
} else if (data.action === 'stale') {
logger.debug('TopologyViewModel: Node became stale, waiting for clusterUpdate event');
}
});
// Listen for connection status changes
window.wsClient.on('connected', () => {
logger.debug('TopologyViewModel: WebSocket connected');
// Connection restored - the server will send a clusterUpdate event shortly
// No need to make an API call, just wait for the websocket data
});
window.wsClient.on('disconnected', () => {
logger.debug('TopologyViewModel: WebSocket disconnected');
});
}
// Update network topology data
// NOTE: This method makes an API call and should only be used for initial load
// All subsequent updates should come from websocket events (clusterUpdate)
async updateNetworkTopology() {
try {
logger.debug('TopologyViewModel: updateNetworkTopology called');
logger.debug('TopologyViewModel: updateNetworkTopology called (API call)');
this.set('isLoading', true);
this.set('error', null);
@@ -600,14 +659,24 @@ class TopologyViewModel extends ViewModel {
const response = await window.apiClient.getClusterMembers();
logger.debug('TopologyViewModel: Got cluster members response:', response);
// Get discovery info to find the primary node
const discoveryInfo = await window.apiClient.getDiscoveryInfo();
logger.debug('TopologyViewModel: Got discovery info:', discoveryInfo);
const members = response.members || [];
const primaryNode = discoveryInfo.primaryNode || null;
logger.debug(`TopologyViewModel: Building graph with ${members.length} members, primary: ${primaryNode}`);
// Build enhanced graph data with actual node connections
const { nodes, links } = await this.buildEnhancedGraphData(members);
const { nodes, links } = await this.buildEnhancedGraphData(members, primaryNode);
logger.debug(`TopologyViewModel: Built graph with ${nodes.length} nodes and ${links.length} links`);
this.batchUpdate({
nodes: nodes,
links: links,
primaryNode: primaryNode,
lastUpdateTime: new Date().toISOString()
});
@@ -621,93 +690,70 @@ class TopologyViewModel extends ViewModel {
}
// Build enhanced graph data with actual node connections
async buildEnhancedGraphData(members) {
// Creates a star topology with the primary node at the center
async buildEnhancedGraphData(members, primaryNode) {
const nodes = [];
const links = [];
const nodeConnections = new Map();
// Get existing nodes to preserve their positions
const existingNodes = this.get('nodes') || [];
const existingNodeMap = new Map(existingNodes.map(n => [n.id, n]));
// Create nodes from members
members.forEach((member, index) => {
if (member && member.ip) {
const existingNode = existingNodeMap.get(member.ip);
const isPrimary = member.ip === primaryNode;
nodes.push({
id: member.ip,
hostname: member.hostname || member.ip,
ip: member.ip,
status: member.status || 'UNKNOWN',
latency: member.latency || 0,
isPrimary: isPrimary,
// Preserve both legacy 'resources' and preferred 'labels'
labels: (member.labels && typeof member.labels === 'object') ? member.labels : (member.resources || {}),
resources: member.resources || {},
x: Math.random() * 1200 + 100, // Better spacing for 1400px width
y: Math.random() * 800 + 100 // Better spacing for 1000px height
// Preserve existing position if node already exists, otherwise assign random position
x: existingNode ? existingNode.x : Math.random() * 1200 + 100,
y: existingNode ? existingNode.y : Math.random() * 800 + 100,
// Preserve velocity if it exists (for D3 simulation)
vx: existingNode ? existingNode.vx : undefined,
vy: existingNode ? existingNode.vy : undefined,
// Preserve fixed position if it was dragged
fx: existingNode ? existingNode.fx : undefined,
fy: existingNode ? existingNode.fy : undefined
});
}
});
// Try to get cluster members from each node to build actual connections
for (const node of nodes) {
try {
const nodeResponse = await window.apiClient.getClusterMembersFromNode(node.ip);
if (nodeResponse && nodeResponse.members) {
nodeConnections.set(node.ip, nodeResponse.members);
}
} catch (error) {
console.warn(`Failed to get cluster members from node ${node.ip}:`, error);
// Continue with other nodes
}
}
// Build links based on actual connections
for (const [sourceIp, sourceMembers] of nodeConnections) {
for (const targetMember of sourceMembers) {
if (targetMember.ip && targetMember.ip !== sourceIp) {
// Check if we already have this link
const existingLink = links.find(link =>
(link.source === sourceIp && link.target === targetMember.ip) ||
(link.source === targetMember.ip && link.target === sourceIp)
);
// Build links - create a star topology with primary node at center
// Only create links from the primary node to each member
// The cluster data comes from the primary, so it only knows about its direct connections
if (primaryNode) {
logger.debug(`TopologyViewModel: Creating star topology with primary ${primaryNode}`);
nodes.forEach(node => {
// Create a link from primary to each non-primary node
if (node.ip !== primaryNode) {
const member = members.find(m => m.ip === node.ip);
const latency = member?.latency || this.estimateLatency(node, { ip: primaryNode });
if (!existingLink) {
const sourceNode = nodes.find(n => n.id === sourceIp);
const targetNode = nodes.find(n => n.id === targetMember.ip);
if (sourceNode && targetNode) {
const latency = targetMember.latency || this.estimateLatency(sourceNode, targetNode);
links.push({
source: sourceIp,
target: targetMember.ip,
latency: latency,
sourceNode: sourceNode,
targetNode: targetNode,
bidirectional: true
});
}
}
}
}
}
// If no actual connections found, create a basic mesh
if (links.length === 0) {
logger.debug('TopologyViewModel: No actual connections found, creating basic mesh');
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
const sourceNode = nodes[i];
const targetNode = nodes[j];
const estimatedLatency = this.estimateLatency(sourceNode, targetNode);
logger.debug(`TopologyViewModel: Creating link from ${primaryNode} to ${node.ip} (latency: ${latency}ms)`);
links.push({
source: sourceNode.id,
target: targetNode.id,
latency: estimatedLatency,
sourceNode: sourceNode,
targetNode: targetNode,
bidirectional: true
source: primaryNode,
target: node.id,
latency: latency,
sourceNode: nodes.find(n => n.ip === primaryNode),
targetNode: node,
bidirectional: false // Primary -> Member is directional
});
}
}
});
logger.debug(`TopologyViewModel: Created ${links.length} links from primary node`);
} else {
logger.warn('TopologyViewModel: No primary node specified, cannot create links');
}
return { nodes, links };
@@ -730,6 +776,31 @@ class TopologyViewModel extends ViewModel {
clearSelection() {
this.set('selectedNode', null);
}
// Switch to a specific node as the new primary
async switchToPrimaryNode(nodeIp) {
try {
logger.debug(`TopologyViewModel: Switching primary node to ${nodeIp}`);
const result = await window.apiClient.setPrimaryNode(nodeIp);
if (result.success) {
logger.info(`TopologyViewModel: Successfully switched primary to ${nodeIp}`);
// Update topology after a short delay to allow backend to update
setTimeout(async () => {
logger.debug('TopologyViewModel: Refreshing topology after primary switch...');
await this.updateNetworkTopology();
}, 1000);
return result;
} else {
throw new Error(result.message || 'Failed to switch primary node');
}
} catch (error) {
logger.error('TopologyViewModel: Failed to switch primary node:', error);
throw error;
}
}
}
// Monitoring View Model for cluster resource monitoring

View File

@@ -68,6 +68,7 @@ button:disabled {
/* === Icon-Only Button Style (Minimal) === */
.btn-icon,
.theme-toggle,
.random-primary-toggle,
.burger-btn,
.primary-node-refresh,
.filter-pill-remove,
@@ -96,6 +97,7 @@ button:disabled {
.btn-icon:hover,
.theme-toggle:hover,
.random-primary-toggle:hover,
.burger-btn:hover,
.primary-node-refresh:hover,
.filter-pill-remove:hover,
@@ -527,6 +529,44 @@ p {
animation: spin 1s linear infinite;
}
.random-primary-toggle {
width: 32px;
height: 32px;
border-radius: 6px;
}
.random-primary-toggle svg {
width: 20px;
height: 20px;
transition: transform 0.3s ease;
}
.random-primary-toggle:hover {
background: rgba(255, 255, 255, 0.1);
}
.random-primary-toggle:hover svg {
transform: rotate(180deg);
}
.random-primary-toggle.spinning svg {
animation: spin 1s linear infinite;
}
.random-primary-toggle:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Topology graph node interactions */
#topology-graph-container .node {
cursor: pointer;
}
#topology-graph-container .node:hover circle:first-child {
filter: brightness(1.2);
}
@keyframes spin {
from {
transform: rotate(0deg);