Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for anonymous in-process servers. #8589

Merged
merged 11 commits into from Oct 25, 2021
42 changes: 28 additions & 14 deletions core/src/main/java/io/grpc/inprocess/InProcessChannelBuilder.java
Expand Up @@ -55,15 +55,28 @@ public final class InProcessChannelBuilder extends
* @return a new builder
*/
public static InProcessChannelBuilder forName(String name) {
return new InProcessChannelBuilder(name);
return forAddress(new InProcessSocketAddress(checkNotNull(name, "name")));
}

/**
* Always fails. Call {@link #forName} instead.
* Create a channel builder that will connect to the server referenced by the given target URI.
* Only intended for use with a custom name resolver.
*
* @param target the identity of the server to connect to
* @return a new builder
*/
@DoNotCall("Unsupported. Use forName() instead")
public static InProcessChannelBuilder forTarget(String target) {
throw new UnsupportedOperationException("call forName() instead");
return new InProcessChannelBuilder(null, checkNotNull(target, "target"));
}

/**
* Create a channel builder that will connect to the server referenced by the given address.
*
* @param address the address of the server to connect to
* @return a new builder
*/
public static InProcessChannelBuilder forAddress(InProcessSocketAddress address) {
return new InProcessChannelBuilder(checkNotNull(address, "address"), null);
}

/**
Expand All @@ -75,13 +88,12 @@ public static InProcessChannelBuilder forAddress(String name, int port) {
}

private final ManagedChannelImplBuilder managedChannelImplBuilder;
private final String name;
private ScheduledExecutorService scheduledExecutorService;
private int maxInboundMetadataSize = Integer.MAX_VALUE;
private boolean transportIncludeStatusCause = false;

private InProcessChannelBuilder(String name) {
this.name = checkNotNull(name, "name");
private InProcessChannelBuilder(
@Nullable InProcessSocketAddress directAddress, @Nullable String target) {

final class InProcessChannelTransportFactoryBuilder implements ClientTransportFactoryBuilder {
@Override
Expand All @@ -90,8 +102,13 @@ public ClientTransportFactory buildClientTransportFactory() {
}
}

managedChannelImplBuilder = new ManagedChannelImplBuilder(new InProcessSocketAddress(name),
"localhost", new InProcessChannelTransportFactoryBuilder(), null);
if (directAddress != null) {
managedChannelImplBuilder = new ManagedChannelImplBuilder(directAddress, "localhost",
new InProcessChannelTransportFactoryBuilder(), null);
} else {
managedChannelImplBuilder = new ManagedChannelImplBuilder(target,
new InProcessChannelTransportFactoryBuilder(), null);
}

// In-process transport should not record its traffic to the stats module.
// https://github.com/grpc/grpc-java/issues/2284
Expand Down Expand Up @@ -204,7 +221,7 @@ public InProcessChannelBuilder propagateCauseWithStatus(boolean enable) {

ClientTransportFactory buildTransportFactory() {
return new InProcessClientTransportFactory(
name, scheduledExecutorService, maxInboundMetadataSize, transportIncludeStatusCause);
scheduledExecutorService, maxInboundMetadataSize, transportIncludeStatusCause);
}

void setStatsEnabled(boolean value) {
Expand All @@ -215,18 +232,15 @@ void setStatsEnabled(boolean value) {
* Creates InProcess transports. Exposed for internal use, as it should be private.
*/
static final class InProcessClientTransportFactory implements ClientTransportFactory {
private final String name;
private final ScheduledExecutorService timerService;
private final boolean useSharedTimer;
private final int maxInboundMetadataSize;
private boolean closed;
private final boolean includeCauseWithStatus;

private InProcessClientTransportFactory(
String name,
@Nullable ScheduledExecutorService scheduledExecutorService,
int maxInboundMetadataSize, boolean includeCauseWithStatus) {
this.name = name;
useSharedTimer = scheduledExecutorService == null;
timerService = useSharedTimer
? SharedResourceHolder.get(GrpcUtil.TIMER_SERVICE) : scheduledExecutorService;
Expand All @@ -242,7 +256,7 @@ public ConnectionClientTransport newClientTransport(
}
// TODO(carl-mastrangelo): Pass channelLogger in.
return new InProcessTransport(
name, maxInboundMetadataSize, options.getAuthority(), options.getUserAgent(),
addr, maxInboundMetadataSize, options.getAuthority(), options.getUserAgent(),
options.getEagAttributes(), includeCauseWithStatus);
}

Expand Down
32 changes: 24 additions & 8 deletions core/src/main/java/io/grpc/inprocess/InProcessServer.java
Expand Up @@ -40,13 +40,23 @@ final class InProcessServer implements InternalServer {
private static final ConcurrentMap<String, InProcessServer> registry
= new ConcurrentHashMap<>();

static InProcessServer findServer(String name) {
Copy link
Contributor Author

@markb74 markb74 Oct 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The possibility of creating a base AbstractInProcessSocketAddress class with package visible findServer(), registerServer(InProcessServer) and unregisterServer(InProcessServer) methods occurred to me.

That would allow this method, and registerInstance() and unregisterInstance() below to just be methods on the address, removing the need for instance checks.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimizing this method seems like a micro-optimization. If this method is the only one that benefits, then avoiding public API seems clearly superior. If we think user's code would improve, then common base class is more interesting. Seems we can always do it in the future, so let's favor less API for now.

Your suggestion would also mean moving the registry to InProcessSocketAddress, which propagates the "strangeness" of anonymous socket address. Seems counter to our preferences.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I was attracted to the approach making everything more consistent, even if that does mean "embracing the strangeness" to some degree. But I like philosophy that improving user code is the key goal, so agreed this probably isn't worth it.

return registry.get(name);
static InProcessServer findServer(SocketAddress addr) {
if (addr instanceof InProcessSocketAddress) {
InProcessSocketAddress inProcessAddress = (InProcessSocketAddress) addr;
if (inProcessAddress.getServer() != null) {
return inProcessAddress.getServer();
} else {
return registry.get(inProcessAddress.getName());
}
}
return null;
}

private final String name;
private final boolean anonymous;
private final int maxInboundMetadataSize;
private final List<ServerStreamTracer.Factory> streamTracerFactories;
private final InProcessSocketAddress listenAddress;
private ServerListener listener;
private boolean shutdown;
/** Defaults to be a SharedResourcePool. */
Expand All @@ -61,25 +71,29 @@ static InProcessServer findServer(String name) {
InProcessServerBuilder builder,
List<? extends ServerStreamTracer.Factory> streamTracerFactories) {
this.name = builder.name;
this.anonymous = builder.anonymous;
this.schedulerPool = builder.schedulerPool;
this.maxInboundMetadataSize = builder.maxInboundMetadataSize;
this.streamTracerFactories =
Collections.unmodifiableList(checkNotNull(streamTracerFactories, "streamTracerFactories"));
this.listenAddress = new InProcessSocketAddress(name, anonymous ? this : null);
}

@Override
public void start(ServerListener serverListener) throws IOException {
this.listener = serverListener;
this.scheduler = schedulerPool.getObject();
// Must be last, as channels can start connecting after this point.
if (registry.putIfAbsent(name, this) != null) {
throw new IOException("name already registered: " + name);
if (!anonymous) {
// Must be last, as channels can start connecting after this point.
if (registry.putIfAbsent(name, this) != null) {
throw new IOException("name already registered: " + name);
}
}
markb74 marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public SocketAddress getListenSocketAddress() {
return new InProcessSocketAddress(name);
return listenAddress;
}

@Override
Expand All @@ -99,8 +113,10 @@ public List<InternalInstrumented<SocketStats>> getListenSocketStatsList() {

@Override
public void shutdown() {
if (!registry.remove(name, this)) {
throw new AssertionError();
if (!anonymous) {
if (!registry.remove(name, this)) {
throw new AssertionError();
}
}
scheduler = schedulerPool.returnObject(scheduler);
synchronized (this) {
Expand Down
16 changes: 14 additions & 2 deletions core/src/main/java/io/grpc/inprocess/InProcessServerBuilder.java
Expand Up @@ -81,7 +81,17 @@ public final class InProcessServerBuilder extends
* @return a new builder
*/
public static InProcessServerBuilder forName(String name) {
return new InProcessServerBuilder(name);
return new InProcessServerBuilder(name, false);
}

/**
* Create a server builder for an anonymous in-process server.
* Anonymous servers can only be connected to via their listen address,
* and can't be referenced by name.
* @return a new builder
*/
public static InProcessServerBuilder anonymous() {
return new InProcessServerBuilder("anonymous", true);
}

/**
Expand All @@ -101,12 +111,14 @@ public static String generateName() {

private final ServerImplBuilder serverImplBuilder;
final String name;
final boolean anonymous;
int maxInboundMetadataSize = Integer.MAX_VALUE;
ObjectPool<ScheduledExecutorService> schedulerPool =
SharedResourcePool.forResource(GrpcUtil.TIMER_SERVICE);

private InProcessServerBuilder(String name) {
private InProcessServerBuilder(String name, boolean anonymous) {
this.name = Preconditions.checkNotNull(name, "name");
this.anonymous = anonymous;

final class InProcessClientTransportServersBuilder implements ClientTransportServersBuilder {
@Override
Expand Down
35 changes: 33 additions & 2 deletions core/src/main/java/io/grpc/inprocess/InProcessSocketAddress.java
Expand Up @@ -19,6 +19,7 @@
import static com.google.common.base.Preconditions.checkNotNull;

import java.net.SocketAddress;
import javax.annotation.Nullable;

/**
* Custom SocketAddress class for {@link InProcessTransport}.
Expand All @@ -27,13 +28,25 @@ public final class InProcessSocketAddress extends SocketAddress {
private static final long serialVersionUID = -2803441206326023474L;

private final String name;
@Nullable
private final InProcessServer server;

/**
* @param name - The name of the inprocess channel or server.
* @since 1.0.0
*/
public InProcessSocketAddress(String name) {
this(name, null);
}

/**
* @param name - The name of the inprocess channel or server.
* @param server - The concrete {@link InProcessServer} instance, Will be present on the listen
* address of an anonymous server.
*/
InProcessSocketAddress(String name, @Nullable InProcessServer server) {
this.name = checkNotNull(name, "name");
this.server = server;
}

/**
Expand All @@ -45,6 +58,11 @@ public String getName() {
return name;
}

@Nullable
InProcessServer getServer() {
return server;
}

/**
* @since 1.14.0
*/
Expand All @@ -58,7 +76,13 @@ public String toString() {
*/
@Override
public int hashCode() {
return name.hashCode();
if (server != null) {
// Since there's a single canonical InProcessSocketAddress instance for
// an anonymous inprocess server, we can just use identity equality.
return super.hashCode();
} else {
return name.hashCode();
}
}

/**
Expand All @@ -69,6 +93,13 @@ public boolean equals(Object obj) {
if (!(obj instanceof InProcessSocketAddress)) {
return false;
}
return name.equals(((InProcessSocketAddress) obj).name);
InProcessSocketAddress addr = (InProcessSocketAddress) obj;
if (server == null && addr.server == null) {
return name.equals(addr.name);
} else {
// Since there's a single canonical InProcessSocketAddress instance for
// an anonymous inprocess server, we can just use identity equality.
return addr == this;
}
}
}