Skip to content
Merged
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
1 change: 1 addition & 0 deletions src/StackExchange.Redis/ConnectionMultiplexer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1428,6 +1428,7 @@ internal void OnHeartbeat()

CheckTopologyRefreshDue(now);
if (_isSentinel) CheckManagedPrimariesDemoted();
ProcessRetiringSubscriptions();

// the core's endpoints, for the same reason the snapshot below is pulsed: a late reply
// announces itself to nobody, so noticing one is work that happens on a clock.
Expand Down
115 changes: 115 additions & 0 deletions src/StackExchange.Redis/RedisSubscriber.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ public partial class ConnectionMultiplexer

private readonly ConcurrentDictionary<RedisChannel, Subscription> subscriptions = new();

// retired subscriptions the server may still hold (an unsubscribe was declined, timed out, never written, or
// deferred), until an unsubscribe is confirmed or the connection drops; see ProcessRetiringSubscriptions
private readonly ConcurrentDictionary<Subscription, RedisChannel> _retiringSubscriptions = new();

internal ConcurrentDictionary<RedisChannel, Subscription> GetSubscriptions() => subscriptions;
ConcurrentDictionary<RedisChannel, Subscription> IInternalConnectionMultiplexer.GetSubscriptions() => GetSubscriptions();

Expand Down Expand Up @@ -224,6 +228,105 @@ internal void OnMessage(in RedisChannel subscription, in RedisChannel channel, i
}
}

internal void TrackRetiringSubscription(Subscription sub, in RedisChannel channel)
=> _retiringSubscriptions.TryAdd(sub, channel);

internal void UntrackRetiringSubscription(Subscription sub)
=> _retiringSubscriptions.TryRemove(sub, out _);

internal int GetRetiringSubscriptionsCount() => _retiringSubscriptions.Count;

/// <summary>
/// Re-issue the unsubscribes of retired subscriptions the server may still hold - because it declined one
/// (<c>BUSY</c>, <c>LOADING</c>, <c>MASTERDOWN</c>), one timed out or was never written, or a subscribe was
/// still in flight - from the heartbeat and the restore paths, so that retries live as long as the multiplexer.
/// Without this, the server stays subscribed, pushing messages nothing receives, until the connection is
/// replaced.
/// </summary>
internal void ProcessRetiringSubscriptions()
{
if (_isDisposed || _retiringSubscriptions.IsEmpty) return;

foreach (var pair in _retiringSubscriptions)
{
var sub = pair.Key;
try
{
sub.RemoveDisconnectedEndpoints();
if (!sub.IsConnectedAny())
{
// nothing left to unsubscribe: a dropped connection took the registration with it
_retiringSubscriptions.TryRemove(sub, out _);
continue;
}

// only once a failure, timeout or deferral has been observed; not while a slow server's reply is
// merely still on its way
if (!sub.TryTakeUnsubscribeRetryNeeded()) continue;

if (!sub.UnsubscribeRetiring(this, pair.Value))
{
_retiringSubscriptions.TryRemove(sub, out _);
}
}
catch (Exception ex)
{
if (!_isDisposed) OnInternalError(ex);
}
}
}

/// <summary>
/// Unsubscribe <paramref name="retired"/> from <paramref name="server"/>, unless a newer subscription to the same
/// channel owns that server, or may yet claim it.
/// </summary>
/// <remarks>
/// Issued while holding <c>lock (subscriptions)</c>, so that a fresh <see cref="GetOrAddSubscription"/> for the
/// channel writes its <c>SUBSCRIBE</c> after this <c>UNSUBSCRIBE</c>, not before it. A restore that moves an existing
/// subscription onto the server without that lock is corrected when the reply arrives (see
/// <c>Subscription.SendAsync</c>).
/// </remarks>
internal void TryUnsubscribeRetiringServer(Subscription retired, in RedisChannel channel, ServerEndPoint server)
{
if (_isDisposed || !retired.IsLiveOn(server)) return;

lock (subscriptions)
{
if (subscriptions.TryGetValue(channel, out var active) && !active.IsRetired)
{
if (active.IsConnectedTo(server.EndPoint))
{
// a newer subscription holds the channel on this server; client and server agree
retired.TryRemoveEndpoint(server);
return;
}

if (!active.DoesNotWantServer(server))
{
// the newer one is still connecting, and may land here: look again at the next heartbeat
retired.MarkUnsubscribeRetryNeeded();
TrackRetiringSubscription(retired, channel);
return;
}
}

try
{
// fire-and-forget for the caller (we may be on a reader, which must not block), observed all the
// same, so that a declined one comes back here through OnUnsubscribeIncomplete
_ = retired.SendAsync(DefaultSubscriber, channel, SubscriptionAction.Unsubscribe, CommandFlags.FireAndForget, server);
}
catch (Exception ex)
{
if (_isDisposed) return;

retired.MarkUnsubscribeRetryNeeded();
TrackRetiringSubscription(retired, channel);
OnInternalError(ex);
}
}
}

/// <summary>
/// Updates all subscriptions re-evaluating their state.
/// This clears the current server if it's not connected, prepping them to reconnect.
Expand All @@ -234,6 +337,13 @@ internal void UpdateSubscriptions()
{
pair.Value.RemoveDisconnectedEndpoints();
}

foreach (var pair in _retiringSubscriptions)
{
var sub = pair.Key;
sub.RemoveDisconnectedEndpoints();
if (!sub.IsConnectedAny()) _retiringSubscriptions.TryRemove(sub, out _);
}
}

/// <summary>
Expand All @@ -247,6 +357,7 @@ internal long EnsureSubscriptions(CommandFlags flags = CommandFlags.None)
var subscriber = DefaultSubscriber;
foreach (var pair in subscriptions)
{
if (pair.Value.IsRetired) continue;
try
{
count += pair.Value.EnsureSubscribedToServer(subscriber, pair.Key, flags, true);
Expand All @@ -256,6 +367,8 @@ internal long EnsureSubscriptions(CommandFlags flags = CommandFlags.None)
OnInternalError(ex);
}
}

ProcessRetiringSubscriptions();
return count;
}

Expand Down Expand Up @@ -533,6 +646,8 @@ private int Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue>? ha

internal void ResubscribeToServer(Subscription sub, in RedisChannel channel, ServerEndPoint serverEndPoint, string cause)
{
if (sub.IsRetired) return;

// conditional: only if that's the server we were connected to, or "none"; we don't want to end up duplicated
if (sub.TryRemoveEndpoint(serverEndPoint) || !sub.IsConnectedAny())
{
Expand Down
Loading
Loading