-
Notifications
You must be signed in to change notification settings - Fork 887
Stop leaking change token registrations #7674
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
ismailbennani
wants to merge
3
commits into
dotnet:main
Choose a base branch
from
ismailbennani:issue-7673-service-discovery-change-token-leak
base: main
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.
+666
−1
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
187 changes: 187 additions & 0 deletions
187
src/Libraries/Microsoft.Extensions.ServiceDiscovery/Internal/LinkedChangeToken.cs
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,187 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.Extensions.Primitives; | ||
|
|
||
| namespace Microsoft.Extensions.ServiceDiscovery.Internal; | ||
|
|
||
| /// <summary> | ||
| /// An <see cref="IChangeToken"/> which signals when any of the change tokens it is linked to signals. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// This serves the same purpose as <see cref="CompositeChangeToken"/>, but it holds callbacks on its sources | ||
| /// only for as long as a consumer is listening. <see cref="CompositeChangeToken"/> registers on its sources on | ||
| /// behalf of its consumers and releases those registrations only when it signals, so linking a token which | ||
| /// never signals roots the composite and everything it references for the lifetime of that source. | ||
| /// </para> | ||
| /// <para> | ||
| /// Here a consumer's registration is made directly on each source and owns those source registrations, so a | ||
| /// consumer releasing its own registration, which is what consumers already do, is all that is needed. Nothing | ||
| /// has to remember to release this token. | ||
| /// </para> | ||
| /// <para> | ||
| /// Registering directly on the sources also means the callback behaviour of this token is whatever its sources | ||
| /// provide, rather than being reshaped by an intermediate <see cref="CancellationTokenSource"/>. As | ||
| /// <see cref="IChangeToken"/> allows, callbacks are best effort; <see cref="HasChanged"/>, which polls the | ||
| /// sources, is the reliable way to observe a change. | ||
| /// </para> | ||
| /// </remarks> | ||
| internal sealed class LinkedChangeToken : IChangeToken | ||
| { | ||
| private readonly IReadOnlyList<IChangeToken> _sources; | ||
| private volatile bool _hasChanged; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new <see cref="LinkedChangeToken"/> instance. | ||
| /// </summary> | ||
| /// <param name="sources">The change tokens to link to.</param> | ||
| public LinkedChangeToken(IReadOnlyList<IChangeToken> sources) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(sources); | ||
|
|
||
| _sources = sources; | ||
|
|
||
| for (var i = 0; i < sources.Count; i++) | ||
| { | ||
| if (sources[i].ActiveChangeCallbacks) | ||
| { | ||
| ActiveChangeCallbacks = true; | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| /// <remarks> | ||
| /// Callbacks are raised only by sources which raise them. Changes to the other sources are observed only by | ||
| /// polling <see cref="HasChanged"/>, which matches <see cref="CompositeChangeToken"/>. | ||
| /// </remarks> | ||
| public bool ActiveChangeCallbacks { get; } | ||
|
|
||
| /// <inheritdoc/> | ||
| public bool HasChanged | ||
| { | ||
| get | ||
| { | ||
| if (_hasChanged) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| for (var i = 0; i < _sources.Count; i++) | ||
| { | ||
| if (_sources[i].HasChanged) | ||
| { | ||
| _hasChanged = true; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public IDisposable RegisterChangeCallback(Action<object?> callback, object? state) | ||
| { | ||
| var registration = new Registration(this, callback, state); | ||
|
|
||
| // Linked after construction rather than in the constructor, because a source which has already signaled | ||
| // raises the callback during linking and must not observe a partially constructed registration. | ||
| registration.LinkToSources(); | ||
| return registration; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// A consumer's registration, which holds that consumer's registration on each of the sources and releases | ||
| /// them when it is disposed or when one of the sources signals. | ||
| /// </summary> | ||
| private sealed class Registration : IDisposable | ||
| { | ||
| // Cached so that registering on a source does not allocate a delegate. The callback shape is dictated by | ||
| // IChangeToken.RegisterChangeCallback; passing the registration as its state keeps it closure-free. | ||
| private static readonly Action<object?> s_onSourceSignaled = static state => ((Registration)state!).OnSourceSignaled(); | ||
|
|
||
| private readonly LinkedChangeToken _token; | ||
| private readonly IDisposable?[] _sourceRegistrations; | ||
| private Action<object?>? _callback; | ||
| private object? _state; | ||
|
|
||
| public Registration(LinkedChangeToken token, Action<object?> callback, object? state) | ||
| { | ||
| _token = token; | ||
| _callback = callback; | ||
| _state = state; | ||
| _sourceRegistrations = new IDisposable?[token._sources.Count]; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Registers this consumer's callback on each source which raises callbacks. | ||
| /// </summary> | ||
| public void LinkToSources() | ||
| { | ||
| var sources = _token._sources; | ||
|
|
||
| for (var i = 0; i < sources.Count; i++) | ||
| { | ||
| if (sources[i].ActiveChangeCallbacks) | ||
| { | ||
| // A source which has already signaled may raise the callback here, synchronously. Sources | ||
| // backed by a CancellationToken do, but IChangeToken does not require it, so a change is | ||
| // only reliably observed by polling HasChanged. | ||
| _sourceRegistrations[i] = sources[i].RegisterChangeCallback(s_onSourceSignaled, this); | ||
| } | ||
| } | ||
|
|
||
| // A null callback means a source signaled, or the consumer disposed, while this loop was still | ||
| // running, so Release could not see every registration it was meant to release. Release the rest. | ||
| if (Volatile.Read(ref _callback) is null) | ||
| { | ||
| Release(); | ||
| } | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| // Cleared before releasing, so that a concurrent LinkToSources sees that it has to release the | ||
| // registrations it makes after this point. | ||
| Interlocked.Exchange(ref _callback, null); | ||
| _state = null; | ||
| Release(); | ||
| } | ||
|
|
||
| private void OnSourceSignaled() | ||
| { | ||
| // Only the first source to signal raises the consumer's callback, and a consumer which has disposed | ||
| // its registration is not called at all. | ||
| if (Interlocked.Exchange(ref _callback, null) is not { } callback) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var state = _state; | ||
| _state = null; | ||
| _token._hasChanged = true; | ||
|
|
||
| try | ||
| { | ||
| callback(state); | ||
| } | ||
| finally | ||
| { | ||
| Release(); | ||
| } | ||
| } | ||
|
|
||
| private void Release() | ||
| { | ||
| for (var i = 0; i < _sourceRegistrations.Length; i++) | ||
| { | ||
| // Exchanged so that releasing more than once, which linking and a signaling source can both | ||
| // cause, disposes each source registration exactly once. | ||
| Interlocked.Exchange(ref _sourceRegistrations[i], null)?.Dispose(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
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.
Request changes
There is a race between
DisposeandOnSourceSignaledin this implementation. IfOnSourceSignaledwins the callback exchange at line 158,Disposecan still clear_statehere before the callback reads it at line 163. The callback is then invoked withnullstate.This can cause the watcher callback in
ServiceEndpointWatcher.cs:175to throw when it casts and uses the state as aServiceEndpointWatcher.Please make callback and state ownership atomic. Disposal should clear the state only if it successfully suppresses the callback; otherwise, the signaling path must retain and consume the original state.
I tried the following regression test locally, including the
ManualChangeTokenhelper below, and it reproduced the suspected race on the current implementation:Please add an equivalent regression test, preferably with a deterministic synchronization point around the callback/state handoff so the race does not depend solely on iteration count, and update the implementation so the callback always receives the state supplied during registration.
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.
The only way I found to force the disposal between the exchange and the read of the state was to introduce an event callback between them. I made it internal and explained in its documentation that it is there only for tests.