Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
71 changes: 71 additions & 0 deletions api/src/main/java/io/grpc/ChannelConfigurator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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.83.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
Comment thread
AgraVator marked this conversation as resolved.
@FunctionalInterface
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.
*
* <p><strong>Note:</strong> Implementations must only apply configurations to the
* provided builder and must NOT call {@code builder.build()} themselves.
*
* <p><strong>Note:</strong> The provided {@code builder} is generic ({@code ?}). Implementations
* should use universal configuration methods (like {@code intercept()}, {@code userAgent()}) on the builder
* rather than casting it to specific implementation types.
*
* @param builder the mutable channel builder for the new child channel
*/
Comment thread
AgraVator marked this conversation as resolved.
Comment thread
AgraVator marked this conversation as resolved.
void configureChannelBuilder(ManagedChannelBuilder<?> builder);
}
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
7 changes: 7 additions & 0 deletions api/src/main/java/io/grpc/ForwardingChannelBuilder2.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 17 additions & 0 deletions api/src/main/java/io/grpc/ManagedChannelBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,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.83.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
23 changes: 23 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;
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,16 @@ public ChannelLogger getChannelLogger() {
return channelLogger;
}

/**
* Returns the configurator for child channels.
*
* @since 1.83.0
*/
@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 +591,7 @@ public static final class Builder {
private MetricRecorder metricRecorder;
private NameResolverRegistry nameResolverRegistry;
private IdentityHashMap<Key<?>, Object> customArgs;
private ChannelConfigurator channelConfigurator = builder -> { };

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

/**
* See {@link Args#getChildChannelConfigurator()}. This is an optional field.
*
* @since 1.83.0
*/
public Builder setChildChannelConfigurator(ChannelConfigurator channelConfigurator) {
this.channelConfigurator = checkNotNull(channelConfigurator, "channelConfigurator");
return this;
}

/**
* Builds an {@link Args}.
*
Expand Down
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 = builder -> { };
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
18 changes: 17 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 final ChannelConfigurator channelConfigurator;

private final InternalLogId logId;
private final String target;
@Nullable
Expand Down Expand Up @@ -545,6 +554,8 @@ ClientStream newSubstream(
Supplier<Stopwatch> stopwatchSupplier,
List<ClientInterceptor> interceptors,
final TimeProvider timeProvider) {
this.channelConfigurator = checkNotNull(builder.channelConfigurator,
"channelConfigurator");
this.target = checkNotNull(builder.target, "target");
this.logId = InternalLogId.allocate("Channel", target);
this.timeProvider = checkNotNull(timeProvider, "timeProvider");
Expand Down Expand Up @@ -589,7 +600,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 +1498,10 @@ 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
channelConfigurator.configureChannelBuilder(builder);

return builder
// TODO(zdapeng): executors should not outlive the parent channel.
.executor(executor)
Expand Down
11 changes: 11 additions & 0 deletions core/src/main/java/io/grpc/internal/ManagedChannelImplBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import io.grpc.CallCredentials;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ChannelConfigurator;
import io.grpc.ChannelCredentials;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
Expand Down Expand Up @@ -149,6 +150,8 @@ public static ManagedChannelBuilder<?> forTarget(String target) {
}


ChannelConfigurator channelConfigurator = builder -> { };

ObjectPool<? extends Executor> executorPool = DEFAULT_EXECUTOR_POOL;

ObjectPool<? extends Executor> offloadExecutorPool = DEFAULT_EXECUTOR_POOL;
Expand Down Expand Up @@ -717,6 +720,14 @@ protected ManagedChannelImplBuilder addMetricSink(MetricSink metricSink) {
return this;
}

@Override
public ManagedChannelImplBuilder childChannelConfigurator(
ChannelConfigurator channelConfigurator) {
this.channelConfigurator = checkNotNull(channelConfigurator,
"childChannelConfigurator");
return this;
}

@Override
public ManagedChannel build() {
ClientTransportFactory clientTransportFactory =
Expand Down
Loading
Loading