Skip to content
Draft
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
70 changes: 70 additions & 0 deletions api/src/main/java/io/grpc/ChildChannelConfigurer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2025 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 java.util.function.Consumer;

/**
* A configurer 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 configurer
* ChildChannelConfigurer configurer = builder -> {
* builder.intercept(new MyAuthInterceptor());
* builder.maxInboundMessageSize(4 * 1024 * 1024);
* };
*
* // 2. Apply to parent channel - automatically used for ALL child channels
* ManagedChannel channel = ManagedChannelBuilder
* .forTarget("xds:///my-service")
* .childChannelConfigurer(configurer)
* .build();
* }</pre>
*
* <p>Implementations must be thread-safe as {@link #accept} may be invoked concurrently
* by multiple internal components.
*
* @since 1.79.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
@FunctionalInterface
public interface ChildChannelConfigurer extends Consumer<ManagedChannelBuilder<?>> {

/**
* 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>Note: The provided {@code builder} is generic (`?`). Implementations should use
* universal configuration methods (like {@code intercept()}, {@code userAgent()}) rather
* than casting to specific implementation types.
*
* @param builder the mutable channel builder for the new child channel
*/
@Override
void accept(ManagedChannelBuilder<?> builder);
}
99 changes: 99 additions & 0 deletions api/src/main/java/io/grpc/ChildChannelConfigurers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright 2025 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 com.google.common.base.Preconditions.checkNotNull;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Utilities for working with {@link ChildChannelConfigurer}.
*
* @since 1.79.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public final class ChildChannelConfigurers {
private static final Logger logger = Logger.getLogger(ChildChannelConfigurers.class.getName());

// Singleton no-op instance to avoid object churn
private static final ChildChannelConfigurer NO_OP = builder -> {
};

private ChildChannelConfigurers() { // Prevent instantiation
}

/**
* Returns a configurer that does nothing.
* Useful as a default value to avoid null checks in internal code.
*/
public static ChildChannelConfigurer noOp() {
return NO_OP;
}

/**
* Returns a configurer that applies all the given configurers in sequence.
*
* <p>If any configurer in the chain throws an exception, the remaining ones are skipped
* (unless wrapped in {@link #safe(ChildChannelConfigurer)}).
*
* @param configurers the configurers to apply in order. Null elements are ignored.
*/
public static ChildChannelConfigurer compose(ChildChannelConfigurer... configurers) {
checkNotNull(configurers, "configurers");
return builder -> {
for (ChildChannelConfigurer configurer : configurers) {
if (configurer != null) {
configurer.accept(builder);
}
}
};
}

/**
* Returns a configurer that applies the delegate but catches and logs any exceptions.
*
* <p>This prevents a buggy configurer (e.g., one that fails metric setup) from crashing
* the critical path of channel creation.
*
* @param delegate the configurer to wrap.
*/
public static ChildChannelConfigurer safe(ChildChannelConfigurer delegate) {
checkNotNull(delegate, "delegate");
return builder -> {
try {
delegate.accept(builder);
} catch (Exception e) {
logger.log(Level.WARNING, "Failed to apply child channel configuration", e);
}
};
}

/**
* Returns a configurer that applies the delegate only if the given condition is true.
*
* <p>Useful for applying interceptors only in specific environments (e.g., Debug/Test).
*
* @param condition true to apply the delegate, false to do nothing.
* @param delegate the configurer to apply if condition is true.
*/
public static ChildChannelConfigurer conditional(boolean condition,
ChildChannelConfigurer delegate) {
checkNotNull(delegate, "delegate");
return condition ? delegate : NO_OP;
}
}
12 changes: 12 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,18 @@ public T disableServiceConfigLookUp() {
return thisT();
}

@Override
public T configureChannel(ManagedChannel parentChannel) {
delegate().configureChannel(parentChannel);
return thisT();
}

@Override
public T childChannelConfigurer(ChildChannelConfigurer childChannelConfigurer) {
delegate().childChannelConfigurer(childChannelConfigurer);
return thisT();
}

/**
* Returns the correctly typed version of the builder.
*/
Expand Down
12 changes: 12 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,18 @@ public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
return thisT();
}

@Override
public T configureChannel(ManagedChannel parentChannel) {
delegate().configureChannel(parentChannel);
return thisT();
}

@Override
public T childChannelConfigurer(ChildChannelConfigurer childChannelConfigurer) {
delegate().childChannelConfigurer(childChannelConfigurer);
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/ManagedChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,23 @@ public ConnectivityState getState(boolean requestConnection) {
throw new UnsupportedOperationException("Not implemented");
}

/**
* Returns the configurer for child channels.
*
* <p>This method is intended for use by the internal gRPC infrastructure (specifically
* load balancers and the channel builder) to propagate configuration to child channels.
* Application code should not call this method.
*
* @return the configurer, or {@code null} if none is set.
* @since 1.79.0
*/
@Internal
public ChildChannelConfigurer getChildChannelConfigurer() {
// Return null by default so we don't break existing custom ManagedChannel implementations
// (like wrappers or mocks) that don't override this method.
return null;
}

/**
* Registers a one-off callback that will be run if the connectivity state of the channel diverges
* from the given {@code source}, which is typically what has just been returned by {@link
Expand Down
35 changes: 35 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,41 @@ public <X> T setNameResolverArg(NameResolver.Args.Key<X> key, X value) {
throw new UnsupportedOperationException();
}

/**
* Configures this builder using settings derived from an existing parent channel.
*
* <p>This method is typically used by internal components (like LoadBalancers) when creating
* child channels to ensure they inherit relevant configuration (like the
* {@link ChildChannelConfigurer}) from the parent.
*
* <p>The specific settings copied are implementation dependent, but typically include
* the child channel configurer and potentially user agents or offload executors.
*
* @param parentChannel the channel to inherit configuration from
* @return this
* @since 1.79.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public T configureChannel(ManagedChannel parentChannel) {
throw new UnsupportedOperationException();
}

/**
* Sets a configurer 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
* or OOB load balancing channels.
*
* @param childChannelConfigurer the configurer to apply.
* @return this
* @since 1.79.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/12574")
public T childChannelConfigurer(ChildChannelConfigurer childChannelConfigurer) {
throw new UnsupportedOperationException("Not implemented");
}

/**
* Builds a channel using the given parameters.
*
Expand Down
52 changes: 52 additions & 0 deletions api/src/main/java/io/grpc/MetricRecorder.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@
*/
@Internal
public interface MetricRecorder {

/**
* Returns a {@link MetricRecorder} that performs no operations.
* The returned instance ignores all calls and skips all validation checks.
*/
static MetricRecorder noOp() {
return NoOpMetricRecorder.INSTANCE;
}

/**
* Adds a value for a double-precision counter metric instrument.
*
Expand Down Expand Up @@ -176,4 +185,47 @@ interface Registration extends AutoCloseable {
@Override
void close();
}

/**
* No-Op implementation of MetricRecorder.
* Overrides all default methods to skip validation checks for maximum performance.
*/
final class NoOpMetricRecorder implements MetricRecorder {
private static final NoOpMetricRecorder INSTANCE = new NoOpMetricRecorder();

@Override
public void addDoubleCounter(DoubleCounterMetricInstrument metricInstrument, double value,
List<String> requiredLabelValues,
List<String> optionalLabelValues) {
}

@Override
public void addLongCounter(LongCounterMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues, List<String> optionalLabelValues) {
}

@Override
public void addLongUpDownCounter(LongUpDownCounterMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues,
List<String> optionalLabelValues) {
}

@Override
public void recordDoubleHistogram(DoubleHistogramMetricInstrument metricInstrument,
double value, List<String> requiredLabelValues,
List<String> optionalLabelValues) {
}

@Override
public void recordLongHistogram(LongHistogramMetricInstrument metricInstrument, long value,
List<String> requiredLabelValues,
List<String> optionalLabelValues) {
}

@Override
public Registration registerBatchCallback(BatchCallback callback,
CallbackMetricInstrument... metricInstruments) {
return () -> { };
}
}
}
21 changes: 21 additions & 0 deletions api/src/main/java/io/grpc/NameResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ public static final class Args {
@Nullable private final MetricRecorder metricRecorder;
@Nullable private final NameResolverRegistry nameResolverRegistry;
@Nullable private final IdentityHashMap<Key<?>, Object> customArgs;
@Nullable private final ManagedChannel parentChannel;

private Args(Builder builder) {
this.defaultPort = checkNotNull(builder.defaultPort, "defaultPort not set");
Expand All @@ -337,6 +338,7 @@ private Args(Builder builder) {
this.metricRecorder = builder.metricRecorder;
this.nameResolverRegistry = builder.nameResolverRegistry;
this.customArgs = cloneCustomArgs(builder.customArgs);
this.parentChannel = builder.parentChannel;
}

/**
Expand Down Expand Up @@ -435,6 +437,14 @@ public ChannelLogger getChannelLogger() {
return channelLogger;
}

/**
* Returns the parent {@link ManagedChannel} served by this NameResolver.
*/
@Internal
public ManagedChannel getParentChannel() {
return parentChannel;
}

/**
* 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 @@ -544,6 +554,7 @@ public static final class Builder {
private MetricRecorder metricRecorder;
private NameResolverRegistry nameResolverRegistry;
private IdentityHashMap<Key<?>, Object> customArgs;
private ManagedChannel parentChannel;

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

/**
* See {@link Args#parentChannel}. This is an optional field.
*
* @since 1.79.0
*/
public Builder setParentChannel(ManagedChannel parentChannel) {
this.parentChannel = parentChannel;
return this;
}

/**
* Builds an {@link Args}.
*
Expand Down
Loading