Skip to content
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions api/src/main/java/io/grpc/ChannelConfigurator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright 2026 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc;



/**
* A configurator for child channels created by gRPC's internal infrastructure.
*
* <p>This interface allows users to inject configuration (such as credentials, interceptors,
* or flow control settings) into channels created automatically by gRPC for control plane
* operations. Common use cases include:
* <ul>
* <li>xDS control plane connections</li>
* <li>Load Balancing helper channels (OOB channels)</li>
* </ul>
*
* <p><strong>Usage Example:</strong>
* <pre>{@code
* // 1. Define the configurator
* ChannelConfigurator configurator = builder -> {
* builder.maxInboundMessageSize(4 * 1024 * 1024);
* };
*
* // 2. Apply to parent channel - automatically used for ALL child channels
* ManagedChannel channel = ManagedChannelBuilder
* .forTarget("xds:///my-service")
* .childChannelConfigurator(configurator)
* .build();
* }</pre>
*
* <p>Implementations must be thread-safe as the configure methods may be invoked concurrently
* by multiple internal components.
*
* @since 1.81.0
Comment thread
AgraVator marked this conversation as resolved.
Outdated
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public interface ChannelConfigurator {

/**
* Configures a builder for a new child channel.
*
* <p>This method is invoked synchronously during the creation of the child channel,
* before {@link ManagedChannelBuilder#build()} is called.
*
* @param builder the mutable channel builder for the new child channel
*/
default void configureChannelBuilder(ManagedChannelBuilder<?> builder) {}
Comment thread
AgraVator marked this conversation as resolved.
Outdated
}
7 changes: 7 additions & 0 deletions api/src/main/java/io/grpc/ForwardingChannelBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ public T disableServiceConfigLookUp() {
return thisT();
}


@Override
public T childChannelConfigurator(ChannelConfigurator channelConfigurator) {
delegate().childChannelConfigurator(channelConfigurator);
return thisT();
}

/**
* Returns the correctly typed version of the builder.
*/
Expand Down
9 changes: 8 additions & 1 deletion api/src/main/java/io/grpc/ForwardingChannelBuilder2.java
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ public T disableServiceConfigLookUp() {
}

@Override
protected T addMetricSink(MetricSink metricSink) {
public T addMetricSink(MetricSink metricSink) {
delegate().addMetricSink(metricSink);
return thisT();
}
Expand All @@ -269,6 +269,13 @@ public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
return thisT();
}


@Override
public T childChannelConfigurator(ChannelConfigurator channelConfigurator) {
delegate().childChannelConfigurator(channelConfigurator);
return thisT();
}

/**
* Returns the {@link ManagedChannel} built by the delegate by default. Overriding method can
* return different value.
Expand Down
6 changes: 6 additions & 0 deletions api/src/main/java/io/grpc/ForwardingServerBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ public T setBinaryLog(BinaryLog binaryLog) {
return thisT();
}

@Override
public T childChannelConfigurator(ChannelConfigurator channelConfigurator) {
delegate().childChannelConfigurator(channelConfigurator);
return thisT();
}

/**
* Returns the {@link Server} built by the delegate by default. Overriding method can return
* different value.
Expand Down
22 changes: 18 additions & 4 deletions api/src/main/java/io/grpc/ManagedChannelBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,6 @@ protected T interceptWithTarget(InterceptorFactory factory) {
throw new UnsupportedOperationException();
}

/** Internal-only. */
@Internal
Comment thread
AgraVator marked this conversation as resolved.
protected interface InterceptorFactory {
ClientInterceptor newInterceptor(String target);
}
Expand Down Expand Up @@ -638,8 +636,7 @@ public T disableServiceConfigLookUp() {
* @return this
* @since 1.64.0
*/
@Internal
protected T addMetricSink(MetricSink metricSink) {
public T addMetricSink(MetricSink metricSink) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What's happening here? Why will this no longer be internal? Even if we were going to make it public, we wouldn't have it go immediately stable; it'd be experimental first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

When an application or test implements ChannelConfigurator, it receives a reference to the child channel's ManagedChannelBuilder.
If addMetricSink were protected (or package-private), then class implementations of ChannelConfigurator outside of the io.grpc package (such as user applications or test suites like FakeControlPlaneXdsIntegrationTest.java) would not be able to call builder.addMetricSink(sink) to register their metric sinks.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What is the problem with that? What new thing do they need to do because of ChannelConfigurator? If addMetricSink() being hidden was a problem, wouldn't that be a pre-existing problem?

GrpcOpenTelemetry.configureChannelBuilder() still works fine with ChannelConfigurator, and it calls addMetricSink() on the user's behalf.

throw new UnsupportedOperationException();
}

Expand All @@ -661,6 +658,23 @@ public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
throw new UnsupportedOperationException();
}


/**
* Sets a configurator that will be applied to all internal child channels created by this
* channel.
*
* <p>This allows injecting configuration (like credentials, interceptors, or flow control)
* into auxiliary channels created by gRPC infrastructure, such as xDS control plane connections.
*
* @param channelConfigurator the configurator to apply.
* @return this
* @since 1.81.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public T childChannelConfigurator(ChannelConfigurator channelConfigurator) {
throw new UnsupportedOperationException("Not implemented");
}

/**
* Builds a channel using the given parameters.
*
Expand Down
24 changes: 24 additions & 0 deletions api/src/main/java/io/grpc/NameResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ public static final class Args {
private final MetricRecorder metricRecorder;
@Nullable private final NameResolverRegistry nameResolverRegistry;
@Nullable private final IdentityHashMap<Key<?>, Object> customArgs;
@Nullable private final ChannelConfigurator channelConfigurator;

private Args(Builder builder) {
this.defaultPort = checkNotNull(builder.defaultPort, "defaultPort not set");
Expand All @@ -373,6 +374,7 @@ private Args(Builder builder) {
: new MetricRecorder() {};
this.nameResolverRegistry = builder.nameResolverRegistry;
this.customArgs = cloneCustomArgs(builder.customArgs);
this.channelConfigurator = builder.channelConfigurator;
}

/**
Expand Down Expand Up @@ -471,6 +473,17 @@ public ChannelLogger getChannelLogger() {
return channelLogger;
}

/**
* Returns the configurator for child channels.
*
* @since 1.81.0
*/
@Nullable
Comment thread
AgraVator marked this conversation as resolved.
Outdated
@Internal
public ChannelConfigurator getChildChannelConfigurator() {
return channelConfigurator;
}

/**
* Returns the Executor on which this resolver should execute long-running or I/O bound work.
* Null if no Executor was set.
Expand Down Expand Up @@ -579,6 +592,7 @@ public static final class Builder {
private MetricRecorder metricRecorder;
private NameResolverRegistry nameResolverRegistry;
private IdentityHashMap<Key<?>, Object> customArgs;
private ChannelConfigurator channelConfigurator = new ChannelConfigurator() {};

Builder() {
}
Expand Down Expand Up @@ -694,6 +708,16 @@ public Builder setNameResolverRegistry(NameResolverRegistry registry) {
return this;
}

/**
* See {@link Args#getChildChannelConfigurator()}. This is an optional field.
*
* @since 1.81.0
*/
public Builder setChildChannelConfigurator(ChannelConfigurator channelConfigurator) {
this.channelConfigurator = channelConfigurator;
Comment thread
AgraVator marked this conversation as resolved.
Outdated
return this;
}

/**
* Builds an {@link Args}.
*
Expand Down
18 changes: 18 additions & 0 deletions api/src/main/java/io/grpc/ServerBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,24 @@ public T setBinaryLog(BinaryLog binaryLog) {
throw new UnsupportedOperationException();
}


/**
* Sets a configurator that will be applied to all internal child channels created by this server.
*
* <p>This allows injecting configuration (like credentials, interceptors, or flow control)
* into auxiliary channels created by gRPC infrastructure, such as xDS control plane connections
* or OOB load balancing channels.
*
* @param channelConfigurator the configurator to apply.
* @return this
* @since 1.81.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public T childChannelConfigurator(ChannelConfigurator channelConfigurator) {
Comment thread
AgraVator marked this conversation as resolved.
Outdated
throw new UnsupportedOperationException("Not implemented");
}


/**
* Builds a server using the given parameters.
*
Expand Down
37 changes: 37 additions & 0 deletions api/src/test/java/io/grpc/ChannelConfiguratorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2026 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class ChannelConfiguratorTest {

@Test
public void defaultMethods_doNothing() {
ChannelConfigurator configurator = new ChannelConfigurator() {};

ManagedChannelBuilder<?> mockChannelBuilder = mock(ManagedChannelBuilder.class);
configurator.configureChannelBuilder(mockChannelBuilder);
verifyNoInteractions(mockChannelBuilder);
}
}
38 changes: 38 additions & 0 deletions api/src/test/java/io/grpc/NameResolverTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ public void args() {
}

private NameResolver.Args createArgs() {
ChannelConfigurator channelConfigurator = new ChannelConfigurator() {};
return NameResolver.Args.newBuilder()
.setDefaultPort(defaultPort)
.setProxyDetector(proxyDetector)
Expand All @@ -116,9 +117,46 @@ private NameResolver.Args createArgs() {
.setOverrideAuthority(overrideAuthority)
.setMetricRecorder(metricRecorder)
.setArg(FOO_ARG_KEY, customArgValue)
.setChildChannelConfigurator(channelConfigurator)
.build();
}

@Test
public void args_childChannelConfigurator() {
final ManagedChannelBuilder<?>[] capturedBuilder = new ManagedChannelBuilder<?>[1];
ChannelConfigurator channelConfigurator = new ChannelConfigurator() {
@Override
public void configureChannelBuilder(ManagedChannelBuilder<?> builder) {
capturedBuilder[0] = builder;
}
};

SynchronizationContext realSyncContext = new SynchronizationContext(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
throw new AssertionError(e);
}
});

NameResolver.Args args = NameResolver.Args.newBuilder()
.setDefaultPort(8080)
.setProxyDetector(mock(ProxyDetector.class))
.setSynchronizationContext(realSyncContext)
.setServiceConfigParser(mock(NameResolver.ServiceConfigParser.class))
.setChannelLogger(mock(ChannelLogger.class))
.setChildChannelConfigurator(channelConfigurator)
.build();

ChannelConfigurator configurator = args.getChildChannelConfigurator();
assertThat(configurator).isSameInstanceAs(channelConfigurator);

// Validate configurator accepts builders
ManagedChannelBuilder<?> mockBuilder = mock(ManagedChannelBuilder.class);
configurator.configureChannelBuilder(mockBuilder);
assertThat(capturedBuilder[0]).isSameInstanceAs(mockBuilder);
}

@Test
@SuppressWarnings("deprecation")
public void startOnOldListener_wrapperListener2UsedToStart() {
Expand Down
21 changes: 20 additions & 1 deletion core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import io.grpc.CallCredentials;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ChannelConfigurator;
import io.grpc.ChannelCredentials;
import io.grpc.ChannelLogger;
import io.grpc.ChannelLogger.ChannelLogLevel;
Expand Down Expand Up @@ -155,6 +156,14 @@ public Result selectConfig(PickSubchannelArgs args) {
private static final LoadBalancer.PickDetailsConsumer NOOP_PICK_DETAILS_CONSUMER =
new LoadBalancer.PickDetailsConsumer() {};

/**
* Retrieves the user-provided configuration function for internal child channels.
*
* <p>This is intended for use by gRPC internal components
* that are responsible for creating auxiliary {@code ManagedChannel} instances.
*/
private ChannelConfigurator channelConfigurator = new ChannelConfigurator() {};
Comment thread
AgraVator marked this conversation as resolved.
Outdated

private final InternalLogId logId;
private final String target;
@Nullable
Expand Down Expand Up @@ -545,6 +554,9 @@ ClientStream newSubstream(
Supplier<Stopwatch> stopwatchSupplier,
List<ClientInterceptor> interceptors,
final TimeProvider timeProvider) {
if (builder.channelConfigurator != null) {
Comment thread
AgraVator marked this conversation as resolved.
Outdated
this.channelConfigurator = builder.channelConfigurator;
}
this.target = checkNotNull(builder.target, "target");
this.logId = InternalLogId.allocate("Channel", target);
this.timeProvider = checkNotNull(timeProvider, "timeProvider");
Expand Down Expand Up @@ -589,7 +601,8 @@ ClientStream newSubstream(
.setOffloadExecutor(this.offloadExecutorHolder)
.setOverrideAuthority(this.authorityOverride)
.setMetricRecorder(this.metricRecorder)
.setNameResolverRegistry(builder.nameResolverRegistry);
.setNameResolverRegistry(builder.nameResolverRegistry)
.setChildChannelConfigurator(this.channelConfigurator);
builder.copyAllNameResolverCustomArgsTo(nameResolverArgsBuilder);
this.nameResolverArgs = nameResolverArgsBuilder.build();
this.nameResolver = getNameResolver(
Expand Down Expand Up @@ -1486,6 +1499,12 @@ protected ManagedChannelBuilder<?> delegate() {

ResolvingOobChannelBuilder builder = new ResolvingOobChannelBuilder();

// Note that we follow the global configurator pattern and try to fuse the configurations as
// soon as the builder gets created
if (channelConfigurator != null) {
Comment thread
AgraVator marked this conversation as resolved.
Outdated
channelConfigurator.configureChannelBuilder(builder);
}

return builder
// TODO(zdapeng): executors should not outlive the parent channel.
.executor(executor)
Expand Down
Loading
Loading