-
Notifications
You must be signed in to change notification settings - Fork 4k
feat(xds): Add filter state reference-counted resource management #12879
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
Open
sauravzg
wants to merge
1
commit into
grpc:master
Choose a base branch
from
sauravzg:sauravz/filter-state-retention
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
205 changes: 205 additions & 0 deletions
205
xds/src/main/java/io/grpc/xds/SharedResourceManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| /* | ||
| * 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.xds; | ||
|
|
||
| import com.google.common.base.Preconditions; | ||
| import io.grpc.Internal; | ||
| import io.grpc.ManagedChannel; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.ConcurrentMap; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
| import java.util.function.Function; | ||
| import javax.annotation.concurrent.ThreadSafe; | ||
|
|
||
| /** | ||
| * Manages generic reference-counted shared resources for xDS filters. | ||
| * | ||
| * <p>Similar to {@code io.grpc.xds.internal.security.ReferenceCountingMap}, but provides | ||
| * additional lifecycle management ({@link #close()}) and a simpler key-only | ||
| * {@link #release(Object)} API designed for xDS filter state cleanup tasks. | ||
| */ | ||
| @Internal | ||
| public final class SharedResourceManager<K, V extends SharedResourceManager.ResourceCloseable> { | ||
|
|
||
| /** | ||
| * An AutoCloseable resource that explicitly guarantees its close operation | ||
| * will not throw checked exceptions. | ||
| */ | ||
| public interface ResourceCloseable extends AutoCloseable { | ||
| @Override | ||
| void close(); | ||
| } | ||
|
|
||
| /** | ||
| * Adapts {@link ManagedChannel} to {@link ResourceCloseable} for management by | ||
| * {@link SharedResourceManager}. | ||
| */ | ||
| public static final class ManagedChannelResource implements ResourceCloseable { | ||
| private final ManagedChannel channel; | ||
|
|
||
| public ManagedChannelResource(ManagedChannel channel) { | ||
| this.channel = Preconditions.checkNotNull(channel, "channel"); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| channel.shutdown(); | ||
| } | ||
|
|
||
| public ManagedChannel getChannel() { | ||
| return channel; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * An internal pure reference-counting container managing a stateful ResourceCloseable. | ||
| */ | ||
| @ThreadSafe | ||
| static final class SharedResource<T extends ResourceCloseable> { | ||
| private final T resource; | ||
| private final AtomicInteger refCount = new AtomicInteger(1); | ||
|
|
||
| SharedResource(T resource) { | ||
| this.resource = Preconditions.checkNotNull(resource, "resource"); | ||
| } | ||
|
|
||
| /** | ||
| * Retains the resource. Returns false if the resource has hit 0 and is being closed. | ||
| */ | ||
| boolean retain() { | ||
| int count; | ||
| do { | ||
| count = refCount.get(); | ||
| if (count == 0) { | ||
| return false; | ||
| } | ||
| } while (!refCount.compareAndSet(count, count + 1)); | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Decrements reference count. Closes underlying resource if count hits 0. | ||
| * @return true if the count reached 0 and the resource was closed; false otherwise. | ||
| */ | ||
| boolean release() { | ||
| int count = refCount.decrementAndGet(); | ||
| if (count < 0) { | ||
| throw new AssertionError("SharedResourceManager reference count dropped below 0"); | ||
| } | ||
| if (count == 0) { | ||
| resource.close(); | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| T get() { | ||
| return resource; | ||
| } | ||
|
|
||
| int getRefCount() { | ||
| return refCount.get(); | ||
| } | ||
| } | ||
|
|
||
| private final ConcurrentMap<K, SharedResource<V>> resources = new ConcurrentHashMap<>(); | ||
| private final Function<K, V> resourceCreator; | ||
| private final Object closeLock = new Object(); | ||
| private volatile boolean closed; | ||
|
|
||
| public SharedResourceManager(Function<K, V> resourceCreator) { | ||
| this.resourceCreator = resourceCreator; | ||
| } | ||
|
|
||
| /** | ||
| * Acquires a resource for the given key, incrementing its reference count. | ||
| */ | ||
| public V acquire(K key) { | ||
| while (true) { | ||
| SharedResource<V> shared = resources.get(key); | ||
| if (shared == null) { | ||
| SharedResource<V> newShared = new SharedResource<>(resourceCreator.apply(key)); | ||
| synchronized (closeLock) { | ||
| if (closed) { | ||
| newShared.release(); | ||
| throw new IllegalStateException("SharedResourceManager is closed"); | ||
| } | ||
| shared = resources.putIfAbsent(key, newShared); | ||
| } | ||
| if (shared == null) { | ||
| return newShared.get(); | ||
| } | ||
| // Lost the race: close the resource we created to prevent leaks. | ||
| newShared.release(); | ||
| } | ||
| if (shared.retain()) { | ||
| return shared.get(); | ||
| } | ||
| // If retain failed, it's being evicted concurrently. Loop to compute a new one. | ||
| resources.remove(key, shared); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Releases a resource for the given key, decrementing its reference count. | ||
| * Closes and evicts the resource if the reference count reaches 0. | ||
| * | ||
| * <p>In the xDS filter state lifecycle, this method is invoked from cleanup | ||
| * tasks that execute within the {@code SynchronizationContext}. | ||
| * | ||
| * @return true if the resource was closed; false otherwise. | ||
| */ | ||
| public boolean release(K key) { | ||
| SharedResource<V> shared = resources.get(key); | ||
| if (shared == null) { | ||
| return false; | ||
| } | ||
| try { | ||
| if (shared.release()) { | ||
| return resources.remove(key, shared); | ||
| } | ||
| } catch (Throwable t) { | ||
| resources.remove(key, shared); | ||
| throw t; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * Removes all entries from the cache and releases the manager's reference for each. | ||
| * | ||
| * <p>This intentionally performs a single {@code release()} per entry, decrementing the | ||
| * manager's own reference count contribution. If in-flight RPCs still hold references, | ||
| * the underlying resource remains open until those references are released. This avoids | ||
| * pulling resources out from under active operations. | ||
| */ | ||
| public void close() { | ||
| synchronized (closeLock) { | ||
| closed = true; | ||
| } | ||
| for (K key : resources.keySet()) { | ||
| SharedResource<V> shared = resources.remove(key); | ||
| if (shared != null) { | ||
| try { | ||
| shared.release(); | ||
| } catch (Throwable t) { | ||
| // Ignore exceptions during final close-all to ensure we try to close other resources | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So, one of the things that I was in thoughts about was , if we should make this class simpler by making this entire map class synchronized (like ReferenceCountingMap in io..xds....security) instead of trying to deal with corner cases around atomic consistency which are difficult to understand and document.
Another thing worth considering is that potentially all operations on the map happen in syncContext since this map is only used when calling
buildInterceptorwhich happens in syncContext , the release also either happens during similar control plane updates so synccontext.It's possible for the cleanup to happen after an RPC end or close , but that's also covered since we do it inside synccontext using a RouteWrapper.
So, we may entirely not need this class to be thread safe.
So, I want opinions on where we should lean towards. IIUC, the ClusterRefState has semantics where it can be
getfrom any thread and mutations from sync context.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Moving the synchronization down to the individual resource level and using a lock-free design for the hot path is superior. In a coarse-grained design where we do it at the SharedResourceManager (map) level, every single RPC across different ext-proc addresses would have to acquire a single global lock on SharedResourceManager during acquire and release.
It is not true that all operations on the map happen in syncContext.
buildClientInterceptoris called when processing xDS updates on the Control plane in a syncContext. Not theSharedResourceManager.acquireandSharedResourceManager.release. acquire happen on the application's RPC thread and release on the transport thread that callsonClosewhen the rpc completes.