Repository navigation
Removed the synchronous Lock method from AsyncLock class - #256
Conversation
|
Thanks, getting rid of the sync-over-async Lock() is a good move. I have one concern and a few small notes.
OnDisconnected is now async void. Whenever _activeCallsLock is briefly held (e.g. by ProcessRpcResultMessage or InvokeRemoteMethod), it returns before the swap. So DisconnectAsync can complete and raise AfterDisconnect while pending calls are not failed yet, _activeCalls is still set and _goodbyeCompletedEvent isn't set. The window is small, but I see two ways it can bite:
Since DisconnectCoreAsync is already async, I'd suggest awaiting the core method there. The async void wrapper would then only be used for the Disconnected event and the keep-alive timer:
The empty catch hides any failure in the disconnect path. Previously, on the DisconnectCoreAsync path, such errors reached the caller, or OnError via HandleConnectionLost. Maybe route them to OnError(ex) instead of the TODO?
"not sure if we should even lock here": I think the lock is correct. The helper simulates exactly the _activeCalls swap that OnDisconnectedCore does under _activeCallsLock, so I'd just drop the comment.
In InvokeRemoteMethod, the cleanup after a failed send calls _activeCalls.Remove(...) without a null check. If a disconnect nulled the dictionary in the meantime, the caller gets a NullReferenceException instead of the actual transport error. _activeCalls?.Remove(...) would fix it. It could go into this PR or a separate one. |
Good catch! 👍
Agreed :)
I still have my doubts... The point is to simulate error condition, so that the worse the better :)
Thanks! That's a potential bug for sure. |
350aab5 to
8afb379
Compare
|
Thanks for the quick update, looks good to me! 👍 One small thing about the new catch in OnDisconnected: OnError(ex) invokes the user's ErrorHandler directly. If that handler throws, the exception escapes the async void method and takes down the process. Maybe guard it there: Alternatively, OnError itself could be made safe, since it's also called from other fire-and-forget paths such as HandleConnectionLost and the auto-reconnect loop. Not a blocker, though. |
8afb379 to
09f1c08
Compare
|
Thanks, all points are addressed. LGTM! 👍 |
bbdc88a to
4801d55
Compare
|
Main concern: late async disconnect handling can corrupt a newly established connection The PR correctly removes the synchronous AsyncLock.Lock() method and makes the known call sites async. However, OnDisconnected is still an async void handler that mutates shared client state. Although DisconnectCoreAsync now awaits OnDisconnectedCore(), a disconnect event handler may already have been started and may still be running when the client begins reconnecting. In that case, the delayed OnDisconnectedCore() can still execute after ConnectAsync() has reset _goodbyeCompletedEvent for the new connection. This is dangerous because ProcessRpcResultMessage contains: if (_goodbyeCompletedEvent.IsSet) If a late disconnect handler from the old connection sets _goodbyeCompletedEvent, RPC results for the new connection may be silently dropped. The new connection can then appear broken, with calls hanging until timeout or failing unexpectedly. A possible sequence is:
The fix should make disconnect handling connection-scoped. For example, introduce a connection generation/epoch and ensure that disconnect handlers carry the generation they belong to. Late handlers from an old generation should be ignored. DisconnectCoreAsync should also await the completion of the disconnect task for the current connection, not merely invoke its own core method. In short: Awaiting OnDisconnectedCore() inside DisconnectCoreAsync() is an improvement, but it does not eliminate the race caused by the still-existing async void disconnect handler. Before merging, the disconnect path should be made idempotent per connection generation so that a delayed disconnect from an old connection cannot affect a newly established one. |
|
Uhhhh... I agree with @theRainbird here. My earlier point only covered the direct call in DisconnectCoreAsync, not the event path. The transports raise Disconnected on their own threads (read loop, WatsonTcp event), where the async void handler starts and can't be awaited. On a manual disconnect, OnDisconnectedCore therefore runs twice: once directly from DisconnectCoreAsync and once via the event. The event one can still be queued on _activeCallsLock when ConnectAsync() runs. I think the late handler can do more damage than just setting _goodbyeCompletedEvent. When it finally gets the lock, _activeCalls is already the new connection's dictionary. It then:
I haven't reproduced this, it's from reading the code. The race itself isn't new: the old sync handler could also block on the lock from a foreign thread. But this PR doesn't fix it either. A connection generation seems to be enough, without restructuring the disconnect path:
A handler that is raised only after the reconnect would read the new generation and can't be recognized this way. That has to be handled by the transports, and they already do it via IsCurrentReadLoop. I'm fine with fixing it in this PR if it stays small, or tracking it as a separate issue. @yallie, what do you prefer? |
|
Yes, I agree with both of you. Thanks for your reviews! :) |
Test on windows to update the badge.
4801d55 to
c3b88e0
Compare
using var client = CreateClient(networkPort, AuthenticationRequiredForNegativeTests);
await client.ConnectAsync().ConfigureAwait(false);
var proxy = client.CreateProxy<ITestService>();
// 1. Capture the generation of the initial connection
var oldGeneration = client.ConnectionGenerationForTest;
// 2. Reconnect: this bumps the generation and creates a new _activeCalls dictionary
await client.DisconnectAsync().ConfigureAwait(false);
await client.ConnectAsync().ConfigureAwait(false);
// 3. Simulate a late handler from the OLD connection that just woke up.
// Without the generation check, this would null out the new _activeCalls.
await client.InvokeOnDisconnectedCoreAsync(oldGeneration).ConfigureAwait(false);
// 4. The new connection must be completely unaffected,
// keep-alive still running, RPC works.
Assert.True(client.IsConnected);
Assert.Equal("test", await proxy.EchoAsync("test").ConfigureAwait(false));Also, rebased this PR onto master. |
I'm not sure but it just doesn't feel right to have this method on async locking primitive.
Also, SemaphoreSlim is non-reentrant, so normal
lockstatement is probably safer to use.Anyway, both places where Lock is used can be refactored to become async methods.