Skip to content

Commit

Permalink
refactor: use common channel registry (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
aaron-steinfeld authored Sep 3, 2021
1 parent d941520 commit 461fe95
Showing 1 changed file with 5 additions and 26 deletions.
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);
}
}

0 comments on commit 461fe95

Please sign in to comment.