Skip to content

Commit b2b7df9

Browse files
committed
feat: add Free methods to Graph and P2P for resetting state and enhance eachStop for peer management
1 parent 44f3e3d commit b2b7df9

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

v2/graph/graph.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ func New(directed bool, weighted bool) *Graph {
3434
}
3535
}
3636

37+
// Free clears all nodes and edges from the graph, effectively resetting it to an empty state.
38+
func (g *Graph) Free() {
39+
for id := range g.nodes {
40+
delete(g.nodes, id)
41+
}
42+
}
43+
3744
/* Node */
3845

3946
// AddNode adds a node to the graph.

v2/p2p/p2p.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ func New(source *graph.Graph, cfg *Config) (*P2P, error) {
6868
return &P2P{peers: nodes, cfg: cfg}, nil
6969
}
7070

71+
// Free clears all peers from the P2P network, effectively resetting it to an empty state.
72+
func (p *P2P) Free() {
73+
for id := range p.peers {
74+
p.peers[id].eachStop()
75+
delete(p.peers, id)
76+
}
77+
}
78+
7179
/* Basic Actions */
7280

7381
// Run starts the message handling routines for all peers in the network.

v2/p2p/peer.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,12 @@ func (p *peer) eachPublish(network *P2P, msg Message) {
146146
}(edgeCopy)
147147
}
148148
}
149+
150+
// eachStop marks the peer as inactive and closes its message queue.
151+
func (p *peer) eachStop() {
152+
p.mu.Lock()
153+
defer p.mu.Unlock()
154+
155+
p.alive = false
156+
close(p.msgQueue)
157+
}

0 commit comments

Comments
 (0)