From 91f58e9de74021fe6630c48f576c777ab4e1826c Mon Sep 17 00:00:00 2001 From: Max Ma Date: Wed, 13 Nov 2024 00:02:09 +0100 Subject: [PATCH] fix load node to network cache issue --- logic/nodes.go | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/logic/nodes.go b/logic/nodes.go index 0a3c5eafa..d4f9df087 100644 --- a/logic/nodes.go +++ b/logic/nodes.go @@ -72,6 +72,17 @@ func storeNodeInCache(node models.Node) { nodesCacheMap[node.ID.String()] = node nodeCacheMutex.Unlock() } +func loadNodesIntoNetworkCache(nMap map[string]models.Node) { + nodeNetworkCacheMutex.Lock() + for _, v := range nMap { + network := v.Network + if nodesNetworkCacheMap[network] == nil { + nodesNetworkCacheMap[network] = make(map[string]models.Node) + } + nodesNetworkCacheMap[network][v.ID.String()] = v + } + nodeNetworkCacheMutex.Unlock() +} func loadNodesIntoCache(nMap map[string]models.Node) { nodeCacheMutex.Lock() @@ -81,6 +92,7 @@ func loadNodesIntoCache(nMap map[string]models.Node) { func ClearNodeCache() { nodeCacheMutex.Lock() nodesCacheMap = make(map[string]models.Node) + nodesNetworkCacheMap = make(map[string]map[string]models.Node) nodeCacheMutex.Unlock() } @@ -95,9 +107,10 @@ const ( // GetNetworkNodes - gets the nodes of a network func GetNetworkNodes(network string) ([]models.Node, error) { - nodeNetworkCacheMutex.Lock() - defer nodeNetworkCacheMutex.Unlock() + if networkNodes, ok := nodesNetworkCacheMap[network]; ok { + nodeNetworkCacheMutex.Lock() + defer nodeNetworkCacheMutex.Unlock() return slices.Collect(maps.Values(networkNodes)), nil } allnodes, err := GetAllNodes() @@ -122,9 +135,10 @@ func GetHostNodes(host *models.Host) []models.Node { // GetNetworkNodesMemory - gets all nodes belonging to a network from list in memory func GetNetworkNodesMemory(allNodes []models.Node, network string) []models.Node { - nodeNetworkCacheMutex.Lock() - defer nodeNetworkCacheMutex.Unlock() + if networkNodes, ok := nodesNetworkCacheMap[network]; ok { + nodeNetworkCacheMutex.Lock() + defer nodeNetworkCacheMutex.Unlock() return slices.Collect(maps.Values(networkNodes)) } var nodes = []models.Node{} @@ -382,6 +396,7 @@ func GetAllNodes() ([]models.Node, error) { nodesMap := make(map[string]models.Node) if servercfg.CacheEnabled() { defer loadNodesIntoCache(nodesMap) + defer loadNodesIntoNetworkCache(nodesMap) } collection, err := database.FetchRecords(database.NODES_TABLE_NAME) if err != nil {