-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: use common channel registry (#77)
- Loading branch information
1 parent
d941520
commit 461fe95
Showing
1 changed file
with
5 additions
and
26 deletions.
There are no files selected for viewing
31 changes: 5 additions & 26 deletions
31
...tils/src/main/java/org/hypertrace/core/graphql/utils/grpc/DefaultGrpcChannelRegistry.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,23 @@ | ||
package org.hypertrace.core.graphql.utils.grpc; | ||
|
||
import io.grpc.ManagedChannel; | ||
import io.grpc.ManagedChannelBuilder; | ||
import java.util.Map; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import javax.inject.Inject; | ||
import javax.inject.Singleton; | ||
import org.hypertrace.core.graphql.spi.lifecycle.GraphQlServiceLifecycle; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
@Singleton | ||
class DefaultGrpcChannelRegistry implements GrpcChannelRegistry { | ||
private static final Logger LOG = LoggerFactory.getLogger(DefaultGrpcChannelRegistry.class); | ||
private final Map<String, ManagedChannel> channelMap = new ConcurrentHashMap<>(); | ||
private volatile boolean isShutdown = false; | ||
|
||
private final org.hypertrace.core.grpcutils.client.GrpcChannelRegistry delegate = | ||
new org.hypertrace.core.grpcutils.client.GrpcChannelRegistry(); | ||
|
||
@Inject | ||
DefaultGrpcChannelRegistry(GraphQlServiceLifecycle serviceLifecycle) { | ||
serviceLifecycle.shutdownCompletion().thenRun(this::shutdown); | ||
serviceLifecycle.shutdownCompletion().thenRun(this.delegate::shutdown); | ||
} | ||
|
||
@Override | ||
public ManagedChannel forAddress(String host, int port) { | ||
assert !this.isShutdown; | ||
String channelId = this.getChannelId(host, port); | ||
return this.channelMap.computeIfAbsent(channelId, unused -> this.buildNewChannel(host, port)); | ||
} | ||
|
||
private ManagedChannel buildNewChannel(String host, int port) { | ||
LOG.info("Creating new channel for {}:{}", host, port); | ||
return ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); | ||
} | ||
|
||
private String getChannelId(String host, int port) { | ||
return host + ":" + port; | ||
} | ||
|
||
private void shutdown() { | ||
channelMap.values().forEach(ManagedChannel::shutdown); | ||
this.isShutdown = true; | ||
return this.delegate.forPlaintextAddress(host, port); | ||
} | ||
} |