Skip to content

Commit e015faf

Browse files
committed
optimize pub/sub check for server-defined channels
1 parent f5b08ad commit e015faf

1 file changed

Lines changed: 30 additions & 4 deletions

File tree

src/StackExchange.Redis/PhysicalConnection.Read.cs

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -733,11 +733,9 @@ internal RedisChannel AsRedisChannel(in RespReader reader, RedisChannel.RedisCha
733733
// we have a channel-prefix, and it matches; strip it
734734
span = span.Slice(channelPrefix.Length);
735735
}
736-
else if (span.StartsWith("__"u8) && (
737-
span.StartsWith("__keyspace@"u8) || span.StartsWith("__keyevent@"u8) ||
738-
span.StartsWith("__subkeyspace@"u8) || span.StartsWith("__subkeyevent@"u8) ||
739-
span.StartsWith("__subkeyspaceitem@"u8) || span.StartsWith("__subkeyspaceevent@"u8)))
736+
else if (IsServerDefinedChannel(span))
740737
{
738+
// Server-defined channels should ignore our channel-prefix rules.
741739
// we shouldn't get unexpected events, so to get here: we've received a notification
742740
// on a channel that doesn't match our prefix; this *should* be limited to
743741
// key notifications (see: IgnoreChannelPrefix), but: we need to be sure
@@ -755,6 +753,34 @@ internal RedisChannel AsRedisChannel(in RespReader reader, RedisChannel.RedisCha
755753
return channel;
756754
}
757755

756+
private static bool IsServerDefinedChannel(ReadOnlySpan<byte> span)
757+
{
758+
var hash = AsciiHash.HashCS(span);
759+
return hash switch
760+
{
761+
KeyspaceChannelPrefix.HashCS when span.StartsWith(KeyspaceChannelPrefix.U8) => true,
762+
KeyeventChannelPrefix.HashCS when span.StartsWith(KeyeventChannelPrefix.U8) => true,
763+
SubkeyspaceChannelPrefix.HashCS when span.StartsWith(SubkeyspaceChannelPrefix.U8) => true,
764+
SubkeyeventChannelPrefix.HashCS when span.StartsWith(SubkeyeventChannelPrefix.U8) => true,
765+
SubkeyspaceItemChannelPrefix.HashCS when span.StartsWith(SubkeyspaceItemChannelPrefix.U8) => true,
766+
SubkeyspaceEventChannelPrefix.HashCS when span.StartsWith(SubkeyspaceEventChannelPrefix.U8) => true,
767+
_ => false,
768+
};
769+
}
770+
771+
[AsciiHash("__keyspace@")]
772+
private static partial class KeyspaceChannelPrefix { }
773+
[AsciiHash("__keyevent@")]
774+
private static partial class KeyeventChannelPrefix { }
775+
[AsciiHash("__subkeyspace@")]
776+
private static partial class SubkeyspaceChannelPrefix { }
777+
[AsciiHash("__subkeyevent@")]
778+
private static partial class SubkeyeventChannelPrefix { }
779+
[AsciiHash("__subkeyspaceitem@")]
780+
private static partial class SubkeyspaceItemChannelPrefix { }
781+
[AsciiHash("__subkeyspaceevent@")]
782+
private static partial class SubkeyspaceEventChannelPrefix { }
783+
758784
[AsciiHash("*2\r\n$4\r\npong\r\n$")]
759785
private static partial class ArrayPong_LC_Bulk { }
760786
[AsciiHash("*2\r\n$4\r\nPONG\r\n$")]

0 commit comments

Comments
 (0)