diff --git a/application/src/main/java/de/cotto/lndmanagej/service/NodeService.java b/application/src/main/java/de/cotto/lndmanagej/service/NodeService.java index 97f19995..7faaae91 100644 --- a/application/src/main/java/de/cotto/lndmanagej/service/NodeService.java +++ b/application/src/main/java/de/cotto/lndmanagej/service/NodeService.java @@ -10,13 +10,18 @@ import org.springframework.stereotype.Component; @Component public class NodeService { private static final int MAXIMUM_SIZE = 500; - private static final int CACHE_EXPIRY_MINUTES = 30; + private static final int ALIAS_CACHE_EXPIRY_MINUTES = 30; + private static final int NODE_CACHE_EXPIRY_SECONDS = 60; private final GrpcNodeInfo grpcNodeInfo; private final LoadingCache aliasCache = new CacheBuilder() - .withExpiryMinutes(CACHE_EXPIRY_MINUTES) + .withExpiryMinutes(ALIAS_CACHE_EXPIRY_MINUTES) .withMaximumSize(MAXIMUM_SIZE) .build(this::getAliasWithoutCache); + private final LoadingCache nodeCache = new CacheBuilder() + .withExpirySeconds(NODE_CACHE_EXPIRY_SECONDS) + .withMaximumSize(MAXIMUM_SIZE) + .build(this::getNodeWithoutCache); public NodeService(GrpcNodeInfo grpcNodeInfo) { this.grpcNodeInfo = grpcNodeInfo; @@ -27,11 +32,17 @@ public class NodeService { } public Node getNode(Pubkey pubkey) { - return grpcNodeInfo.getNode(pubkey); + return nodeCache.getUnchecked(pubkey); + } + + private Node getNodeWithoutCache(Pubkey pubkey) { + Node node = grpcNodeInfo.getNode(pubkey); + aliasCache.put(pubkey, node.alias()); + return node; } private String getAliasWithoutCache(Pubkey pubkey) { - return getNode(pubkey).alias(); + return getNodeWithoutCache(pubkey).alias(); } } diff --git a/application/src/test/java/de/cotto/lndmanagej/service/NodeServiceTest.java b/application/src/test/java/de/cotto/lndmanagej/service/NodeServiceTest.java index 15e72a4d..f7bb11f6 100644 --- a/application/src/test/java/de/cotto/lndmanagej/service/NodeServiceTest.java +++ b/application/src/test/java/de/cotto/lndmanagej/service/NodeServiceTest.java @@ -9,6 +9,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static de.cotto.lndmanagej.model.NodeFixtures.ALIAS; import static de.cotto.lndmanagej.model.NodeFixtures.NODE; +import static de.cotto.lndmanagej.model.NodeFixtures.NODE_WITHOUT_ALIAS; import static de.cotto.lndmanagej.model.PubkeyFixtures.PUBKEY; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @@ -32,4 +33,12 @@ class NodeServiceTest { when(grpcNodeInfo.getNode(PUBKEY)).thenReturn(NODE); assertThat(nodeService.getNode(PUBKEY)).isEqualTo(NODE); } + + @Test + void getNode_updates_alias() { + when(grpcNodeInfo.getNode(PUBKEY)).thenReturn(NODE_WITHOUT_ALIAS).thenReturn(NODE).thenThrow(); + assertThat(nodeService.getAlias(PUBKEY)).isEqualTo(NODE_WITHOUT_ALIAS.alias()); + nodeService.getNode(PUBKEY); + assertThat(nodeService.getAlias(PUBKEY)).isEqualTo(ALIAS); + } } \ No newline at end of file