Skip to content
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

Cluster Keyspace Notification Support #813

Closed
Closed
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
2 changes: 2 additions & 0 deletions StackExchange.Redis/StackExchange/Redis/RedisChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public struct RedisChannel : IEquatable<RedisChannel>

internal readonly byte[] Value;
internal readonly bool IsPatternBased;
internal readonly bool IsKeyspaceChannel;

/// <summary>
/// Indicates whether the channel-name is either null or a zero-length value
Expand All @@ -38,6 +39,7 @@ private RedisChannel(byte[] value, bool isPatternBased)
{
Value = value;
IsPatternBased = isPatternBased;
IsKeyspaceChannel = value != null && Encoding.UTF8.GetString(value).ToLower().StartsWith("__key");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of creating a byte[] for each comparison - it'd be far cheaper to pre-compute the byte array of "__key" once in a static and compare them instead :)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the fixed version.
https://pastebin.com/Q9T0Q99K

}

private static bool DeterminePatternBased(byte[] value, PatternMode mode)
Expand Down
72 changes: 60 additions & 12 deletions StackExchange.Redis/StackExchange/Redis/RedisSubscriber.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -144,7 +145,7 @@ internal long ValidateSubscriptions()
private sealed class Subscription
{
private Action<RedisChannel, RedisValue> handler;
private ServerEndPoint owner;
private List<ServerEndPoint> owners = new List<ServerEndPoint>();

public Subscription(Action<RedisChannel, RedisValue> value) => handler = value;

Expand All @@ -170,33 +171,81 @@ public bool Remove(Action<RedisChannel, RedisValue> value)
}

public Task SubscribeToServer(ConnectionMultiplexer multiplexer, RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
// subscribe to all masters in cluster for keyspace/keyevent notifications
if (channel.IsKeyspaceChannel) {
return SubscribeToMasters(multiplexer, channel, flags, asyncState, internalCall);
}
return SubscribeToSingleServer(multiplexer, channel, flags, asyncState, internalCall);
}

private Task SubscribeToSingleServer(ConnectionMultiplexer multiplexer, RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
var cmd = channel.IsPatternBased ? RedisCommand.PSUBSCRIBE : RedisCommand.SUBSCRIBE;
var selected = multiplexer.SelectServer(-1, cmd, flags, default(RedisKey));

if (selected == null || Interlocked.CompareExchange(ref owner, selected, null) != null) return null;
lock (owners)
{
if (selected == null || owners.Contains(selected)) return null;
owners.Add(selected);
}

var msg = Message.Create(-1, flags, cmd, channel);

if (internalCall) msg.SetInternalCall();
return selected.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState);
}

private Task SubscribeToMasters(ConnectionMultiplexer multiplexer, RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
List<Task> subscribeTasks = new List<Task>();
var cmd = channel.IsPatternBased ? RedisCommand.PSUBSCRIBE : RedisCommand.SUBSCRIBE;
var masters = multiplexer.GetServerSnapshot().Where(s => !s.IsSlave && s.EndPoint.Equals(s.ClusterConfiguration.Origin));

lock (owners)
{
foreach (var master in masters)
{
if (owners.Contains(master)) continue;
owners.Add(master);
var msg = Message.Create(-1, flags, cmd, channel);
if (internalCall) msg.SetInternalCall();
subscribeTasks.Add(master.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState));
}
}

return Task.WhenAll(subscribeTasks);
}

public Task UnsubscribeFromServer(RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
var oldOwner = Interlocked.Exchange(ref owner, null);
if (oldOwner == null) return null;
if (owners.Count == 0) return null;

List<Task> queuedTasks = new List<Task>();
var cmd = channel.IsPatternBased ? RedisCommand.PUNSUBSCRIBE : RedisCommand.UNSUBSCRIBE;
var msg = Message.Create(-1, flags, cmd, channel);
if (internalCall) msg.SetInternalCall();
return oldOwner.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState);
foreach (var owner in owners)
queuedTasks.Add(owner.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

owners isn't locked here, so this can go boom under load. The previous interlock above prevented this scenario.

owners.Clear();
return Task.WhenAll(queuedTasks.ToArray());
}

internal ServerEndPoint GetOwner() => Interlocked.CompareExchange(ref owner, null, null);
internal ServerEndPoint GetOwner()
{
var owner = owners?[0]; // we subscribe to arbitrary server, so why not return one
return Interlocked.CompareExchange(ref owner, null, null);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't make sense anymore...would need to lock owners here instead.

}

internal void Resubscribe(RedisChannel channel, ServerEndPoint server)
{
if (server != null && Interlocked.CompareExchange(ref owner, server, server) == server)
bool hasOwner;

lock (owners)
{
hasOwner = owners.Contains(server);
}

if (server != null && hasOwner)
{
var cmd = channel.IsPatternBased ? RedisCommand.PSUBSCRIBE : RedisCommand.SUBSCRIBE;
var msg = Message.Create(-1, CommandFlags.FireAndForget, cmd, channel);
Expand All @@ -208,16 +257,15 @@ internal void Resubscribe(RedisChannel channel, ServerEndPoint server)
internal bool Validate(ConnectionMultiplexer multiplexer, RedisChannel channel)
{
bool changed = false;
var oldOwner = Interlocked.CompareExchange(ref owner, null, null);
if (oldOwner != null && !oldOwner.IsSelectable(RedisCommand.PSUBSCRIBE))
if (owners.Count != 0 && !owners.All(o => o.IsSelectable(RedisCommand.PSUBSCRIBE)))
{
if (UnsubscribeFromServer(channel, CommandFlags.FireAndForget, null, true) != null)
{
changed = true;
}
oldOwner = null;
owners.Clear();
}
if (oldOwner == null && SubscribeToServer(multiplexer, channel, CommandFlags.FireAndForget, null, true) != null)
if (owners.Count == 0 && SubscribeToServer(multiplexer, channel, CommandFlags.FireAndForget, null, true) != null)
{
changed = true;
}
Expand Down