12 KiB
Phase 1: Core Framework and Types
Overview
Phase 1 establishes the foundation of the network library by implementing core types and the base building blocks: NetworkNode and NetworkSystem. This phase is critical as it defines the data structures and relationships that the entire system depends on.
Core Architecture Class Diagram
The following class diagram illustrates the key components and their relationships that should be implemented in this phase:
classDiagram
class NetworkNode {
-id: string
-level: number
-parent: NetworkNode
-children: Map~string, NetworkNode~
-siblings: Map~string, NetworkNode~
-capabilities: NodeCapabilities
-performance: NodePerformance
-levelConfig: LevelConfig
-transport: NetworkTransport
+addChild(node: NetworkNode)
+removeChild(nodeId: string)
+addSibling(node: NetworkNode)
+removeSibling(nodeId: string)
+sendMessage(message: NetworkMessage)
+tryPromote()
+demote()
+canAcceptChildren()
}
class LevelConfig {
+level: number
+name: string
+maxChildren: number
+maxSiblings: number
+minPromotionScore: number
+demotionThreshold: number
+messageRoutingConfig: MessageRoutingConfig
}
class NetworkSystem {
-nodes: Map~string, NetworkNode~
-config: NetworkSystemConfig
+createNode(id, transport, capabilities)
+removeNode(id)
+findBestParent(node)
+placeNodeInHierarchy(node)
}
class NetworkTransport {
<<interface>>
+sendTo(nodeId, message)
+on(event, handler)
+off(event, handler)
}
class VotingManager {
-node: NetworkNode
-config: VotingConfig
+startVote(trigger)
+castVote(vote)
}
NetworkNode "1" --> "0..1" NetworkNode : parent
NetworkNode "1" --> "*" NetworkNode : children
NetworkNode "1" --> "*" NetworkNode : siblings
NetworkNode "1" --> "1" LevelConfig
NetworkNode "1" --> "0..1" VotingManager
NetworkNode "1" --> "1" NetworkTransport
NetworkSystem "1" --> "*" NetworkNode
This diagram illustrates the unified node architecture where all network participants use the same NetworkNode class with behavior determined by their level in the hierarchy. The relationships between nodes (parent-child and sibling) form the network structure, with each node configured based on its level.
Key Components
1. Core Types and Interfaces (src/types.ts)
This file serves as the centralized location for all shared types used throughout the system. It should include:
- Connection States and Message Types: Define enums for connection states, message priorities, and routing modes
- Node Configuration: Define interfaces for node capabilities, performance metrics, and connection quality
- Level Configuration: Define interfaces for level configurations, system configuration, and routing rules
- Voting System Types: Define interfaces for votes, vote tallies, and voting configuration
- Tier Management Types: Define interfaces for tier statistics and configuration
- Plugin Interface: Define the base plugin interface
2. Node-Specific Types (src/node/types.ts)
This file defines interfaces specific to the NetworkNode component to avoid circular dependencies:
- INetworkNodeIdentity: A lightweight interface representing node identity
- Component Interfaces: Define interfaces for VotingManager, MessageRouter, and NetworkStats
3. NetworkNode Implementation (src/node/node.ts)
The NetworkNode class is the fundamental building block of the system. It should:
- Maintain parent-child relationships in the hierarchy
- Track siblings at the same level
- Support dynamic level changes (promotion/demotion)
- Provide message routing capabilities
- Configure behavior based on level
- Support plugin registration and management
Key Methods to Implement
-
Parent-Child Management:
addChild: Add a child node to this noderemoveChild: Remove a child nodecanAcceptChildren: Check if this node can accept more children
-
Sibling Management:
addSibling: Add a sibling noderemoveSibling: Remove a sibling relationship
-
Messaging:
sendMessage: Send a message to another node- Process incoming messages
-
Level Management:
tryPromote: Attempt to promote this node to the next leveldemote: Demote this node to a lower level
-
Plugin Management:
registerPlugin: Register a plugin with this noderemovePlugin: Remove a plugingetPlugin: Get a plugin by ID
Edge Cases to Handle
- Level Changes: When a node changes level, children must be redistributed
- Parent Disconnection: When a parent disconnects, child nodes must find new parents
- Circular References: Avoid circular parent-child relationships
- Level Configuration: Apply the correct configuration based on the node's level
- Message Routing: Ensure messages are routed correctly based on the hierarchy
4. NetworkSystem Implementation (src/network/network.ts)
The NetworkSystem class manages the entire network of nodes. It should:
- Create and remove nodes
- Place nodes in the hierarchy
- Find appropriate parents for nodes
- Manage the tier structure
- Handle node disconnections and reconnections
Key Methods to Implement
-
Node Management:
createNode: Create a new node with the specified propertiesremoveNode: Remove a node from the systemgetNode: Get a node by IDgetAllNodes: Get all nodes in the system
-
Hierarchy Management:
findBestParent: Find the most suitable parent for a nodeplaceNodeInHierarchy: Place a node in the hierarchygetNodesByLevel: Get all nodes at a specific level
-
Event Handling:
handleNodeDisconnection: Handle a node disconnectinghandleNodeReconnection: Handle a node reconnecting
Edge Cases to Handle
- Empty Levels: Handle situations where an entire level becomes empty
- Disconnection Cascades: Prevent cascading disconnections from destabilizing the system
- Reconnection Loops: Prevent infinite reconnection attempts
- Configuration Inconsistencies: Validate level configurations to ensure they're consistent
Implementation Requirements
Node Relationships
Node relationships should be flexible but controlled:
-
Parent-Child Relationships:
- A node can have only one parent
- A node's level must be one less than its parent's level
- A node cannot be its own ancestor (no cycles in the hierarchy)
- Level 0 nodes (clients) cannot have children
-
Sibling Relationships:
- Siblings must be at the same level
- Sibling relationships should be bidirectional
- The number of siblings should not exceed the level's maxSiblings parameter
Level Configuration
Each level needs specific configuration:
-
Level 0 (Client):
- Cannot have children
- No hosting responsibilities
- May have unlimited siblings
-
Level 1 (Host):
- Limited number of children (typically 20)
- Limited number of siblings (typically 10)
- Handles message routing for its children
-
Level 2+ (Tier Host, Region Host, etc.):
- Each higher level has fewer hosts but more responsibilities
- Higher levels need higher performance thresholds
- Higher levels may route messages differently
Performance Metrics
Nodes need to track and report performance metrics:
-
System Metrics:
- CPU load
- Memory usage
- Network usage
- Battery level (for mobile devices)
-
Connection Metrics:
- Latency/ping times to connected nodes
- Packet loss
- Bandwidth
- Jitter
- Connection stability
Message Handling
The basic message flow implementation should support:
-
Message Types:
- Direct messages (node to node)
- Broadcasts (to all or a subset of nodes)
- System messages (for internal coordination)
-
Message Priorities:
- Critical messages (highest priority)
- High priority messages
- Medium priority messages
- Low priority messages (lowest priority)
-
Message Routing:
- Upward routing (to parent)
- Downward routing (to children)
- Hierarchical routing (up then down)
- Multi-level routing (optimized path)
- Broadcast routing (to all connected nodes)
Testing Strategy
NetworkNode Tests
-
Relationship Tests:
- Test adding/removing children
- Test handling parent changes
- Test sibling relationships
-
Level Management Tests:
- Test promotion criteria
- Test demotion criteria
- Test level-specific behavior
-
Message Routing Tests:
- Test sending messages to parent
- Test sending messages to children
- Test handling unknown recipients
NetworkSystem Tests
-
Node Management Tests:
- Test creating nodes with different capabilities
- Test removing nodes
- Test retrieving nodes
-
Hierarchy Tests:
- Test placement algorithms
- Test finding best parent
- Test handling disconnections
-
Configuration Tests:
- Test level configuration application
- Test system configuration validation
Edge Cases and Considerations
1. Memory Management
Be careful with bidirectional references to avoid memory leaks:
- Use weak references where appropriate
- Clean up event listeners when nodes are removed
- Ensure circular references are properly handled
2. Event Propagation
Consider how events propagate through the hierarchy:
- Should events bubble up to parents?
- Should parents broadcast events to children?
- How are events handled when the hierarchy changes?
3. Concurrency
Consider concurrent operations on the node hierarchy:
- What happens if a node is added while the hierarchy is being reorganized?
- How are race conditions handled when multiple nodes disconnect simultaneously?
- How is message ordering maintained during hierarchy changes?
4. Error Handling
Implement robust error handling:
- Handle transport failures gracefully
- Validate all inputs, especially network messages
- Provide meaningful error messages for debugging
5. Configuration Validation
Validate system configuration to prevent issues:
- Ensure level configurations are consistent
- Validate routing configurations
- Check for missing required configuration fields
Integration Points
The core components should be designed with clear integration points for future phases:
- Transport Integration: NetworkNode should use the ITransport interface
- Voting Integration: NetworkNode should prepare for VotingManager integration
- Plugin System: NetworkNode should support plugin registration
- Tier Management: NetworkSystem should prepare for TierManager integration
Performance Considerations
Even in this foundational phase, consider performance:
- Message Handling: Optimize message routing algorithm
- Node Storage: Use efficient data structures for node lookups
- Event Handling: Avoid unnecessary event emissions
Success Criteria
This phase is complete when:
- All core types and interfaces are defined
- NetworkNode fully implements parent-child relationships
- NetworkNode correctly adapts behavior based on level
- NetworkSystem can create, place, and manage nodes
- Basic message routing works correctly
- All tests pass with 100% code coverage
- Edge cases are properly handled and tested
The foundation laid in this phase will support all subsequent development, so it's critical to ensure it's robust, well-tested, and extensible.