Commit 567cdf73 authored by Nick Craver's avatar Nick Craver

Code cleanup and C#6 feature use

parent 470898c9
...@@ -46,7 +46,7 @@ public ResponseException(string code) ...@@ -46,7 +46,7 @@ public ResponseException(string code)
public Redis(string host, int port) public Redis(string host, int port)
{ {
if (host == null) if (host == null)
throw new ArgumentNullException("host"); throw new ArgumentNullException(nameof(host));
Host = host; Host = host;
Port = port; Port = port;
...@@ -94,9 +94,9 @@ public int Db ...@@ -94,9 +94,9 @@ public int Db
public void Set(string key, string value) public void Set(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
Set(key, Encoding.UTF8.GetBytes(value)); Set(key, Encoding.UTF8.GetBytes(value));
} }
...@@ -104,12 +104,12 @@ public void Set(string key, string value) ...@@ -104,12 +104,12 @@ public void Set(string key, string value)
public void Set(string key, byte[] value) public void Set(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length)) if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect"); throw new Exception("Unable to connect");
...@@ -119,9 +119,9 @@ public void Set(string key, byte[] value) ...@@ -119,9 +119,9 @@ public void Set(string key, byte[] value)
public bool SetNX(string key, string value) public bool SetNX(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
return SetNX(key, Encoding.UTF8.GetBytes(value)); return SetNX(key, Encoding.UTF8.GetBytes(value));
} }
...@@ -129,12 +129,12 @@ public bool SetNX(string key, string value) ...@@ -129,12 +129,12 @@ public bool SetNX(string key, string value)
public bool SetNX(string key, byte[] value) public bool SetNX(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false; return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false;
} }
...@@ -147,7 +147,7 @@ public void Set(IDictionary<string, string> dict) ...@@ -147,7 +147,7 @@ public void Set(IDictionary<string, string> dict)
public void Set(IDictionary<string, byte[]> dict) public void Set(IDictionary<string, byte[]> dict)
{ {
if (dict == null) if (dict == null)
throw new ArgumentNullException("dict"); throw new ArgumentNullException(nameof(dict));
var nl = Encoding.UTF8.GetBytes("\r\n"); var nl = Encoding.UTF8.GetBytes("\r\n");
...@@ -173,14 +173,14 @@ public void Set(IDictionary<string, byte[]> dict) ...@@ -173,14 +173,14 @@ public void Set(IDictionary<string, byte[]> dict)
public byte[] Get(string key) public byte[] Get(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectData(null, "GET " + key + "\r\n"); return SendExpectData(null, "GET " + key + "\r\n");
} }
public string GetString(string key) public string GetString(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return Encoding.UTF8.GetString(Get(key)); return Encoding.UTF8.GetString(Get(key));
} }
...@@ -192,12 +192,12 @@ public byte[][] Sort(SortOptions options) ...@@ -192,12 +192,12 @@ public byte[][] Sort(SortOptions options)
public byte[] GetSet(string key, byte[] value) public byte[] GetSet(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length)) if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect"); throw new Exception("Unable to connect");
...@@ -208,9 +208,9 @@ public byte[] GetSet(string key, byte[] value) ...@@ -208,9 +208,9 @@ public byte[] GetSet(string key, byte[] value)
public string GetSet(string key, string value) public string GetSet(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value))); return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value)));
} }
...@@ -466,56 +466,56 @@ byte[] ReadData() ...@@ -466,56 +466,56 @@ byte[] ReadData()
public bool ContainsKey(string key) public bool ContainsKey(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXISTS " + key + "\r\n") == 1; return SendExpectInt("EXISTS " + key + "\r\n") == 1;
} }
public bool Remove(string key) public bool Remove(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DEL " + key + "\r\n", key) == 1; return SendExpectInt("DEL " + key + "\r\n", key) == 1;
} }
public int Remove(params string[] args) public int Remove(params string[] args)
{ {
if (args == null) if (args == null)
throw new ArgumentNullException("args"); throw new ArgumentNullException(nameof(args));
return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n"); return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n");
} }
public int Increment(string key) public int Increment(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCR " + key + "\r\n"); return SendExpectInt("INCR " + key + "\r\n");
} }
public int Increment(string key, int count) public int Increment(string key, int count)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCRBY {0} {1}\r\n", key, count); return SendExpectInt("INCRBY {0} {1}\r\n", key, count);
} }
public int Decrement(string key) public int Decrement(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECR " + key + "\r\n"); return SendExpectInt("DECR " + key + "\r\n");
} }
public int Decrement(string key, int count) public int Decrement(string key, int count)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECRBY {0} {1}\r\n", key, count); return SendExpectInt("DECRBY {0} {1}\r\n", key, count);
} }
public KeyType TypeOf(string key) public KeyType TypeOf(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
switch (SendExpectString("TYPE {0}\r\n", key)) switch (SendExpectString("TYPE {0}\r\n", key))
{ {
case "none": case "none":
...@@ -538,30 +538,30 @@ public string RandomKey() ...@@ -538,30 +538,30 @@ public string RandomKey()
public bool Rename(string oldKeyname, string newKeyname) public bool Rename(string oldKeyname, string newKeyname)
{ {
if (oldKeyname == null) if (oldKeyname == null)
throw new ArgumentNullException("oldKeyname"); throw new ArgumentNullException(nameof(oldKeyname));
if (newKeyname == null) if (newKeyname == null)
throw new ArgumentNullException("newKeyname"); throw new ArgumentNullException(nameof(newKeyname));
return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+'; return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+';
} }
public bool Expire(string key, int seconds) public bool Expire(string key, int seconds)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1; return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1;
} }
public bool ExpireAt(string key, int time) public bool ExpireAt(string key, int time)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1; return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1;
} }
public int TimeToLive(string key) public int TimeToLive(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("TTL {0}\r\n", key); return SendExpectInt("TTL {0}\r\n", key);
} }
...@@ -778,13 +778,13 @@ public byte[][] GetUnionOfSets(params string[] keys) ...@@ -778,13 +778,13 @@ public byte[][] GetUnionOfSets(params string[] keys)
void StoreSetCommands(string cmd, string destKey, params string[] keys) void StoreSetCommands(string cmd, string destKey, params string[] keys)
{ {
if (String.IsNullOrEmpty(cmd)) if (String.IsNullOrEmpty(cmd))
throw new ArgumentNullException("cmd"); throw new ArgumentNullException(nameof(cmd));
if (String.IsNullOrEmpty(destKey)) if (String.IsNullOrEmpty(destKey))
throw new ArgumentNullException("destKey"); throw new ArgumentNullException(nameof(destKey));
if (keys == null) if (keys == null)
throw new ArgumentNullException("keys"); throw new ArgumentNullException(nameof(keys));
SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys)); SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys));
} }
......
using System; using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework; using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
......
#if FEATURE_MOQ #if FEATURE_MOQ
using System;
using Moq; using Moq;
using NUnit.Framework; using NUnit.Framework;
using StackExchange.Redis.KeyspaceIsolation; using StackExchange.Redis.KeyspaceIsolation;
......
using System.Linq; using NUnit.Framework;
using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
{ {
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
...@@ -555,7 +554,7 @@ public void GetFromRightNodeBasedOnFlags(CommandFlags flags, bool isSlave) ...@@ -555,7 +554,7 @@ public void GetFromRightNodeBasedOnFlags(CommandFlags flags, bool isSlave)
private static string Describe(EndPoint endpoint) private static string Describe(EndPoint endpoint)
{ {
return endpoint == null ? "(unknown)" : endpoint.ToString(); return endpoint?.ToString() ?? "(unknown)";
} }
class TestProfiler : IProfiler class TestProfiler : IProfiler
......
using System; using System.Threading;
using System.Threading;
using NUnit.Framework; using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
......
using NUnit.Framework; using NUnit.Framework;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.Threading; using System.Threading;
......
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework; using NUnit.Framework;
using StackExchange.Redis;
namespace StackExchange.Redis.Tests.Issues namespace StackExchange.Redis.Tests.Issues
{ {
...@@ -32,7 +27,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb() ...@@ -32,7 +27,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb()
var log = new StringWriter(); var log = new StringWriter();
try try
{ {
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1}", PrimaryServer, PrimaryPort), log)) { using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort}", log)) {
var db = conn.GetDatabase(); var db = conn.GetDatabase();
Assert.AreEqual(0, db.Database); Assert.AreEqual(0, db.Database);
} }
...@@ -49,7 +44,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb() ...@@ -49,7 +44,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb()
var log = new StringWriter(); var log = new StringWriter();
try try
{ {
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1},defaultDatabase=3", PrimaryServer, PrimaryPort), log)) { using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort},defaultDatabase=3", log)) {
var db = conn.GetDatabase(); var db = conn.GetDatabase();
Assert.AreEqual(3, db.Database); Assert.AreEqual(3, db.Database);
} }
......
using System; namespace StackExchange.Redis.Tests.Issues
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis.Tests.Issues
{ {
class Issue118 class Issue118
{ {
......
using System; using System.Diagnostics;
using System.Diagnostics;
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
#if CORE_CLR #if CORE_CLR
using System.Reflection; using System.Reflection;
#endif #endif
......
...@@ -28,7 +28,7 @@ static TaskCompletionSource<T> Create<T>(SourceOrign origin) ...@@ -28,7 +28,7 @@ static TaskCompletionSource<T> Create<T>(SourceOrign origin)
case SourceOrign.NewTCS: return new TaskCompletionSource<T>(); case SourceOrign.NewTCS: return new TaskCompletionSource<T>();
case SourceOrign.Create: return TaskSource.Create<T>(null); case SourceOrign.Create: return TaskSource.Create<T>(null);
case SourceOrign.CreateDenyExec: return TaskSource.CreateDenyExecSync<T>(null); case SourceOrign.CreateDenyExec: return TaskSource.CreateDenyExecSync<T>(null);
default: throw new ArgumentOutOfRangeException("origin"); default: throw new ArgumentOutOfRangeException(nameof(origin));
} }
} }
[Test] [Test]
...@@ -78,7 +78,7 @@ public enum AttachMode ...@@ -78,7 +78,7 @@ public enum AttachMode
} }
class AwaitState class AwaitState
{ {
public int Thread { get { return continuationThread; } } public int Thread => continuationThread;
volatile int continuationThread = -1; volatile int continuationThread = -1;
private ManualResetEventSlim evt = new ManualResetEventSlim(); private ManualResetEventSlim evt = new ManualResetEventSlim();
public void Wait() public void Wait()
...@@ -99,7 +99,7 @@ public void Attach(Task task, AttachMode attachMode) ...@@ -99,7 +99,7 @@ public void Attach(Task task, AttachMode attachMode)
DoAwait(task); DoAwait(task);
break; break;
default: default:
throw new ArgumentOutOfRangeException("attachMode"); throw new ArgumentOutOfRangeException(nameof(attachMode));
} }
} }
private void Continue(Task task) private void Continue(Task task)
......
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OK/@EntryIndexedValue">OK</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PONG/@EntryIndexedValue">PONG</s:String></wpf:ResourceDictionary>
\ No newline at end of file
using System; using System;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
#if !STRONG_NAME
using System.Runtime.CompilerServices;
#endif
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
......
...@@ -9,9 +9,22 @@ namespace StackExchange.Redis ...@@ -9,9 +9,22 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class CommandMap public sealed class CommandMap
{ {
private static readonly CommandMap private readonly byte[][] map;
@default = CreateImpl(null, null),
twemproxy = CreateImpl(null, exclusions: new HashSet<RedisCommand> internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get; } = CreateImpl(null, null);
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get; } = CreateImpl(null, exclusions: new HashSet<RedisCommand>
{ {
// see https://github.com/twitter/twemproxy/blob/master/notes/redis.md // see https://github.com/twitter/twemproxy/blob/master/notes/redis.md
RedisCommand.KEYS, RedisCommand.MIGRATE, RedisCommand.MOVE, RedisCommand.OBJECT, RedisCommand.RANDOMKEY, RedisCommand.KEYS, RedisCommand.MIGRATE, RedisCommand.MOVE, RedisCommand.OBJECT, RedisCommand.RANDOMKEY,
...@@ -38,45 +51,28 @@ private static readonly CommandMap ...@@ -38,45 +51,28 @@ private static readonly CommandMap
RedisCommand.BGREWRITEAOF, RedisCommand.BGSAVE, RedisCommand.CLIENT, RedisCommand.CLUSTER, RedisCommand.CONFIG, RedisCommand.DBSIZE, RedisCommand.BGREWRITEAOF, RedisCommand.BGSAVE, RedisCommand.CLIENT, RedisCommand.CLUSTER, RedisCommand.CONFIG, RedisCommand.DBSIZE,
RedisCommand.DEBUG, RedisCommand.FLUSHALL, RedisCommand.FLUSHDB, RedisCommand.INFO, RedisCommand.LASTSAVE, RedisCommand.MONITOR, RedisCommand.SAVE, RedisCommand.DEBUG, RedisCommand.FLUSHALL, RedisCommand.FLUSHDB, RedisCommand.INFO, RedisCommand.LASTSAVE, RedisCommand.MONITOR, RedisCommand.SAVE,
RedisCommand.SHUTDOWN, RedisCommand.SLAVEOF, RedisCommand.SLOWLOG, RedisCommand.SYNC, RedisCommand.TIME RedisCommand.SHUTDOWN, RedisCommand.SLAVEOF, RedisCommand.SLOWLOG, RedisCommand.SYNC, RedisCommand.TIME
}), ssdb = Create(new HashSet<string> { });
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get; } = Create(new HashSet<string> {
// see http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html // see http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html
"ping", "ping",
"get", "set", "del", "incr", "incrby", "mget", "mset", "keys", "getset", "setnx", "get", "set", "del", "incr", "incrby", "mget", "mset", "keys", "getset", "setnx",
"hget", "hset", "hdel", "hincrby", "hkeys", "hvals", "hmget", "hmset", "hlen", "hget", "hset", "hdel", "hincrby", "hkeys", "hvals", "hmget", "hmset", "hlen",
"zscore", "zadd", "zrem", "zrange", "zrangebyscore", "zincrby", "zdecrby", "zcard", "zscore", "zadd", "zrem", "zrange", "zrangebyscore", "zincrby", "zdecrby", "zcard",
"llen", "lpush", "rpush", "lpop", "rpop", "lrange", "lindex" "llen", "lpush", "rpush", "lpop", "rpop", "lrange", "lindex"
}, true), }, true);
sentinel = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
private readonly byte[][] map;
internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get { return @default; } }
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get { return twemproxy; } }
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get { return ssdb; } }
/// <summary> /// <summary>
/// The commands available to <a href="Sentinel">http://redis.io/topics/sentinel</a> /// The commands available to <a href="Sentinel">http://redis.io/topics/sentinel</a>
/// </summary> /// </summary>
/// <remarks>http://redis.io/topics/sentinel</remarks> /// <remarks>http://redis.io/topics/sentinel</remarks>
public static CommandMap Sentinel { get { return sentinel; } } public static CommandMap Sentinel { get; } = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
/// <summary> /// <summary>
/// Create a new CommandMap, customizing some commands /// Create a new CommandMap, customizing some commands
...@@ -208,13 +204,13 @@ private static CommandMap CreateImpl(Dictionary<string, string> caseInsensitiveO ...@@ -208,13 +204,13 @@ private static CommandMap CreateImpl(Dictionary<string, string> caseInsensitiveO
} }
} }
if (value != name) haveDelta = true; if (value != name) haveDelta = true;
// TODO: bug?
haveDelta = true; haveDelta = true;
byte[] val = string.IsNullOrWhiteSpace(value) ? null : Encoding.UTF8.GetBytes(value); byte[] val = string.IsNullOrWhiteSpace(value) ? null : Encoding.UTF8.GetBytes(value);
map[idx] = val; map[idx] = val;
} }
} }
if (!haveDelta && @default != null) return @default; if (!haveDelta && Default != null) return Default;
return new CommandMap(map); return new CommandMap(map);
} }
......
...@@ -11,13 +11,13 @@ public sealed class CommandTrace ...@@ -11,13 +11,13 @@ public sealed class CommandTrace
internal CommandTrace(long uniqueId, long time, long duration, RedisValue[] arguments) internal CommandTrace(long uniqueId, long time, long duration, RedisValue[] arguments)
{ {
this.UniqueId = uniqueId; UniqueId = uniqueId;
this.Time = RedisBase.UnixEpoch.AddSeconds(time); Time = RedisBase.UnixEpoch.AddSeconds(time);
// duration = The amount of time needed for its execution, in microseconds. // duration = The amount of time needed for its execution, in microseconds.
// A tick is equal to 100 nanoseconds, or one ten-millionth of a second. // A tick is equal to 100 nanoseconds, or one ten-millionth of a second.
// So 1 microsecond = 10 ticks // So 1 microsecond = 10 ticks
this.Duration = TimeSpan.FromTicks(duration * 10); Duration = TimeSpan.FromTicks(duration * 10);
this.Arguments = arguments; Arguments = arguments;
} }
/// <summary> /// <summary>
......
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
using System; namespace StackExchange.Redis
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis
{ {
internal static class VolatileWrapper internal static class VolatileWrapper
{ {
......
...@@ -4,7 +4,7 @@ namespace StackExchange.Redis ...@@ -4,7 +4,7 @@ namespace StackExchange.Redis
{ {
internal static class CompletedTask<T> internal static class CompletedTask<T>
{ {
private readonly static Task<T> @default = FromResult(default(T), null); private static readonly Task<T> @default = FromResult(default(T), null);
public static Task<T> Default(object asyncState) public static Task<T> Default(object asyncState)
{ {
......
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -31,8 +27,8 @@ public struct Enumerator : IEnumerator<IProfiledCommand> ...@@ -31,8 +27,8 @@ public struct Enumerator : IEnumerator<IProfiledCommand>
ProfileStorage Head; ProfileStorage Head;
ProfileStorage CurrentBacker; ProfileStorage CurrentBacker;
bool IsEmpty { get { return Head == null; } } bool IsEmpty => Head == null;
bool IsUnstartedOrFinished { get { return CurrentBacker == null; } } bool IsUnstartedOrFinished => CurrentBacker == null;
internal Enumerator(ProfileStorage head) internal Enumerator(ProfileStorage head)
{ {
...@@ -43,15 +39,9 @@ internal Enumerator(ProfileStorage head) ...@@ -43,15 +39,9 @@ internal Enumerator(ProfileStorage head)
/// <summary> /// <summary>
/// The current element. /// The current element.
/// </summary> /// </summary>
public IProfiledCommand Current public IProfiledCommand Current => CurrentBacker;
{
get { return CurrentBacker; }
}
object System.Collections.IEnumerator.Current object System.Collections.IEnumerator.Current => CurrentBacker;
{
get { return CurrentBacker; }
}
/// <summary> /// <summary>
/// Advances the enumeration, returning true if there is a new element to consume and false /// Advances the enumeration, returning true if there is a new element to consume and false
......
...@@ -18,7 +18,7 @@ public abstract class Condition ...@@ -18,7 +18,7 @@ public abstract class Condition
/// </summary> /// </summary>
public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue value) public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue value)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashNotExists(key, hashField); if (value.IsNull) return HashNotExists(key, hashField);
return new EqualsCondition(key, hashField, true, value); return new EqualsCondition(key, hashField, true, value);
} }
...@@ -28,7 +28,7 @@ public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue ...@@ -28,7 +28,7 @@ public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue
/// </summary> /// </summary>
public static Condition HashExists(RedisKey key, RedisValue hashField) public static Condition HashExists(RedisKey key, RedisValue hashField)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, true); return new ExistsCondition(key, hashField, true);
} }
...@@ -37,7 +37,7 @@ public static Condition HashExists(RedisKey key, RedisValue hashField) ...@@ -37,7 +37,7 @@ public static Condition HashExists(RedisKey key, RedisValue hashField)
/// </summary> /// </summary>
public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisValue value) public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisValue value)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashExists(key, hashField); if (value.IsNull) return HashExists(key, hashField);
return new EqualsCondition(key, hashField, false, value); return new EqualsCondition(key, hashField, false, value);
} }
...@@ -47,7 +47,7 @@ public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisVa ...@@ -47,7 +47,7 @@ public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisVa
/// </summary> /// </summary>
public static Condition HashNotExists(RedisKey key, RedisValue hashField) public static Condition HashNotExists(RedisKey key, RedisValue hashField)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, false); return new ExistsCondition(key, hashField, false);
} }
...@@ -136,7 +136,7 @@ public static Message CreateMessage(Condition condition, int db, CommandFlags fl ...@@ -136,7 +136,7 @@ public static Message CreateMessage(Condition condition, int db, CommandFlags fl
protected override bool SetResultCore(PhysicalConnection connection, Message message, RawResult result) protected override bool SetResultCore(PhysicalConnection connection, Message message, RawResult result)
{ {
var msg = message as ConditionMessage; var msg = message as ConditionMessage;
var condition = msg == null ? null : msg.Condition; var condition = msg?.Condition;
bool final; bool final;
if (condition != null && condition.TryValidate(result, out final)) if (condition != null && condition.TryValidate(result, out final))
{ {
...@@ -307,7 +307,7 @@ internal override Condition MapKeys(Func<RedisKey,RedisKey> map) ...@@ -307,7 +307,7 @@ internal override Condition MapKeys(Func<RedisKey,RedisKey> map)
private readonly RedisKey key; private readonly RedisKey key;
public ListCondition(RedisKey key, long index, bool expectedResult, RedisValue? expectedValue) public ListCondition(RedisKey key, long index, bool expectedResult, RedisValue? expectedValue)
{ {
if (key.IsNull) throw new ArgumentException("key"); if (key.IsNull) throw new ArgumentException(nameof(key));
this.key = key; this.key = key;
this.index = index; this.index = index;
this.expectedResult = expectedResult; this.expectedResult = expectedResult;
...@@ -371,7 +371,7 @@ internal override bool TryValidate(RawResult result, out bool value) ...@@ -371,7 +371,7 @@ internal override bool TryValidate(RawResult result, out bool value)
/// </summary> /// </summary>
public sealed class ConditionResult public sealed class ConditionResult
{ {
internal readonly Condition Condition; internal readonly Condition Condition;
private ResultBox<bool> resultBox; private ResultBox<bool> resultBox;
...@@ -386,7 +386,8 @@ internal ConditionResult(Condition condition) ...@@ -386,7 +386,8 @@ internal ConditionResult(Condition condition)
/// <summary> /// <summary>
/// Indicates whether the condition was satisfied /// Indicates whether the condition was satisfied
/// </summary> /// </summary>
public bool WasSatisfied { get { return wasSatisfied; } } public bool WasSatisfied => wasSatisfied;
internal IEnumerable<Message> CreateMessages(int db) internal IEnumerable<Message> CreateMessages(int db)
{ {
return Condition.CreateMessages(db, resultBox); return Condition.CreateMessages(db, resultBox);
......
...@@ -178,7 +178,7 @@ public CommandMap CommandMap ...@@ -178,7 +178,7 @@ public CommandMap CommandMap
if (commandMap != null) return commandMap; if (commandMap != null) return commandMap;
switch (Proxy) switch (Proxy)
{ {
case Redis.Proxy.Twemproxy: case Proxy.Twemproxy:
return CommandMap.Twemproxy; return CommandMap.Twemproxy;
default: default:
return CommandMap.Default; return CommandMap.Default;
...@@ -186,7 +186,7 @@ public CommandMap CommandMap ...@@ -186,7 +186,7 @@ public CommandMap CommandMap
} }
set set
{ {
if (value == null) throw new ArgumentNullException("value"); if (value == null) throw new ArgumentNullException(nameof(value));
commandMap = value; commandMap = value;
} }
} }
...@@ -215,7 +215,7 @@ public CommandMap CommandMap ...@@ -215,7 +215,7 @@ public CommandMap CommandMap
/// <summary> /// <summary>
/// The endpoints defined for this configuration /// The endpoints defined for this configuration
/// </summary> /// </summary>
public EndPointCollection EndPoints { get { return endpoints; } } public EndPointCollection EndPoints => endpoints;
/// <summary> /// <summary>
/// Use ThreadPriority.AboveNormal for SocketManager reader and writer threads (true by default). If false, ThreadPriority.Normal will be used. /// Use ThreadPriority.AboveNormal for SocketManager reader and writer threads (true by default). If false, ThreadPriority.Normal will be used.
...@@ -397,7 +397,7 @@ public override string ToString() ...@@ -397,7 +397,7 @@ public override string ToString()
Append(sb, OptionKeys.ConfigCheckSeconds, configCheckSeconds); Append(sb, OptionKeys.ConfigCheckSeconds, configCheckSeconds);
Append(sb, OptionKeys.ResponseTimeout, responseTimeout); Append(sb, OptionKeys.ResponseTimeout, responseTimeout);
Append(sb, OptionKeys.DefaultDatabase, defaultDatabase); Append(sb, OptionKeys.DefaultDatabase, defaultDatabase);
if (commandMap != null) commandMap.AppendDeltas(sb); commandMap?.AppendDeltas(sb);
return sb.ToString(); return sb.ToString();
} }
...@@ -466,8 +466,7 @@ static void Append(StringBuilder sb, object value) ...@@ -466,8 +466,7 @@ static void Append(StringBuilder sb, object value)
static void Append(StringBuilder sb, string prefix, object value) static void Append(StringBuilder sb, string prefix, object value)
{ {
if (value == null) return; string s = value?.ToString();
string s = value.ToString();
if (!string.IsNullOrWhiteSpace(s)) if (!string.IsNullOrWhiteSpace(s))
{ {
if (sb.Length != 0) sb.Append(','); if (sb.Length != 0) sb.Append(',');
...@@ -509,7 +508,7 @@ private void DoParse(string configuration, bool ignoreUnknown) ...@@ -509,7 +508,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
{ {
if (configuration == null) if (configuration == null)
{ {
throw new ArgumentNullException("configuration"); throw new ArgumentNullException(nameof(configuration));
} }
if (string.IsNullOrWhiteSpace(configuration)) if (string.IsNullOrWhiteSpace(configuration))
...@@ -629,7 +628,7 @@ private void DoParse(string configuration, bool ignoreUnknown) ...@@ -629,7 +628,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
} }
if (map != null && map.Count != 0) if (map != null && map.Count != 0)
{ {
this.CommandMap = CommandMap.Create(map); CommandMap = CommandMap.Create(map);
} }
} }
......
...@@ -7,11 +7,9 @@ namespace StackExchange.Redis ...@@ -7,11 +7,9 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class ConnectionCounters public class ConnectionCounters
{ {
private readonly ConnectionType connectionType;
internal ConnectionCounters(ConnectionType connectionType) internal ConnectionCounters(ConnectionType connectionType)
{ {
this.connectionType = connectionType; ConnectionType = connectionType;
} }
/// <summary> /// <summary>
...@@ -27,7 +25,8 @@ internal ConnectionCounters(ConnectionType connectionType) ...@@ -27,7 +25,8 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary> /// <summary>
/// The type of this connection /// The type of this connection
/// </summary> /// </summary>
public ConnectionType ConnectionType { get { return connectionType; } } public ConnectionType ConnectionType { get; }
/// <summary> /// <summary>
/// The number of operations that failed to complete asynchronously /// The number of operations that failed to complete asynchronously
/// </summary> /// </summary>
...@@ -36,10 +35,7 @@ internal ConnectionCounters(ConnectionType connectionType) ...@@ -36,10 +35,7 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary> /// <summary>
/// Indicates if there are any pending items or failures on this connection /// Indicates if there are any pending items or failures on this connection
/// </summary> /// </summary>
public bool IsEmpty public bool IsEmpty => PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0;
{
get { return PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0; }
}
/// <summary> /// <summary>
/// Indicates the total number of messages despatched to a non-preferred endpoint, for example sent to a master /// Indicates the total number of messages despatched to a non-preferred endpoint, for example sent to a master
...@@ -80,7 +76,7 @@ public bool IsEmpty ...@@ -80,7 +76,7 @@ public bool IsEmpty
/// <summary> /// <summary>
/// Indicates the total number of outstanding items against this connection /// Indicates the total number of outstanding items against this connection
/// </summary> /// </summary>
public int TotalOutstanding { get { return PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion; } } public int TotalOutstanding => PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion;
/// <summary> /// <summary>
/// Indicates the total number of writers items against this connection /// Indicates the total number of writers items against this connection
...@@ -100,17 +96,17 @@ public override string ToString() ...@@ -100,17 +96,17 @@ public override string ToString()
internal void Add(ConnectionCounters other) internal void Add(ConnectionCounters other)
{ {
if (other == null) return; if (other == null) return;
this.CompletedAsynchronously += other.CompletedAsynchronously; CompletedAsynchronously += other.CompletedAsynchronously;
this.CompletedSynchronously += other.CompletedSynchronously; CompletedSynchronously += other.CompletedSynchronously;
this.FailedAsynchronously += other.FailedAsynchronously; FailedAsynchronously += other.FailedAsynchronously;
this.OperationCount += other.OperationCount; OperationCount += other.OperationCount;
this.PendingUnsentItems += other.PendingUnsentItems; PendingUnsentItems += other.PendingUnsentItems;
this.ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion; ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion;
this.SentItemsAwaitingResponse += other.SentItemsAwaitingResponse; SentItemsAwaitingResponse += other.SentItemsAwaitingResponse;
this.SocketCount += other.SocketCount; SocketCount += other.SocketCount;
this.Subscriptions += other.Subscriptions; Subscriptions += other.Subscriptions;
this.WriterCount += other.WriterCount; WriterCount += other.WriterCount;
this.NonPreferredEndpointCount += other.NonPreferredEndpointCount; NonPreferredEndpointCount += other.NonPreferredEndpointCount;
} }
internal bool Any() internal bool Any()
...@@ -135,5 +131,4 @@ internal void Append(StringBuilder sb) ...@@ -135,5 +131,4 @@ internal void Append(StringBuilder sb)
if (NonPreferredEndpointCount != 0) sb.Append(", non-pref=").Append(NonPreferredEndpointCount); if (NonPreferredEndpointCount != 0) sb.Append(", non-pref=").Append(NonPreferredEndpointCount);
} }
} }
} }
...@@ -9,57 +9,43 @@ namespace StackExchange.Redis ...@@ -9,57 +9,43 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class ConnectionFailedEventArgs : EventArgs, ICompletable public sealed class ConnectionFailedEventArgs : EventArgs, ICompletable
{ {
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly ConnectionFailureType failureType;
private readonly EventHandler<ConnectionFailedEventArgs> handler; private readonly EventHandler<ConnectionFailedEventArgs> handler;
private readonly object sender; private readonly object sender;
internal ConnectionFailedEventArgs(EventHandler<ConnectionFailedEventArgs> handler, object sender, EndPoint endPoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception) internal ConnectionFailedEventArgs(EventHandler<ConnectionFailedEventArgs> handler, object sender, EndPoint endPoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endPoint; EndPoint = endPoint;
this.connectionType = connectionType; ConnectionType = connectionType;
this.exception = exception; Exception = exception;
this.failureType = failureType; FailureType = failureType;
} }
/// <summary> /// <summary>
/// Gets the connection-type of the failing connection /// Gets the connection-type of the failing connection
/// </summary> /// </summary>
public ConnectionType ConnectionType public ConnectionType ConnectionType { get; }
{
get { return connectionType; }
}
/// <summary> /// <summary>
/// Gets the failing server-endpoint /// Gets the failing server-endpoint
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
/// <summary> /// <summary>
/// Gets the exception if available (this can be null) /// Gets the exception if available (this can be null)
/// </summary> /// </summary>
public Exception Exception public Exception Exception { get; }
{
get { return exception; }
}
/// <summary> /// <summary>
/// The type of failure /// The type of failure
/// </summary> /// </summary>
public ConnectionFailureType FailureType public ConnectionFailureType FailureType { get; }
{
get { return failureType; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, connection-failed: "); sb.Append("event, connection-failed: ");
if (endpoint == null) sb.Append("n/a"); if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint)); else sb.Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -24,7 +18,7 @@ partial class ConnectionMultiplexer ...@@ -24,7 +18,7 @@ partial class ConnectionMultiplexer
/// </summary> /// </summary>
public void RegisterProfiler(IProfiler profiler) public void RegisterProfiler(IProfiler profiler)
{ {
if (profiler == null) throw new ArgumentNullException("profiler"); if (profiler == null) throw new ArgumentNullException(nameof(profiler));
if (this.profiler != null) throw new InvalidOperationException("IProfiler already registered for this ConnectionMultiplexer"); if (this.profiler != null) throw new InvalidOperationException("IProfiler already registered for this ConnectionMultiplexer");
this.profiler = profiler; this.profiler = profiler;
...@@ -44,8 +38,8 @@ public void RegisterProfiler(IProfiler profiler) ...@@ -44,8 +38,8 @@ public void RegisterProfiler(IProfiler profiler)
public void BeginProfiling(object forContext) public void BeginProfiling(object forContext)
{ {
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler"); if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext"); if (forContext == null) throw new ArgumentNullException(nameof(forContext));
if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", "forContext"); if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", nameof(forContext));
if (!profiledCommands.TryCreate(forContext)) if (!profiledCommands.TryCreate(forContext))
{ {
...@@ -61,7 +55,7 @@ public void BeginProfiling(object forContext) ...@@ -61,7 +55,7 @@ public void BeginProfiling(object forContext)
public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true) public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true)
{ {
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler"); if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext"); if (forContext == null) throw new ArgumentNullException(nameof(forContext));
ProfiledCommandEnumerable ret; ProfiledCommandEnumerable ret;
if (!profiledCommands.TryRemove(forContext, out ret)) if (!profiledCommands.TryRemove(forContext, out ret))
......
...@@ -2,20 +2,20 @@ ...@@ -2,20 +2,20 @@
{ {
partial class ConnectionMultiplexer partial class ConnectionMultiplexer
{ {
internal SocketManager SocketManager { get { return socketManager; } } internal SocketManager SocketManager => socketManager;
private SocketManager socketManager; private SocketManager socketManager;
private bool ownsSocketManager; private bool ownsSocketManager;
partial void OnCreateReaderWriter(ConfigurationOptions configuration) partial void OnCreateReaderWriter(ConfigurationOptions configuration)
{ {
this.ownsSocketManager = configuration.SocketManager == null; ownsSocketManager = configuration.SocketManager == null;
this.socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads); socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads);
} }
partial void OnCloseReaderWriter() partial void OnCloseReaderWriter()
{ {
if (ownsSocketManager && socketManager != null) socketManager.Dispose(); if (ownsSocketManager) socketManager?.Dispose();
socketManager = null; socketManager = null;
} }
...@@ -30,7 +30,5 @@ internal void RequestWrite(PhysicalBridge bridge, bool forced) ...@@ -30,7 +30,5 @@ internal void RequestWrite(PhysicalBridge bridge, bool forced)
} }
} }
partial void OnWriterCreated(); partial void OnWriterCreated();
} }
} }
...@@ -3,16 +3,15 @@ ...@@ -3,16 +3,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Concurrent;
#if NET40 #if NET40
using Microsoft.Runtime.CompilerServices; using Microsoft.Runtime.CompilerServices;
#else #else
using System.IO.Compression;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
#endif #endif
...@@ -28,12 +27,12 @@ private static void ObverveErrors(this Task task) ...@@ -28,12 +27,12 @@ private static void ObverveErrors(this Task task)
public static Task ObserveErrors(this Task task) public static Task ObserveErrors(this Task task)
{ {
if (task != null) task.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted); task?.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted);
return task; return task;
} }
public static Task<T> ObserveErrors<T>(this Task<T> task) public static Task<T> ObserveErrors<T>(this Task<T> task)
{ {
if (task != null) task.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted); task?.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted);
return task; return task;
} }
...@@ -62,12 +61,7 @@ public static TaskFactory Factory ...@@ -62,12 +61,7 @@ public static TaskFactory Factory
{ {
get get
{ {
if (_factory != null) return _factory ?? Task.Factory;
{
return _factory;
}
return Task.Factory;
} }
set set
{ {
...@@ -95,15 +89,12 @@ public ServerCounters GetCounters() ...@@ -95,15 +89,12 @@ public ServerCounters GetCounters()
/// <summary> /// <summary>
/// Gets the client-name that will be used on all new connections /// Gets the client-name that will be used on all new connections
/// </summary> /// </summary>
public string ClientName { get { return configuration.ClientName ?? Environment.GetEnvironmentVariable("ComputerName"); } } public string ClientName => configuration.ClientName ?? Environment.GetEnvironmentVariable("ComputerName");
/// <summary> /// <summary>
/// Gets the configuration of the connection /// Gets the configuration of the connection
/// </summary> /// </summary>
public string Configuration public string Configuration => configuration.ToString();
{
get { return configuration.ToString(); }
}
internal void OnConnectionFailed(EndPoint endpoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception, bool reconfigure) internal void OnConnectionFailed(EndPoint endpoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception, bool reconfigure)
{ {
...@@ -223,7 +214,7 @@ static void Write<T>(ZipArchive zip, string name, Task task, Action<T, StreamWri ...@@ -223,7 +214,7 @@ static void Write<T>(ZipArchive zip, string name, Task task, Action<T, StreamWri
/// </summary> /// </summary>
public void ExportConfiguration(Stream destination, ExportOptions options = ExportOptions.All) public void ExportConfiguration(Stream destination, ExportOptions options = ExportOptions.All)
{ {
if (destination == null) throw new ArgumentNullException("destination"); if (destination == null) throw new ArgumentNullException(nameof(destination));
// what is possible, given the command map? // what is possible, given the command map?
ExportOptions mask = 0; ExportOptions mask = 0;
...@@ -302,7 +293,7 @@ internal void MakeMaster(ServerEndPoint server, ReplicationChangeOptions options ...@@ -302,7 +293,7 @@ internal void MakeMaster(ServerEndPoint server, ReplicationChangeOptions options
CommandMap.AssertAvailable(RedisCommand.SLAVEOF); CommandMap.AssertAvailable(RedisCommand.SLAVEOF);
if (!configuration.AllowAdmin) throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, RedisCommand.SLAVEOF, null, server); if (!configuration.AllowAdmin) throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, RedisCommand.SLAVEOF, null, server);
if (server == null) throw new ArgumentNullException("server"); if (server == null) throw new ArgumentNullException(nameof(server));
var srv = new RedisServer(this, server, null); var srv = new RedisServer(this, server, null);
if (!srv.IsConnected) throw ExceptionFactory.NoConnectionAvailable(IncludeDetailInExceptions, RedisCommand.SLAVEOF, null, server); if (!srv.IsConnected) throw ExceptionFactory.NoConnectionAvailable(IncludeDetailInExceptions, RedisCommand.SLAVEOF, null, server);
...@@ -400,11 +391,13 @@ internal void MakeMaster(ServerEndPoint server, ReplicationChangeOptions options ...@@ -400,11 +391,13 @@ internal void MakeMaster(ServerEndPoint server, ReplicationChangeOptions options
/// <summary> /// <summary>
/// Used internally to synchronize loggine without depending on locking the log instance /// Used internally to synchronize loggine without depending on locking the log instance
/// </summary> /// </summary>
private object LogSyncLock { get { return UniqueId; } } // we know this has strong identity: readonly and unique to us private object LogSyncLock => UniqueId;
// we know this has strong identity: readonly and unique to us
internal void LogLocked(TextWriter log, string line) internal void LogLocked(TextWriter log, string line)
{ {
if(log != null) lock (LogSyncLock) { log.WriteLine(line); } if (log != null) lock (LogSyncLock) { log.WriteLine(line); }
} }
internal void LogLocked(TextWriter log, string line, object arg) internal void LogLocked(TextWriter log, string line, object arg)
{ {
...@@ -469,10 +462,7 @@ static void WriteNormalizingLineEndings(string source, StreamWriter writer) ...@@ -469,10 +462,7 @@ static void WriteNormalizingLineEndings(string source, StreamWriter writer)
/// <summary> /// <summary>
/// Gets the timeout associated with the connections /// Gets the timeout associated with the connections
/// </summary> /// </summary>
public int TimeoutMilliseconds public int TimeoutMilliseconds => timeoutMilliseconds;
{
get { return timeoutMilliseconds; }
}
/// <summary> /// <summary>
/// Gets all endpoints defined on the server /// Gets all endpoints defined on the server
...@@ -501,7 +491,7 @@ internal bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool i ...@@ -501,7 +491,7 @@ internal bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool i
/// </summary> /// </summary>
public void Wait(Task task) public void Wait(Task task)
{ {
if (task == null) throw new ArgumentNullException("task"); if (task == null) throw new ArgumentNullException(nameof(task));
if (!task.Wait(timeoutMilliseconds)) throw new TimeoutException(); if (!task.Wait(timeoutMilliseconds)) throw new TimeoutException();
} }
...@@ -511,7 +501,7 @@ public void Wait(Task task) ...@@ -511,7 +501,7 @@ public void Wait(Task task)
public T Wait<T>(Task<T> task) public T Wait<T>(Task<T> task)
{ {
if (task == null) throw new ArgumentNullException("task"); if (task == null) throw new ArgumentNullException(nameof(task));
if (!task.Wait(timeoutMilliseconds)) throw new TimeoutException(); if (!task.Wait(timeoutMilliseconds)) throw new TimeoutException();
return task.Result; return task.Result;
} }
...@@ -520,7 +510,7 @@ public T Wait<T>(Task<T> task) ...@@ -520,7 +510,7 @@ public T Wait<T>(Task<T> task)
/// </summary> /// </summary>
public void WaitAll(params Task[] tasks) public void WaitAll(params Task[] tasks)
{ {
if (tasks == null) throw new ArgumentNullException("tasks"); if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return; if (tasks.Length == 0) return;
if (!Task.WaitAll(tasks, timeoutMilliseconds)) throw new TimeoutException(); if (!Task.WaitAll(tasks, timeoutMilliseconds)) throw new TimeoutException();
} }
...@@ -531,7 +521,7 @@ private bool WaitAllIgnoreErrors(Task[] tasks) ...@@ -531,7 +521,7 @@ private bool WaitAllIgnoreErrors(Task[] tasks)
} }
private static bool WaitAllIgnoreErrors(Task[] tasks, int timeout) private static bool WaitAllIgnoreErrors(Task[] tasks, int timeout)
{ {
if (tasks == null) throw new ArgumentNullException("tasks"); if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return true; if (tasks.Length == 0) return true;
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
try try
...@@ -589,7 +579,7 @@ static bool AllComplete(Task[] tasks) ...@@ -589,7 +579,7 @@ static bool AllComplete(Task[] tasks)
} }
private async Task<bool> WaitAllIgnoreErrorsAsync(Task[] tasks, int timeoutMilliseconds, TextWriter log) private async Task<bool> WaitAllIgnoreErrorsAsync(Task[] tasks, int timeoutMilliseconds, TextWriter log)
{ {
if (tasks == null) throw new ArgumentNullException("tasks"); if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) if (tasks.Length == 0)
{ {
LogLocked(log, "No tasks to await"); LogLocked(log, "No tasks to await");
...@@ -694,8 +684,6 @@ public int HashSlot(RedisKey key) ...@@ -694,8 +684,6 @@ public int HashSlot(RedisKey key)
return serverSelectionStrategy.HashSlot(key); return serverSelectionStrategy.HashSlot(key);
} }
internal ServerEndPoint AnyConnected(ServerType serverType, uint startOffset, RedisCommand command, CommandFlags flags) internal ServerEndPoint AnyConnected(ServerType serverType, uint startOffset, RedisCommand command, CommandFlags flags)
{ {
var tmp = serverSnapshot; var tmp = serverSnapshot;
...@@ -735,7 +723,8 @@ internal ServerEndPoint AnyConnected(ServerType serverType, uint startOffset, Re ...@@ -735,7 +723,8 @@ internal ServerEndPoint AnyConnected(ServerType serverType, uint startOffset, Re
} }
volatile bool isDisposed; volatile bool isDisposed;
internal bool IsDisposed { get { return isDisposed; } } internal bool IsDisposed => isDisposed;
/// <summary> /// <summary>
/// Create a new ConnectionMultiplexer instance /// Create a new ConnectionMultiplexer instance
/// </summary> /// </summary>
...@@ -784,7 +773,7 @@ public static async Task<ConnectionMultiplexer> ConnectAsync(ConfigurationOption ...@@ -784,7 +773,7 @@ public static async Task<ConnectionMultiplexer> ConnectAsync(ConfigurationOption
static ConnectionMultiplexer CreateMultiplexer(object configuration) static ConnectionMultiplexer CreateMultiplexer(object configuration)
{ {
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException(nameof(configuration));
ConfigurationOptions config; ConfigurationOptions config;
if (configuration is string) if (configuration is string)
{ {
...@@ -796,7 +785,7 @@ static ConnectionMultiplexer CreateMultiplexer(object configuration) ...@@ -796,7 +785,7 @@ static ConnectionMultiplexer CreateMultiplexer(object configuration)
{ {
throw new ArgumentException("configuration"); throw new ArgumentException("configuration");
} }
if (config.EndPoints.Count == 0) throw new ArgumentException("No endpoints specified", "configuration"); if (config.EndPoints.Count == 0) throw new ArgumentException("No endpoints specified", nameof(configuration));
config.SetDefaultPorts(); config.SetDefaultPorts();
return new ConnectionMultiplexer(config); return new ConnectionMultiplexer(config);
} }
...@@ -825,7 +814,7 @@ private static ConnectionMultiplexer ConnectImpl(Func<ConnectionMultiplexer> mul ...@@ -825,7 +814,7 @@ private static ConnectionMultiplexer ConnectImpl(Func<ConnectionMultiplexer> mul
killMe = muxer; killMe = muxer;
// note that task has timeouts internally, so it might take *just over* the regular timeout // note that task has timeouts internally, so it might take *just over* the regular timeout
// wrap into task to force async execution // wrap into task to force async execution
var task = Factory.StartNew(() => { return muxer.ReconfigureAsync(true, false, log, null, "connect").Result; }); var task = Factory.StartNew(() => muxer.ReconfigureAsync(true, false, log, null, "connect").Result);
if (!task.Wait(muxer.SyncConnectTimeout(true))) if (!task.Wait(muxer.SyncConnectTimeout(true)))
{ {
...@@ -881,12 +870,12 @@ internal ServerEndPoint GetServerEndPoint(EndPoint endpoint) ...@@ -881,12 +870,12 @@ internal ServerEndPoint GetServerEndPoint(EndPoint endpoint)
internal readonly CommandMap CommandMap; internal readonly CommandMap CommandMap;
private ConnectionMultiplexer(ConfigurationOptions configuration) private ConnectionMultiplexer(ConfigurationOptions configuration)
{ {
if (configuration == null) throw new ArgumentNullException("configuration"); if (configuration == null) throw new ArgumentNullException(nameof(configuration));
IncludeDetailInExceptions = true; IncludeDetailInExceptions = true;
this.configuration = configuration; this.configuration = configuration;
var map = this.CommandMap = configuration.CommandMap; var map = CommandMap = configuration.CommandMap;
if (!string.IsNullOrWhiteSpace(configuration.Password)) map.AssertAvailable(RedisCommand.AUTH); if (!string.IsNullOrWhiteSpace(configuration.Password)) map.AssertAvailable(RedisCommand.AUTH);
if(!map.IsAvailable(RedisCommand.ECHO) && !map.IsAvailable(RedisCommand.PING) && !map.IsAvailable(RedisCommand.TIME)) if(!map.IsAvailable(RedisCommand.ECHO) && !map.IsAvailable(RedisCommand.PING) && !map.IsAvailable(RedisCommand.TIME))
...@@ -896,7 +885,7 @@ private ConnectionMultiplexer(ConfigurationOptions configuration) ...@@ -896,7 +885,7 @@ private ConnectionMultiplexer(ConfigurationOptions configuration)
} }
PreserveAsyncOrder = true; // safest default PreserveAsyncOrder = true; // safest default
this.timeoutMilliseconds = configuration.SyncTimeout; timeoutMilliseconds = configuration.SyncTimeout;
OnCreateReaderWriter(configuration); OnCreateReaderWriter(configuration);
unprocessableCompletionManager = new CompletionManager(this, "multiplexer"); unprocessableCompletionManager = new CompletionManager(this, "multiplexer");
...@@ -944,10 +933,9 @@ private void OnHeartbeat() ...@@ -944,10 +933,9 @@ private void OnHeartbeat()
return unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastHeartbeatTicks)) / 1000; return unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastHeartbeatTicks)) / 1000;
} }
} }
internal static long LastGlobalHeartbeatSecondsAgo internal static long LastGlobalHeartbeatSecondsAgo => unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastGlobalHeartbeatTicks)) / 1000;
{ get { return unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastGlobalHeartbeatTicks)) / 1000; } }
internal CompletionManager UnprocessableCompletionManager { get { return unprocessableCompletionManager; } } internal CompletionManager UnprocessableCompletionManager => unprocessableCompletionManager;
/// <summary> /// <summary>
/// Obtain a pub/sub subscriber connection to the specified server /// Obtain a pub/sub subscriber connection to the specified server
...@@ -965,7 +953,7 @@ public IDatabase GetDatabase(int db = -1, object asyncState = null) ...@@ -965,7 +953,7 @@ public IDatabase GetDatabase(int db = -1, object asyncState = null)
if (db == -1) if (db == -1)
db = configuration.DefaultDatabase ?? 0; db = configuration.DefaultDatabase ?? 0;
if (db < 0) throw new ArgumentOutOfRangeException("db"); if (db < 0) throw new ArgumentOutOfRangeException(nameof(db));
if (db != 0 && RawConfig.Proxy == Proxy.Twemproxy) throw new NotSupportedException("Twemproxy only supports database 0"); if (db != 0 && RawConfig.Proxy == Proxy.Twemproxy) throw new NotSupportedException("Twemproxy only supports database 0");
return new RedisDatabase(this, db, asyncState); return new RedisDatabase(this, db, asyncState);
} }
...@@ -998,10 +986,10 @@ public IServer GetServer(IPAddress host, int port) ...@@ -998,10 +986,10 @@ public IServer GetServer(IPAddress host, int port)
/// </summary> /// </summary>
public IServer GetServer(EndPoint endpoint, object asyncState = null) public IServer GetServer(EndPoint endpoint, object asyncState = null)
{ {
if (endpoint == null) throw new ArgumentNullException("endpoint"); if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
if (RawConfig.Proxy == Proxy.Twemproxy) throw new NotSupportedException("The server API is not available via twemproxy"); if (RawConfig.Proxy == Proxy.Twemproxy) throw new NotSupportedException("The server API is not available via twemproxy");
var server = (ServerEndPoint)servers[endpoint]; var server = (ServerEndPoint)servers[endpoint];
if (server == null) throw new ArgumentException("The specified endpoint is not defined", "endpoint"); if (server == null) throw new ArgumentException("The specified endpoint is not defined", nameof(endpoint));
return new RedisServer(this, server, asyncState); return new RedisServer(this, server, asyncState);
} }
...@@ -1178,20 +1166,20 @@ internal async Task<bool> ReconfigureAsync(bool first, bool reconfigureAll, Text ...@@ -1178,20 +1166,20 @@ internal async Task<bool> ReconfigureAsync(bool first, bool reconfigureAll, Text
} }
} }
int index = 0; int index = 0;
lock (this.servers) lock (servers)
{ {
serverSnapshot = new ServerEndPoint[configuration.EndPoints.Count]; serverSnapshot = new ServerEndPoint[configuration.EndPoints.Count];
foreach (var endpoint in configuration.EndPoints) foreach (var endpoint in configuration.EndPoints)
{ {
var server = new ServerEndPoint(this, endpoint, log); var server = new ServerEndPoint(this, endpoint, log);
serverSnapshot[index++] = server; serverSnapshot[index++] = server;
this.servers.Add(endpoint, server); servers.Add(endpoint, server);
} }
} }
foreach (var server in serverSnapshot) foreach (var server in serverSnapshot)
{ {
server.Activate(ConnectionType.Interactive, log); server.Activate(ConnectionType.Interactive, log);
if (this.CommandMap.IsAvailable(RedisCommand.SUBSCRIBE)) if (CommandMap.IsAvailable(RedisCommand.SUBSCRIBE))
{ {
server.Activate(ConnectionType.Subscription, null); // no need to log the SUB stuff server.Activate(ConnectionType.Subscription, null); // no need to log the SUB stuff
} }
...@@ -1373,15 +1361,15 @@ internal async Task<bool> ReconfigureAsync(bool first, bool reconfigureAll, Text ...@@ -1373,15 +1361,15 @@ internal async Task<bool> ReconfigureAsync(bool first, bool reconfigureAll, Text
// set the serverSelectionStrategy // set the serverSelectionStrategy
if (RawConfig.Proxy == Proxy.Twemproxy) if (RawConfig.Proxy == Proxy.Twemproxy)
{ {
this.serverSelectionStrategy.ServerType = ServerType.Twemproxy; serverSelectionStrategy.ServerType = ServerType.Twemproxy;
} }
else if (standaloneCount == 0 && sentinelCount > 0) else if (standaloneCount == 0 && sentinelCount > 0)
{ {
this.serverSelectionStrategy.ServerType = ServerType.Sentinel; serverSelectionStrategy.ServerType = ServerType.Sentinel;
} }
else else
{ {
this.serverSelectionStrategy.ServerType = ServerType.Standalone; serverSelectionStrategy.ServerType = ServerType.Standalone;
} }
var preferred = await NominatePreferredMaster(log, servers, useTieBreakers, tieBreakers, masters).ObserveErrors().ForAwait(); var preferred = await NominatePreferredMaster(log, servers, useTieBreakers, tieBreakers, masters).ObserveErrors().ForAwait();
foreach (var master in masters) foreach (var master in masters)
...@@ -1716,17 +1704,13 @@ private bool TryPushMessageToBridge<T>(Message message, ResultProcessor<T> proce ...@@ -1716,17 +1704,13 @@ private bool TryPushMessageToBridge<T>(Message message, ResultProcessor<T> proce
if (server != null) if (server != null)
{ {
if (profiler != null) var profCtx = profiler?.GetContext();
if (profCtx != null)
{ {
var profCtx = profiler.GetContext(); ConcurrentProfileStorageCollection inFlightForCtx;
if (profiledCommands.TryGetValue(profCtx, out inFlightForCtx))
if(profCtx != null)
{ {
ConcurrentProfileStorageCollection inFlightForCtx; message.SetProfileStorage(ProfileStorage.NewWithContext(inFlightForCtx, server));
if (profiledCommands.TryGetValue(profCtx, out inFlightForCtx))
{
message.SetProfileStorage(ProfileStorage.NewWithContext(inFlightForCtx, server));
}
} }
} }
...@@ -1778,9 +1762,9 @@ public bool IsConnected ...@@ -1778,9 +1762,9 @@ public bool IsConnected
} }
} }
internal ConfigurationOptions RawConfig { get { return configuration; } } internal ConfigurationOptions RawConfig => configuration;
internal ServerSelectionStrategy ServerSelectionStrategy { get { return serverSelectionStrategy; } } internal ServerSelectionStrategy ServerSelectionStrategy => serverSelectionStrategy;
/// <summary> /// <summary>
...@@ -2028,8 +2012,8 @@ private static int GetThreadPoolStats(out string iocp, out string worker) ...@@ -2028,8 +2012,8 @@ private static int GetThreadPoolStats(out string iocp, out string worker)
int busyIoThreads = maxIoThreads - freeIoThreads; int busyIoThreads = maxIoThreads - freeIoThreads;
int busyWorkerThreads = maxWorkerThreads - freeWorkerThreads; int busyWorkerThreads = maxWorkerThreads - freeWorkerThreads;
iocp = string.Format("(Busy={0},Free={1},Min={2},Max={3})", busyIoThreads, freeIoThreads, minIoThreads, maxIoThreads); iocp = $"(Busy={busyIoThreads},Free={freeIoThreads},Min={minIoThreads},Max={maxIoThreads})";
worker = string.Format("(Busy={0},Free={1},Min={2},Max={3})", busyWorkerThreads, freeWorkerThreads, minWorkerThreads, maxWorkerThreads); worker = $"(Busy={busyWorkerThreads},Free={freeWorkerThreads},Min={minWorkerThreads},Max={maxWorkerThreads})";
return busyWorkerThreads; return busyWorkerThreads;
} }
#endif #endif
......
...@@ -17,7 +17,7 @@ public static long GetAllocationCount() ...@@ -17,7 +17,7 @@ public static long GetAllocationCount()
} }
static partial void OnAllocated() static partial void OnAllocated()
{ {
Interlocked.Increment(ref ResultBox.allocations); Interlocked.Increment(ref allocations);
} }
} }
partial interface IServer partial interface IServer
...@@ -103,17 +103,17 @@ partial class ServerEndPoint ...@@ -103,17 +103,17 @@ partial class ServerEndPoint
internal void SimulateConnectionFailure() internal void SimulateConnectionFailure()
{ {
var tmp = interactive; var tmp = interactive;
if (tmp != null) tmp.SimulateConnectionFailure(); tmp?.SimulateConnectionFailure();
tmp = subscription; tmp = subscription;
if (tmp != null) tmp.SimulateConnectionFailure(); tmp?.SimulateConnectionFailure();
} }
internal string ListPending(int maxCount) internal string ListPending(int maxCount)
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var tmp = interactive; var tmp = interactive;
if (tmp != null) tmp.ListPending(sb, maxCount); tmp?.ListPending(sb, maxCount);
tmp = subscription; tmp = subscription;
if (tmp != null) tmp.ListPending(sb, maxCount); tmp?.ListPending(sb, maxCount);
return sb.ToString(); return sb.ToString();
} }
} }
...@@ -231,12 +231,11 @@ partial class PhysicalBridge ...@@ -231,12 +231,11 @@ partial class PhysicalBridge
{ {
internal void SimulateConnectionFailure() internal void SimulateConnectionFailure()
{ {
if (!multiplexer.RawConfig.AllowAdmin) if (!Multiplexer.RawConfig.AllowAdmin)
{ {
throw ExceptionFactory.AdminModeNotEnabled(multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, serverEndPoint); // close enough throw ExceptionFactory.AdminModeNotEnabled(Multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, ServerEndPoint); // close enough
} }
var tmp = physical; physical?.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
if (tmp != null) tmp.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
} }
internal void ListPending(StringBuilder sb, int maxCount) internal void ListPending(StringBuilder sb, int maxCount)
{ {
...@@ -248,20 +247,18 @@ partial class PhysicalConnection ...@@ -248,20 +247,18 @@ partial class PhysicalConnection
{ {
partial void OnDebugAbort() partial void OnDebugAbort()
{ {
if (!multiplexer.AllowConnect) if (!Multiplexer.AllowConnect)
{ {
throw new RedisConnectionException(ConnectionFailureType.InternalFailure, "debugging"); throw new RedisConnectionException(ConnectionFailureType.InternalFailure, "debugging");
} }
} }
bool ISocketCallback.IgnoreConnect bool ISocketCallback.IgnoreConnect => Multiplexer.IgnoreConnect;
{
get { return multiplexer.IgnoreConnect; }
}
private volatile static bool emulateStaleConnection; private static volatile bool emulateStaleConnection;
public static bool EmulateStaleConnection public static bool EmulateStaleConnection
{ get {
get
{ {
return emulateStaleConnection; return emulateStaleConnection;
} }
......
...@@ -16,6 +16,7 @@ public sealed class EndPointCollection : Collection<EndPoint> ...@@ -16,6 +16,7 @@ public sealed class EndPointCollection : Collection<EndPoint>
public EndPointCollection() : base() public EndPointCollection() : base()
{ {
} }
/// <summary> /// <summary>
/// Create a new EndPointCollection /// Create a new EndPointCollection
/// </summary> /// </summary>
...@@ -63,16 +64,14 @@ public void Add(IPAddress host, int port) ...@@ -63,16 +64,14 @@ public void Add(IPAddress host, int port)
{ {
Add(new IPEndPoint(host, port)); Add(new IPEndPoint(host, port));
} }
/// <summary> /// <summary>
/// See Collection&lt;T&gt;.InsertItem() /// See Collection&lt;T&gt;.InsertItem()
/// </summary> /// </summary>
protected override void InsertItem(int index, EndPoint item) protected override void InsertItem(int index, EndPoint item)
{ {
if (item == null) throw new ArgumentNullException("item"); if (item == null) throw new ArgumentNullException(nameof(item));
if (Contains(item)) throw new ArgumentException("EndPoints must be unique", "item"); if (Contains(item)) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.InsertItem(index, item); base.InsertItem(index, item);
} }
/// <summary> /// <summary>
...@@ -80,7 +79,7 @@ protected override void InsertItem(int index, EndPoint item) ...@@ -80,7 +79,7 @@ protected override void InsertItem(int index, EndPoint item)
/// </summary> /// </summary>
protected override void SetItem(int index, EndPoint item) protected override void SetItem(int index, EndPoint item)
{ {
if (item == null) throw new ArgumentNullException("item"); if (item == null) throw new ArgumentNullException(nameof(item));
int existingIndex; int existingIndex;
try try
{ {
...@@ -90,7 +89,7 @@ protected override void SetItem(int index, EndPoint item) ...@@ -90,7 +89,7 @@ protected override void SetItem(int index, EndPoint item)
// mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help // mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help
existingIndex = -1; existingIndex = -1;
} }
if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", "item"); if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.SetItem(index, item); base.SetItem(index, item);
} }
...@@ -100,22 +99,16 @@ internal void SetDefaultPorts(int defaultPort) ...@@ -100,22 +99,16 @@ internal void SetDefaultPorts(int defaultPort)
{ {
var endpoint = this[i]; var endpoint = this[i];
var dns = endpoint as DnsEndPoint; var dns = endpoint as DnsEndPoint;
if (dns != null) if (dns?.Port == 0)
{ {
if (dns.Port == 0) this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
{ continue;
this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
continue;
}
} }
var ip = endpoint as IPEndPoint; var ip = endpoint as IPEndPoint;
if (ip != null) if (ip?.Port == 0)
{ {
if (ip.Port == 0) this[i] = new IPEndPoint(ip.Address, defaultPort);
{ continue;
this[i] = new IPEndPoint(ip.Address, defaultPort);
continue;
}
} }
} }
} }
......
...@@ -9,28 +9,25 @@ namespace StackExchange.Redis ...@@ -9,28 +9,25 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class EndPointEventArgs : EventArgs, ICompletable public class EndPointEventArgs : EventArgs, ICompletable
{ {
private readonly EndPoint endpoint;
private readonly EventHandler<EndPointEventArgs> handler; private readonly EventHandler<EndPointEventArgs> handler;
private readonly object sender; private readonly object sender;
internal EndPointEventArgs(EventHandler<EndPointEventArgs> handler, object sender, EndPoint endpoint) internal EndPointEventArgs(EventHandler<EndPointEventArgs> handler, object sender, EndPoint endpoint)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endpoint; EndPoint = endpoint;
} }
/// <summary> /// <summary>
/// The endpoint involved in this event (this can be null) /// The endpoint involved in this event (this can be null)
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, endpoint: "); sb.Append("event, endpoint: ");
if (endpoint == null) sb.Append("n/a"); if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint)); else sb.Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
...@@ -90,7 +90,7 @@ internal static string ToString(EndPoint endpoint) ...@@ -90,7 +90,7 @@ internal static string ToString(EndPoint endpoint)
if (ip.Port == 0) return ip.Address.ToString(); if (ip.Port == 0) return ip.Address.ToString();
return ip.Address.ToString() + ":" + Format.ToString(ip.Port); return ip.Address.ToString() + ":" + Format.ToString(ip.Port);
} }
return endpoint == null ? "" : endpoint.ToString(); return endpoint?.ToString() ?? "";
} }
internal static string ToStringHostOnly(EndPoint endpoint) internal static string ToStringHostOnly(EndPoint endpoint)
{ {
...@@ -118,7 +118,7 @@ internal static bool TryGetHostPort(EndPoint endpoint, out string host, out int ...@@ -118,7 +118,7 @@ internal static bool TryGetHostPort(EndPoint endpoint, out string host, out int
port = ip.Port; port = ip.Port;
return true; return true;
} }
else if (endpoint is DnsEndPoint) if (endpoint is DnsEndPoint)
{ {
DnsEndPoint dns = (DnsEndPoint)endpoint; DnsEndPoint dns = (DnsEndPoint)endpoint;
host = dns.Host; host = dns.Host;
......
...@@ -22,11 +22,12 @@ public HashEntry(RedisValue name, RedisValue value) ...@@ -22,11 +22,12 @@ public HashEntry(RedisValue name, RedisValue value)
/// <summary> /// <summary>
/// The name of the hash field /// The name of the hash field
/// </summary> /// </summary>
public RedisValue Name { get { return name; } } public RedisValue Name => name;
/// <summary> /// <summary>
/// The value of the hash field /// The value of the hash field
/// </summary> /// </summary>
public RedisValue Value{ get { return value; } } public RedisValue Value => value;
/// <summary> /// <summary>
/// The name of the hash field /// The name of the hash field
...@@ -79,7 +80,7 @@ public override bool Equals(object obj) ...@@ -79,7 +80,7 @@ public override bool Equals(object obj)
/// </summary> /// </summary>
public bool Equals(HashEntry value) public bool Equals(HashEntry value)
{ {
return this.name == value.name && this.value == value.value; return name == value.name && this.value == value.value;
} }
/// <summary> /// <summary>
/// Compares two values for equality /// Compares two values for equality
......
...@@ -9,31 +9,31 @@ namespace StackExchange.Redis ...@@ -9,31 +9,31 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class HashSlotMovedEventArgs : EventArgs, ICompletable public sealed class HashSlotMovedEventArgs : EventArgs, ICompletable
{ {
private readonly int hashSlot;
private readonly EndPoint old, @new;
private readonly object sender; private readonly object sender;
private readonly EventHandler<HashSlotMovedEventArgs> handler; private readonly EventHandler<HashSlotMovedEventArgs> handler;
/// <summary> /// <summary>
/// The hash-slot that was relocated /// The hash-slot that was relocated
/// </summary> /// </summary>
public int HashSlot { get { return hashSlot; } } public int HashSlot { get; }
/// <summary> /// <summary>
/// The old endpoint for this hash-slot (if known) /// The old endpoint for this hash-slot (if known)
/// </summary> /// </summary>
public EndPoint OldEndPoint { get { return old; } } public EndPoint OldEndPoint { get; }
/// <summary> /// <summary>
/// The new endpoint for this hash-slot (if known) /// The new endpoint for this hash-slot (if known)
/// </summary> /// </summary>
public EndPoint NewEndPoint { get { return @new; } } public EndPoint NewEndPoint { get; }
internal HashSlotMovedEventArgs(EventHandler<HashSlotMovedEventArgs> handler, object sender, internal HashSlotMovedEventArgs(EventHandler<HashSlotMovedEventArgs> handler, object sender,
int hashSlot, EndPoint old, EndPoint @new) int hashSlot, EndPoint old, EndPoint @new)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.hashSlot = hashSlot; HashSlot = hashSlot;
this.old = old; OldEndPoint = old;
this.@new = @new; NewEndPoint = @new;
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
...@@ -43,7 +43,7 @@ bool ICompletable.TryComplete(bool isAsync) ...@@ -43,7 +43,7 @@ bool ICompletable.TryComplete(bool isAsync)
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, slot-moved: ").Append(hashSlot); sb.Append("event, slot-moved: ").Append(HashSlot);
} }
} }
} }
...@@ -909,21 +909,20 @@ public interface IDatabaseAsync : IRedisAsync ...@@ -909,21 +909,20 @@ public interface IDatabaseAsync : IRedisAsync
/// </summary> /// </summary>
public struct RedisValueWithExpiry public struct RedisValueWithExpiry
{ {
private readonly TimeSpan? expiry;
private readonly RedisValue value;
internal RedisValueWithExpiry(RedisValue value, TimeSpan? expiry) internal RedisValueWithExpiry(RedisValue value, TimeSpan? expiry)
{ {
this.value = value; Value = value;
this.expiry = expiry; Expiry = expiry;
} }
/// <summary> /// <summary>
/// The expiry of this record /// The expiry of this record
/// </summary> /// </summary>
public TimeSpan? Expiry { get { return expiry; } } public TimeSpan? Expiry { get; }
/// <summary> /// <summary>
/// The value of this record /// The value of this record
/// </summary> /// </summary>
public RedisValue Value { get { return value; } } public RedisValue Value { get; }
} }
} }
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
internal interface IMultiMessage internal interface IMultiMessage
{ IEnumerable<Message> GetMessages(PhysicalConnection connection); {
IEnumerable<Message> GetMessages(PhysicalConnection connection);
} }
} }
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
...@@ -43,7 +43,7 @@ internal class IgnoreNamePrefixAttribute : Attribute ...@@ -43,7 +43,7 @@ internal class IgnoreNamePrefixAttribute : Attribute
{ {
public IgnoreNamePrefixAttribute(bool ignoreEntireMethod = false) public IgnoreNamePrefixAttribute(bool ignoreEntireMethod = false)
{ {
this.IgnoreEntireMethod = ignoreEntireMethod; IgnoreEntireMethod = ignoreEntireMethod;
} }
public bool IgnoreEntireMethod { get; private set; } public bool IgnoreEntireMethod { get; private set; }
......
...@@ -9,55 +9,41 @@ namespace StackExchange.Redis ...@@ -9,55 +9,41 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class InternalErrorEventArgs : EventArgs, ICompletable public class InternalErrorEventArgs : EventArgs, ICompletable
{ {
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly EventHandler<InternalErrorEventArgs> handler; private readonly EventHandler<InternalErrorEventArgs> handler;
private readonly string origin;
private readonly object sender; private readonly object sender;
internal InternalErrorEventArgs(EventHandler<InternalErrorEventArgs> handler, object sender, EndPoint endpoint, ConnectionType connectionType, Exception exception, string origin) internal InternalErrorEventArgs(EventHandler<InternalErrorEventArgs> handler, object sender, EndPoint endpoint, ConnectionType connectionType, Exception exception, string origin)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endpoint; EndPoint = endpoint;
this.connectionType = connectionType; ConnectionType = connectionType;
this.exception = exception; Exception = exception;
this.origin = origin; Origin = origin;
} }
/// <summary> /// <summary>
/// Gets the connection-type of the failing connection /// Gets the connection-type of the failing connection
/// </summary> /// </summary>
public ConnectionType ConnectionType public ConnectionType ConnectionType { get; }
{
get { return connectionType; }
}
/// <summary> /// <summary>
/// Gets the failing server-endpoint (this can be null) /// Gets the failing server-endpoint (this can be null)
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
/// <summary> /// <summary>
/// Gets the exception if available (this can be null) /// Gets the exception if available (this can be null)
/// </summary> /// </summary>
public Exception Exception public Exception Exception { get; }
{
get { return exception; }
}
/// <summary> /// <summary>
/// The underlying origin of the error /// The underlying origin of the error
/// </summary> /// </summary>
public string Origin public string Origin { get; }
{
get { return origin; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, internal-error: ").Append(origin); sb.Append("event, internal-error: ").Append(Origin);
if (endpoint != null) sb.Append(", ").Append(Format.ToString(endpoint)); if (EndPoint != null) sb.Append(", ").Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
using System; using System.Text.RegularExpressions;
using System.Text.RegularExpressions; #if CORE_CLR
using System;
#endif
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
...@@ -2,14 +2,13 @@ ...@@ -2,14 +2,13 @@
{ {
internal sealed class BatchWrapper : WrapperBase<IBatch>, IBatch internal sealed class BatchWrapper : WrapperBase<IBatch>, IBatch
{ {
public BatchWrapper(IBatch inner, byte[] prefix) public BatchWrapper(IBatch inner, byte[] prefix) : base(inner, prefix)
: base(inner, prefix)
{ {
} }
public void Execute() public void Execute()
{ {
this.Inner.Execute(); Inner.Execute();
} }
} }
} }
...@@ -41,12 +41,12 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi ...@@ -41,12 +41,12 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi
{ {
if (database == null) if (database == null)
{ {
throw new ArgumentNullException("database"); throw new ArgumentNullException(nameof(database));
} }
if (keyPrefix.IsNull) if (keyPrefix.IsNull)
{ {
throw new ArgumentNullException("keyPrefix"); throw new ArgumentNullException(nameof(keyPrefix));
} }
if (keyPrefix.IsEmpty) if (keyPrefix.IsEmpty)
......
...@@ -6,184 +6,180 @@ namespace StackExchange.Redis.KeyspaceIsolation ...@@ -6,184 +6,180 @@ namespace StackExchange.Redis.KeyspaceIsolation
{ {
internal sealed class DatabaseWrapper : WrapperBase<IDatabase>, IDatabase internal sealed class DatabaseWrapper : WrapperBase<IDatabase>, IDatabase
{ {
public DatabaseWrapper(IDatabase inner, byte[] prefix) public DatabaseWrapper(IDatabase inner, byte[] prefix) : base(inner, prefix)
: base(inner, prefix)
{ {
} }
public IBatch CreateBatch(object asyncState = null) public IBatch CreateBatch(object asyncState = null)
{ {
return new BatchWrapper(this.Inner.CreateBatch(asyncState), this.Prefix); return new BatchWrapper(Inner.CreateBatch(asyncState), Prefix);
} }
public ITransaction CreateTransaction(object asyncState = null) public ITransaction CreateTransaction(object asyncState = null)
{ {
return new TransactionWrapper(this.Inner.CreateTransaction(asyncState), this.Prefix); return new TransactionWrapper(Inner.CreateTransaction(asyncState), Prefix);
} }
public int Database public int Database => Inner.Database;
{
get { return this.Inner.Database; }
}
public RedisValue DebugObject(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue DebugObject(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.DebugObject(this.ToInner(key), flags); return Inner.DebugObject(ToInner(key), flags);
} }
public double HashDecrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) public double HashDecrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDecrement(this.ToInner(key), hashField, value, flags); return Inner.HashDecrement(ToInner(key), hashField, value, flags);
} }
public long HashDecrement(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) public long HashDecrement(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDecrement(this.ToInner(key), hashField, value, flags); return Inner.HashDecrement(ToInner(key), hashField, value, flags);
} }
public long HashDelete(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) public long HashDelete(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDelete(this.ToInner(key), hashFields, flags); return Inner.HashDelete(ToInner(key), hashFields, flags);
} }
public bool HashDelete(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public bool HashDelete(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDelete(this.ToInner(key), hashField, flags); return Inner.HashDelete(ToInner(key), hashField, flags);
} }
public bool HashExists(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public bool HashExists(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashExists(this.ToInner(key), hashField, flags); return Inner.HashExists(ToInner(key), hashField, flags);
} }
public HashEntry[] HashGetAll(RedisKey key, CommandFlags flags = CommandFlags.None) public HashEntry[] HashGetAll(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGetAll(this.ToInner(key), flags); return Inner.HashGetAll(ToInner(key), flags);
} }
public RedisValue[] HashGet(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) public RedisValue[] HashGet(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGet(this.ToInner(key), hashFields, flags); return Inner.HashGet(ToInner(key), hashFields, flags);
} }
public RedisValue HashGet(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public RedisValue HashGet(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGet(this.ToInner(key), hashField, flags); return Inner.HashGet(ToInner(key), hashField, flags);
} }
public double HashIncrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) public double HashIncrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashIncrement(this.ToInner(key), hashField, value, flags); return Inner.HashIncrement(ToInner(key), hashField, value, flags);
} }
public long HashIncrement(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) public long HashIncrement(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashIncrement(this.ToInner(key), hashField, value, flags); return Inner.HashIncrement(ToInner(key), hashField, value, flags);
} }
public RedisValue[] HashKeys(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue[] HashKeys(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashKeys(this.ToInner(key), flags); return Inner.HashKeys(ToInner(key), flags);
} }
public long HashLength(RedisKey key, CommandFlags flags = CommandFlags.None) public long HashLength(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashLength(this.ToInner(key), flags); return Inner.HashLength(ToInner(key), flags);
} }
public bool HashSet(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public bool HashSet(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashSet(this.ToInner(key), hashField, value, when, flags); return Inner.HashSet(ToInner(key), hashField, value, when, flags);
} }
public void HashSet(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None) public void HashSet(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.HashSet(this.ToInner(key), hashFields, flags); Inner.HashSet(ToInner(key), hashFields, flags);
} }
public RedisValue[] HashValues(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue[] HashValues(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashValues(this.ToInner(key), flags); return Inner.HashValues(ToInner(key), flags);
} }
public bool HyperLogLogAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public bool HyperLogLogAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogAdd(this.ToInner(key), values, flags); return Inner.HyperLogLogAdd(ToInner(key), values, flags);
} }
public bool HyperLogLogAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public bool HyperLogLogAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogAdd(this.ToInner(key), value, flags); return Inner.HyperLogLogAdd(ToInner(key), value, flags);
} }
public long HyperLogLogLength(RedisKey key, CommandFlags flags = CommandFlags.None) public long HyperLogLogLength(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogLength(this.ToInner(key), flags); return Inner.HyperLogLogLength(ToInner(key), flags);
} }
public long HyperLogLogLength(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public long HyperLogLogLength(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogLength(this.ToInner(keys), flags); return Inner.HyperLogLogLength(ToInner(keys), flags);
} }
public void HyperLogLogMerge(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) public void HyperLogLogMerge(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.HyperLogLogMerge(this.ToInner(destination), this.ToInner(sourceKeys), flags); Inner.HyperLogLogMerge(ToInner(destination), ToInner(sourceKeys), flags);
} }
public void HyperLogLogMerge(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public void HyperLogLogMerge(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.HyperLogLogMerge(this.ToInner(destination), this.ToInner(first), this.ToInner(second), flags); Inner.HyperLogLogMerge(ToInner(destination), ToInner(first), ToInner(second), flags);
} }
public EndPoint IdentifyEndpoint(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None) public EndPoint IdentifyEndpoint(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.IdentifyEndpoint(this.ToInner(key), flags); return Inner.IdentifyEndpoint(ToInner(key), flags);
} }
public long KeyDelete(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public long KeyDelete(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDelete(this.ToInner(keys), flags); return Inner.KeyDelete(ToInner(keys), flags);
} }
public bool KeyDelete(RedisKey key, CommandFlags flags = CommandFlags.None) public bool KeyDelete(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDelete(this.ToInner(key), flags); return Inner.KeyDelete(ToInner(key), flags);
} }
public byte[] KeyDump(RedisKey key, CommandFlags flags = CommandFlags.None) public byte[] KeyDump(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDump(this.ToInner(key), flags); return Inner.KeyDump(ToInner(key), flags);
} }
public bool KeyExists(RedisKey key, CommandFlags flags = CommandFlags.None) public bool KeyExists(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExists(this.ToInner(key), flags); return Inner.KeyExists(ToInner(key), flags);
} }
public bool KeyExpire(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None) public bool KeyExpire(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExpire(this.ToInner(key), expiry, flags); return Inner.KeyExpire(ToInner(key), expiry, flags);
} }
public bool KeyExpire(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None) public bool KeyExpire(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExpire(this.ToInner(key), expiry, flags); return Inner.KeyExpire(ToInner(key), expiry, flags);
} }
public void KeyMigrate(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None) public void KeyMigrate(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.KeyMigrate(this.ToInner(key), toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags); Inner.KeyMigrate(ToInner(key), toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags);
} }
public bool KeyMove(RedisKey key, int database, CommandFlags flags = CommandFlags.None) public bool KeyMove(RedisKey key, int database, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyMove(this.ToInner(key), database, flags); return Inner.KeyMove(ToInner(key), database, flags);
} }
public bool KeyPersist(RedisKey key, CommandFlags flags = CommandFlags.None) public bool KeyPersist(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyPersist(this.ToInner(key), flags); return Inner.KeyPersist(ToInner(key), flags);
} }
public RedisKey KeyRandom(CommandFlags flags = CommandFlags.None) public RedisKey KeyRandom(CommandFlags flags = CommandFlags.None)
...@@ -193,436 +189,436 @@ public RedisKey KeyRandom(CommandFlags flags = CommandFlags.None) ...@@ -193,436 +189,436 @@ public RedisKey KeyRandom(CommandFlags flags = CommandFlags.None)
public bool KeyRename(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None) public bool KeyRename(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyRename(this.ToInner(key), this.ToInner(newKey), when, flags); return Inner.KeyRename(ToInner(key), ToInner(newKey), when, flags);
} }
public void KeyRestore(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None) public void KeyRestore(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.KeyRestore(this.ToInner(key), value, expiry, flags); Inner.KeyRestore(ToInner(key), value, expiry, flags);
} }
public TimeSpan? KeyTimeToLive(RedisKey key, CommandFlags flags = CommandFlags.None) public TimeSpan? KeyTimeToLive(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyTimeToLive(this.ToInner(key), flags); return Inner.KeyTimeToLive(ToInner(key), flags);
} }
public RedisType KeyType(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisType KeyType(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyType(this.ToInner(key), flags); return Inner.KeyType(ToInner(key), flags);
} }
public RedisValue ListGetByIndex(RedisKey key, long index, CommandFlags flags = CommandFlags.None) public RedisValue ListGetByIndex(RedisKey key, long index, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListGetByIndex(this.ToInner(key), index, flags); return Inner.ListGetByIndex(ToInner(key), index, flags);
} }
public long ListInsertAfter(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) public long ListInsertAfter(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListInsertAfter(this.ToInner(key), pivot, value, flags); return Inner.ListInsertAfter(ToInner(key), pivot, value, flags);
} }
public long ListInsertBefore(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) public long ListInsertBefore(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListInsertBefore(this.ToInner(key), pivot, value, flags); return Inner.ListInsertBefore(ToInner(key), pivot, value, flags);
} }
public RedisValue ListLeftPop(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue ListLeftPop(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPop(this.ToInner(key), flags); return Inner.ListLeftPop(ToInner(key), flags);
} }
public long ListLeftPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public long ListLeftPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPush(this.ToInner(key), values, flags); return Inner.ListLeftPush(ToInner(key), values, flags);
} }
public long ListLeftPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public long ListLeftPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPush(this.ToInner(key), value, when, flags); return Inner.ListLeftPush(ToInner(key), value, when, flags);
} }
public long ListLength(RedisKey key, CommandFlags flags = CommandFlags.None) public long ListLength(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLength(this.ToInner(key), flags); return Inner.ListLength(ToInner(key), flags);
} }
public RedisValue[] ListRange(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None) public RedisValue[] ListRange(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRange(this.ToInner(key), start, stop, flags); return Inner.ListRange(ToInner(key), start, stop, flags);
} }
public long ListRemove(RedisKey key, RedisValue value, long count = 0, CommandFlags flags = CommandFlags.None) public long ListRemove(RedisKey key, RedisValue value, long count = 0, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRemove(this.ToInner(key), value, count, flags); return Inner.ListRemove(ToInner(key), value, count, flags);
} }
public RedisValue ListRightPop(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue ListRightPop(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPop(this.ToInner(key), flags); return Inner.ListRightPop(ToInner(key), flags);
} }
public RedisValue ListRightPopLeftPush(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None) public RedisValue ListRightPopLeftPush(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPopLeftPush(this.ToInner(source), this.ToInner(destination), flags); return Inner.ListRightPopLeftPush(ToInner(source), ToInner(destination), flags);
} }
public long ListRightPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public long ListRightPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPush(this.ToInner(key), values, flags); return Inner.ListRightPush(ToInner(key), values, flags);
} }
public long ListRightPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public long ListRightPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPush(this.ToInner(key), value, when, flags); return Inner.ListRightPush(ToInner(key), value, when, flags);
} }
public void ListSetByIndex(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None) public void ListSetByIndex(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.ListSetByIndex(this.ToInner(key), index, value, flags); Inner.ListSetByIndex(ToInner(key), index, value, flags);
} }
public void ListTrim(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) public void ListTrim(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None)
{ {
this.Inner.ListTrim(this.ToInner(key), start, stop, flags); Inner.ListTrim(ToInner(key), start, stop, flags);
} }
public bool LockExtend(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) public bool LockExtend(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockExtend(this.ToInner(key), value, expiry, flags); return Inner.LockExtend(ToInner(key), value, expiry, flags);
} }
public RedisValue LockQuery(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue LockQuery(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockQuery(this.ToInner(key), flags); return Inner.LockQuery(ToInner(key), flags);
} }
public bool LockRelease(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public bool LockRelease(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockRelease(this.ToInner(key), value, flags); return Inner.LockRelease(ToInner(key), value, flags);
} }
public bool LockTake(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) public bool LockTake(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockTake(this.ToInner(key), value, expiry, flags); return Inner.LockTake(ToInner(key), value, expiry, flags);
} }
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.Publish(this.ToInner(channel), message, flags); return Inner.Publish(ToInner(channel), message, flags);
} }
public RedisResult ScriptEvaluate(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) public RedisResult ScriptEvaluate(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return this.Inner.ScriptEvaluate(hash, this.ToInner(keys), values, flags); return Inner.ScriptEvaluate(hash, ToInner(keys), values, flags);
} }
public RedisResult ScriptEvaluate(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) public RedisResult ScriptEvaluate(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return this.Inner.ScriptEvaluate(script, this.ToInner(keys), values, flags); return Inner.ScriptEvaluate(script, ToInner(keys), values, flags);
} }
public RedisResult ScriptEvaluate(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) public RedisResult ScriptEvaluate(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return script.Evaluate(this.Inner, parameters, Prefix, flags); return script.Evaluate(Inner, parameters, Prefix, flags);
} }
public RedisResult ScriptEvaluate(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) public RedisResult ScriptEvaluate(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return script.Evaluate(this.Inner, parameters, Prefix, flags); return script.Evaluate(Inner, parameters, Prefix, flags);
} }
public long SetAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public long SetAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetAdd(this.ToInner(key), values, flags); return Inner.SetAdd(ToInner(key), values, flags);
} }
public bool SetAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public bool SetAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetAdd(this.ToInner(key), value, flags); return Inner.SetAdd(ToInner(key), value, flags);
} }
public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAndStore(operation, this.ToInner(destination), this.ToInner(keys), flags); return Inner.SetCombineAndStore(operation, ToInner(destination), ToInner(keys), flags);
} }
public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAndStore(operation, this.ToInner(destination), this.ToInner(first), this.ToInner(second), flags); return Inner.SetCombineAndStore(operation, ToInner(destination), ToInner(first), ToInner(second), flags);
} }
public RedisValue[] SetCombine(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public RedisValue[] SetCombine(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombine(operation, this.ToInner(keys), flags); return Inner.SetCombine(operation, ToInner(keys), flags);
} }
public RedisValue[] SetCombine(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public RedisValue[] SetCombine(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombine(operation, this.ToInner(first), this.ToInner(second), flags); return Inner.SetCombine(operation, ToInner(first), ToInner(second), flags);
} }
public bool SetContains(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public bool SetContains(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetContains(this.ToInner(key), value, flags); return Inner.SetContains(ToInner(key), value, flags);
} }
public long SetLength(RedisKey key, CommandFlags flags = CommandFlags.None) public long SetLength(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetLength(this.ToInner(key), flags); return Inner.SetLength(ToInner(key), flags);
} }
public RedisValue[] SetMembers(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue[] SetMembers(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetMembers(this.ToInner(key), flags); return Inner.SetMembers(ToInner(key), flags);
} }
public bool SetMove(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None) public bool SetMove(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetMove(this.ToInner(source), this.ToInner(destination), value, flags); return Inner.SetMove(ToInner(source), ToInner(destination), value, flags);
} }
public RedisValue SetPop(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue SetPop(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetPop(this.ToInner(key), flags); return Inner.SetPop(ToInner(key), flags);
} }
public RedisValue SetRandomMember(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue SetRandomMember(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRandomMember(this.ToInner(key), flags); return Inner.SetRandomMember(ToInner(key), flags);
} }
public RedisValue[] SetRandomMembers(RedisKey key, long count, CommandFlags flags = CommandFlags.None) public RedisValue[] SetRandomMembers(RedisKey key, long count, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRandomMembers(this.ToInner(key), count, flags); return Inner.SetRandomMembers(ToInner(key), count, flags);
} }
public long SetRemove(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public long SetRemove(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRemove(this.ToInner(key), values, flags); return Inner.SetRemove(ToInner(key), values, flags);
} }
public bool SetRemove(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public bool SetRemove(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRemove(this.ToInner(key), value, flags); return Inner.SetRemove(ToInner(key), value, flags);
} }
public long SortAndStore(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) public long SortAndStore(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortAndStore(this.ToInner(destination), this.ToInner(key), skip, take, order, sortType, this.SortByToInner(by), this.SortGetToInner(get), flags); return Inner.SortAndStore(ToInner(destination), ToInner(key), skip, take, order, sortType, SortByToInner(by), SortGetToInner(get), flags);
} }
public RedisValue[] Sort(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) public RedisValue[] Sort(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.Sort(this.ToInner(key), skip, take, order, sortType, this.SortByToInner(by), this.SortGetToInner(get), flags); return Inner.Sort(ToInner(key), skip, take, order, sortType, SortByToInner(by), SortGetToInner(get), flags);
} }
public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, CommandFlags flags = CommandFlags.None) public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetAdd(this.ToInner(key), values, flags); return Inner.SortedSetAdd(ToInner(key), values, flags);
} }
public bool SortedSetAdd(RedisKey key, RedisValue member, double score, CommandFlags flags = CommandFlags.None) public bool SortedSetAdd(RedisKey key, RedisValue member, double score, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetAdd(this.ToInner(key), member, score, flags); return Inner.SortedSetAdd(ToInner(key), member, score, flags);
} }
public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetCombineAndStore(operation, this.ToInner(destination), this.ToInner(keys), weights, aggregate, flags); return Inner.SortedSetCombineAndStore(operation, ToInner(destination), ToInner(keys), weights, aggregate, flags);
} }
public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetCombineAndStore(operation, this.ToInner(destination), this.ToInner(first), this.ToInner(second), aggregate, flags); return Inner.SortedSetCombineAndStore(operation, ToInner(destination), ToInner(first), ToInner(second), aggregate, flags);
} }
public double SortedSetDecrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) public double SortedSetDecrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetDecrement(this.ToInner(key), member, value, flags); return Inner.SortedSetDecrement(ToInner(key), member, value, flags);
} }
public double SortedSetIncrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) public double SortedSetIncrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetIncrement(this.ToInner(key), member, value, flags); return Inner.SortedSetIncrement(ToInner(key), member, value, flags);
} }
public long SortedSetLength(RedisKey key, double min = -1.0 / 0.0, double max = 1.0 / 0.0, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public long SortedSetLength(RedisKey key, double min = -1.0 / 0.0, double max = 1.0 / 0.0, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetLength(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetLength(ToInner(key), min, max, exclude, flags);
} }
public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetLengthByValue(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetLengthByValue(ToInner(key), min, max, exclude, flags);
} }
public RedisValue[] SortedSetRangeByRank(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public RedisValue[] SortedSetRangeByRank(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByRank(this.ToInner(key), start, stop, order, flags); return Inner.SortedSetRangeByRank(ToInner(key), start, stop, order, flags);
} }
public SortedSetEntry[] SortedSetRangeByRankWithScores(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public SortedSetEntry[] SortedSetRangeByRankWithScores(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByRankWithScores(this.ToInner(key), start, stop, order, flags); return Inner.SortedSetRangeByRankWithScores(ToInner(key), start, stop, order, flags);
} }
public RedisValue[] SortedSetRangeByScore(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public RedisValue[] SortedSetRangeByScore(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByScore(this.ToInner(key), start, stop, exclude, order, skip, take, flags); return Inner.SortedSetRangeByScore(ToInner(key), start, stop, exclude, order, skip, take, flags);
} }
public SortedSetEntry[] SortedSetRangeByScoreWithScores(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public SortedSetEntry[] SortedSetRangeByScoreWithScores(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByScoreWithScores(this.ToInner(key), start, stop, exclude, order, skip, take, flags); return Inner.SortedSetRangeByScoreWithScores(ToInner(key), start, stop, exclude, order, skip, take, flags);
} }
public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByValue(this.ToInner(key), min, max, exclude, skip, take, flags); return Inner.SortedSetRangeByValue(ToInner(key), min, max, exclude, skip, take, flags);
} }
public long? SortedSetRank(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public long? SortedSetRank(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRank(this.ToInner(key), member, order, flags); return Inner.SortedSetRank(ToInner(key), member, order, flags);
} }
public long SortedSetRemove(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) public long SortedSetRemove(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemove(this.ToInner(key), members, flags); return Inner.SortedSetRemove(ToInner(key), members, flags);
} }
public bool SortedSetRemove(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) public bool SortedSetRemove(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemove(this.ToInner(key), member, flags); return Inner.SortedSetRemove(ToInner(key), member, flags);
} }
public long SortedSetRemoveRangeByRank(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) public long SortedSetRemoveRangeByRank(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByRank(this.ToInner(key), start, stop, flags); return Inner.SortedSetRemoveRangeByRank(ToInner(key), start, stop, flags);
} }
public long SortedSetRemoveRangeByScore(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public long SortedSetRemoveRangeByScore(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByScore(this.ToInner(key), start, stop, exclude, flags); return Inner.SortedSetRemoveRangeByScore(ToInner(key), start, stop, exclude, flags);
} }
public long SortedSetRemoveRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public long SortedSetRemoveRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByValue(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetRemoveRangeByValue(ToInner(key), min, max, exclude, flags);
} }
public double? SortedSetScore(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) public double? SortedSetScore(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetScore(this.ToInner(key), member, flags); return Inner.SortedSetScore(ToInner(key), member, flags);
} }
public long StringAppend(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public long StringAppend(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringAppend(this.ToInner(key), value, flags); return Inner.StringAppend(ToInner(key), value, flags);
} }
public long StringBitCount(RedisKey key, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None) public long StringBitCount(RedisKey key, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitCount(this.ToInner(key), start, end, flags); return Inner.StringBitCount(ToInner(key), start, end, flags);
} }
public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitOperation(operation, this.ToInner(destination), this.ToInner(keys), flags); return Inner.StringBitOperation(operation, ToInner(destination), ToInner(keys), flags);
} }
public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None) public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitOperation(operation, this.ToInner(destination), this.ToInner(first), this.ToInnerOrDefault(second), flags); return Inner.StringBitOperation(operation, ToInner(destination), ToInner(first), ToInnerOrDefault(second), flags);
} }
public long StringBitPosition(RedisKey key, bool bit, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None) public long StringBitPosition(RedisKey key, bool bit, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitPosition(this.ToInner(key), bit, start, end, flags); return Inner.StringBitPosition(ToInner(key), bit, start, end, flags);
} }
public double StringDecrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None) public double StringDecrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringDecrement(this.ToInner(key), value, flags); return Inner.StringDecrement(ToInner(key), value, flags);
} }
public long StringDecrement(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None) public long StringDecrement(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringDecrement(this.ToInner(key), value, flags); return Inner.StringDecrement(ToInner(key), value, flags);
} }
public RedisValue[] StringGet(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public RedisValue[] StringGet(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGet(this.ToInner(keys), flags); return Inner.StringGet(ToInner(keys), flags);
} }
public RedisValue StringGet(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValue StringGet(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGet(this.ToInner(key), flags); return Inner.StringGet(ToInner(key), flags);
} }
public bool StringGetBit(RedisKey key, long offset, CommandFlags flags = CommandFlags.None) public bool StringGetBit(RedisKey key, long offset, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetBit(this.ToInner(key), offset, flags); return Inner.StringGetBit(ToInner(key), offset, flags);
} }
public RedisValue StringGetRange(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None) public RedisValue StringGetRange(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetRange(this.ToInner(key), start, end, flags); return Inner.StringGetRange(ToInner(key), start, end, flags);
} }
public RedisValue StringGetSet(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public RedisValue StringGetSet(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetSet(this.ToInner(key), value, flags); return Inner.StringGetSet(ToInner(key), value, flags);
} }
public RedisValueWithExpiry StringGetWithExpiry(RedisKey key, CommandFlags flags = CommandFlags.None) public RedisValueWithExpiry StringGetWithExpiry(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetWithExpiry(this.ToInner(key), flags); return Inner.StringGetWithExpiry(ToInner(key), flags);
} }
public double StringIncrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None) public double StringIncrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringIncrement(this.ToInner(key), value, flags); return Inner.StringIncrement(ToInner(key), value, flags);
} }
public long StringIncrement(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None) public long StringIncrement(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringIncrement(this.ToInner(key), value, flags); return Inner.StringIncrement(ToInner(key), value, flags);
} }
public long StringLength(RedisKey key, CommandFlags flags = CommandFlags.None) public long StringLength(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringLength(this.ToInner(key), flags); return Inner.StringLength(ToInner(key), flags);
} }
public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSet(this.ToInner(values), when, flags); return Inner.StringSet(ToInner(values), when, flags);
} }
public bool StringSet(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) public bool StringSet(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSet(this.ToInner(key), value, expiry, when, flags); return Inner.StringSet(ToInner(key), value, expiry, when, flags);
} }
public bool StringSetBit(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) public bool StringSetBit(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetBit(this.ToInner(key), offset, bit, flags); return Inner.StringSetBit(ToInner(key), offset, bit, flags);
} }
public RedisValue StringSetRange(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) public RedisValue StringSetRange(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetRange(this.ToInner(key), offset, value, flags); return Inner.StringSetRange(ToInner(key), offset, value, flags);
} }
public TimeSpan Ping(CommandFlags flags = CommandFlags.None) public TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.Ping(flags); return Inner.Ping(flags);
} }
...@@ -632,7 +628,7 @@ IEnumerable<HashEntry> IDatabase.HashScan(RedisKey key, RedisValue pattern, int ...@@ -632,7 +628,7 @@ IEnumerable<HashEntry> IDatabase.HashScan(RedisKey key, RedisValue pattern, int
} }
public IEnumerable<HashEntry> HashScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None) public IEnumerable<HashEntry> HashScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashScan(this.ToInner(key), pattern, pageSize, cursor, pageOffset, flags); return Inner.HashScan(ToInner(key), pattern, pageSize, cursor, pageOffset, flags);
} }
IEnumerable<RedisValue> IDatabase.SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) IEnumerable<RedisValue> IDatabase.SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
...@@ -641,7 +637,7 @@ IEnumerable<RedisValue> IDatabase.SetScan(RedisKey key, RedisValue pattern, int ...@@ -641,7 +637,7 @@ IEnumerable<RedisValue> IDatabase.SetScan(RedisKey key, RedisValue pattern, int
} }
public IEnumerable<RedisValue> SetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None) public IEnumerable<RedisValue> SetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetScan(this.ToInner(key), pattern, pageSize, cursor, pageOffset, flags); return Inner.SetScan(ToInner(key), pattern, pageSize, cursor, pageOffset, flags);
} }
IEnumerable<SortedSetEntry> IDatabase.SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) IEnumerable<SortedSetEntry> IDatabase.SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
...@@ -650,19 +646,19 @@ IEnumerable<SortedSetEntry> IDatabase.SortedSetScan(RedisKey key, RedisValue pat ...@@ -650,19 +646,19 @@ IEnumerable<SortedSetEntry> IDatabase.SortedSetScan(RedisKey key, RedisValue pat
} }
public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None) public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetScan(this.ToInner(key), pattern, pageSize, cursor, pageOffset, flags); return Inner.SortedSetScan(ToInner(key), pattern, pageSize, cursor, pageOffset, flags);
} }
#if DEBUG #if DEBUG
public string ClientGetName(CommandFlags flags = CommandFlags.None) public string ClientGetName(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ClientGetName(flags); return Inner.ClientGetName(flags);
} }
public void Quit(CommandFlags flags = CommandFlags.None) public void Quit(CommandFlags flags = CommandFlags.None)
{ {
this.Inner.Quit(flags); Inner.Quit(flags);
} }
#endif #endif
} }
......
...@@ -4,29 +4,28 @@ namespace StackExchange.Redis.KeyspaceIsolation ...@@ -4,29 +4,28 @@ namespace StackExchange.Redis.KeyspaceIsolation
{ {
internal sealed class TransactionWrapper : WrapperBase<ITransaction>, ITransaction internal sealed class TransactionWrapper : WrapperBase<ITransaction>, ITransaction
{ {
public TransactionWrapper(ITransaction inner, byte[] prefix) public TransactionWrapper(ITransaction inner, byte[] prefix) : base(inner, prefix)
: base(inner, prefix)
{ {
} }
public ConditionResult AddCondition(Condition condition) public ConditionResult AddCondition(Condition condition)
{ {
return this.Inner.AddCondition(condition == null ? null : condition.MapKeys(GetMapFunction())); return Inner.AddCondition(condition?.MapKeys(GetMapFunction()));
} }
public bool Execute(CommandFlags flags = CommandFlags.None) public bool Execute(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.Execute(flags); return Inner.Execute(flags);
} }
public Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None) public Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ExecuteAsync(flags); return Inner.ExecuteAsync(flags);
} }
public void Execute() public void Execute()
{ {
this.Inner.Execute(); Inner.Execute();
} }
} }
} }
...@@ -7,193 +7,181 @@ namespace StackExchange.Redis.KeyspaceIsolation ...@@ -7,193 +7,181 @@ namespace StackExchange.Redis.KeyspaceIsolation
{ {
internal class WrapperBase<TInner> : IDatabaseAsync where TInner : IDatabaseAsync internal class WrapperBase<TInner> : IDatabaseAsync where TInner : IDatabaseAsync
{ {
private readonly TInner _inner;
private readonly byte[] _keyPrefix;
internal WrapperBase(TInner inner, byte[] keyPrefix) internal WrapperBase(TInner inner, byte[] keyPrefix)
{ {
_inner = inner; Inner = inner;
_keyPrefix = keyPrefix; Prefix = keyPrefix;
} }
public ConnectionMultiplexer Multiplexer public ConnectionMultiplexer Multiplexer => Inner.Multiplexer;
{
get { return this.Inner.Multiplexer; }
}
internal TInner Inner internal TInner Inner { get; }
{
get { return _inner; }
}
internal byte[] Prefix internal byte[] Prefix { get; }
{
get { return _keyPrefix; }
}
public Task<RedisValue> DebugObjectAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> DebugObjectAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.DebugObjectAsync(this.ToInner(key), flags); return Inner.DebugObjectAsync(ToInner(key), flags);
} }
public Task<double> HashDecrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) public Task<double> HashDecrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDecrementAsync(this.ToInner(key), hashField, value, flags); return Inner.HashDecrementAsync(ToInner(key), hashField, value, flags);
} }
public Task<long> HashDecrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) public Task<long> HashDecrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDecrementAsync(this.ToInner(key), hashField, value, flags); return Inner.HashDecrementAsync(ToInner(key), hashField, value, flags);
} }
public Task<long> HashDeleteAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) public Task<long> HashDeleteAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDeleteAsync(this.ToInner(key), hashFields, flags); return Inner.HashDeleteAsync(ToInner(key), hashFields, flags);
} }
public Task<bool> HashDeleteAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public Task<bool> HashDeleteAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashDeleteAsync(this.ToInner(key), hashField, flags); return Inner.HashDeleteAsync(ToInner(key), hashField, flags);
} }
public Task<bool> HashExistsAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public Task<bool> HashExistsAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashExistsAsync(this.ToInner(key), hashField, flags); return Inner.HashExistsAsync(ToInner(key), hashField, flags);
} }
public Task<HashEntry[]> HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<HashEntry[]> HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGetAllAsync(this.ToInner(key), flags); return Inner.HashGetAllAsync(ToInner(key), flags);
} }
public Task<RedisValue[]> HashGetAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> HashGetAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGetAsync(this.ToInner(key), hashFields, flags); return Inner.HashGetAsync(ToInner(key), hashFields, flags);
} }
public Task<RedisValue> HashGetAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) public Task<RedisValue> HashGetAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashGetAsync(this.ToInner(key), hashField, flags); return Inner.HashGetAsync(ToInner(key), hashField, flags);
} }
public Task<double> HashIncrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) public Task<double> HashIncrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashIncrementAsync(this.ToInner(key), hashField, value, flags); return Inner.HashIncrementAsync(ToInner(key), hashField, value, flags);
} }
public Task<long> HashIncrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) public Task<long> HashIncrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashIncrementAsync(this.ToInner(key), hashField, value, flags); return Inner.HashIncrementAsync(ToInner(key), hashField, value, flags);
} }
public Task<RedisValue[]> HashKeysAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> HashKeysAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashKeysAsync(this.ToInner(key), flags); return Inner.HashKeysAsync(ToInner(key), flags);
} }
public Task<long> HashLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<long> HashLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashLengthAsync(this.ToInner(key), flags); return Inner.HashLengthAsync(ToInner(key), flags);
} }
public Task<bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashSetAsync(this.ToInner(key), hashField, value, when, flags); return Inner.HashSetAsync(ToInner(key), hashField, value, when, flags);
} }
public Task HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None) public Task HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashSetAsync(this.ToInner(key), hashFields, flags); return Inner.HashSetAsync(ToInner(key), hashFields, flags);
} }
public Task<RedisValue[]> HashValuesAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> HashValuesAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HashValuesAsync(this.ToInner(key), flags); return Inner.HashValuesAsync(ToInner(key), flags);
} }
public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogAddAsync(this.ToInner(key), values, flags); return Inner.HyperLogLogAddAsync(ToInner(key), values, flags);
} }
public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogAddAsync(this.ToInner(key), value, flags); return Inner.HyperLogLogAddAsync(ToInner(key), value, flags);
} }
public Task<long> HyperLogLogLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<long> HyperLogLogLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogLengthAsync(this.ToInner(key), flags); return Inner.HyperLogLogLengthAsync(ToInner(key), flags);
} }
public Task<long> HyperLogLogLengthAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<long> HyperLogLogLengthAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogLengthAsync(this.ToInner(keys), flags); return Inner.HyperLogLogLengthAsync(ToInner(keys), flags);
} }
public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogMergeAsync(this.ToInner(destination), this.ToInner(sourceKeys), flags); return Inner.HyperLogLogMergeAsync(ToInner(destination), ToInner(sourceKeys), flags);
} }
public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.HyperLogLogMergeAsync(this.ToInner(destination), this.ToInner(first), this.ToInner(second), flags); return Inner.HyperLogLogMergeAsync(ToInner(destination), ToInner(first), ToInner(second), flags);
} }
public Task<EndPoint> IdentifyEndpointAsync(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None) public Task<EndPoint> IdentifyEndpointAsync(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.IdentifyEndpointAsync(this.ToInner(key), flags); return Inner.IdentifyEndpointAsync(ToInner(key), flags);
} }
public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None) public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.IsConnected(this.ToInner(key), flags); return Inner.IsConnected(ToInner(key), flags);
} }
public Task<long> KeyDeleteAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<long> KeyDeleteAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDeleteAsync(this.ToInner(keys), flags); return Inner.KeyDeleteAsync(ToInner(keys), flags);
} }
public Task<bool> KeyDeleteAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<bool> KeyDeleteAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDeleteAsync(this.ToInner(key), flags); return Inner.KeyDeleteAsync(ToInner(key), flags);
} }
public Task<byte[]> KeyDumpAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<byte[]> KeyDumpAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyDumpAsync(this.ToInner(key), flags); return Inner.KeyDumpAsync(ToInner(key), flags);
} }
public Task<bool> KeyExistsAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<bool> KeyExistsAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExistsAsync(this.ToInner(key), flags); return Inner.KeyExistsAsync(ToInner(key), flags);
} }
public Task<bool> KeyExpireAsync(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None) public Task<bool> KeyExpireAsync(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExpireAsync(this.ToInner(key), expiry, flags); return Inner.KeyExpireAsync(ToInner(key), expiry, flags);
} }
public Task<bool> KeyExpireAsync(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None) public Task<bool> KeyExpireAsync(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyExpireAsync(this.ToInner(key), expiry, flags); return Inner.KeyExpireAsync(ToInner(key), expiry, flags);
} }
public Task KeyMigrateAsync(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None) public Task KeyMigrateAsync(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyMigrateAsync(this.ToInner(key), toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags); return Inner.KeyMigrateAsync(ToInner(key), toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags);
} }
public Task<bool> KeyMoveAsync(RedisKey key, int database, CommandFlags flags = CommandFlags.None) public Task<bool> KeyMoveAsync(RedisKey key, int database, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyMoveAsync(this.ToInner(key), database, flags); return Inner.KeyMoveAsync(ToInner(key), database, flags);
} }
public Task<bool> KeyPersistAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<bool> KeyPersistAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyPersistAsync(this.ToInner(key), flags); return Inner.KeyPersistAsync(ToInner(key), flags);
} }
public Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None) public Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None)
...@@ -203,466 +191,466 @@ public Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None) ...@@ -203,466 +191,466 @@ public Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None)
public Task<bool> KeyRenameAsync(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<bool> KeyRenameAsync(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyRenameAsync(this.ToInner(key), this.ToInner(newKey), when, flags); return Inner.KeyRenameAsync(ToInner(key), ToInner(newKey), when, flags);
} }
public Task KeyRestoreAsync(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None) public Task KeyRestoreAsync(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyRestoreAsync(this.ToInner(key), value, expiry, flags); return Inner.KeyRestoreAsync(ToInner(key), value, expiry, flags);
} }
public Task<TimeSpan?> KeyTimeToLiveAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<TimeSpan?> KeyTimeToLiveAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyTimeToLiveAsync(this.ToInner(key), flags); return Inner.KeyTimeToLiveAsync(ToInner(key), flags);
} }
public Task<RedisType> KeyTypeAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisType> KeyTypeAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.KeyTypeAsync(this.ToInner(key), flags); return Inner.KeyTypeAsync(ToInner(key), flags);
} }
public Task<RedisValue> ListGetByIndexAsync(RedisKey key, long index, CommandFlags flags = CommandFlags.None) public Task<RedisValue> ListGetByIndexAsync(RedisKey key, long index, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListGetByIndexAsync(this.ToInner(key), index, flags); return Inner.ListGetByIndexAsync(ToInner(key), index, flags);
} }
public Task<long> ListInsertAfterAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<long> ListInsertAfterAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListInsertAfterAsync(this.ToInner(key), pivot, value, flags); return Inner.ListInsertAfterAsync(ToInner(key), pivot, value, flags);
} }
public Task<long> ListInsertBeforeAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<long> ListInsertBeforeAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListInsertBeforeAsync(this.ToInner(key), pivot, value, flags); return Inner.ListInsertBeforeAsync(ToInner(key), pivot, value, flags);
} }
public Task<RedisValue> ListLeftPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> ListLeftPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPopAsync(this.ToInner(key), flags); return Inner.ListLeftPopAsync(ToInner(key), flags);
} }
public Task<long> ListLeftPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public Task<long> ListLeftPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPushAsync(this.ToInner(key), values, flags); return Inner.ListLeftPushAsync(ToInner(key), values, flags);
} }
public Task<long> ListLeftPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<long> ListLeftPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLeftPushAsync(this.ToInner(key), value, when, flags); return Inner.ListLeftPushAsync(ToInner(key), value, when, flags);
} }
public Task<long> ListLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<long> ListLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListLengthAsync(this.ToInner(key), flags); return Inner.ListLengthAsync(ToInner(key), flags);
} }
public Task<RedisValue[]> ListRangeAsync(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> ListRangeAsync(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRangeAsync(this.ToInner(key), start, stop, flags); return Inner.ListRangeAsync(ToInner(key), start, stop, flags);
} }
public Task<long> ListRemoveAsync(RedisKey key, RedisValue value, long count = 0, CommandFlags flags = CommandFlags.None) public Task<long> ListRemoveAsync(RedisKey key, RedisValue value, long count = 0, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRemoveAsync(this.ToInner(key), value, count, flags); return Inner.ListRemoveAsync(ToInner(key), value, count, flags);
} }
public Task<RedisValue> ListRightPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> ListRightPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPopAsync(this.ToInner(key), flags); return Inner.ListRightPopAsync(ToInner(key), flags);
} }
public Task<RedisValue> ListRightPopLeftPushAsync(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None) public Task<RedisValue> ListRightPopLeftPushAsync(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPopLeftPushAsync(this.ToInner(source), this.ToInner(destination), flags); return Inner.ListRightPopLeftPushAsync(ToInner(source), ToInner(destination), flags);
} }
public Task<long> ListRightPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public Task<long> ListRightPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPushAsync(this.ToInner(key), values, flags); return Inner.ListRightPushAsync(ToInner(key), values, flags);
} }
public Task<long> ListRightPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<long> ListRightPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListRightPushAsync(this.ToInner(key), value, when, flags); return Inner.ListRightPushAsync(ToInner(key), value, when, flags);
} }
public Task ListSetByIndexAsync(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None) public Task ListSetByIndexAsync(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListSetByIndexAsync(this.ToInner(key), index, value, flags); return Inner.ListSetByIndexAsync(ToInner(key), index, value, flags);
} }
public Task ListTrimAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) public Task ListTrimAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ListTrimAsync(this.ToInner(key), start, stop, flags); return Inner.ListTrimAsync(ToInner(key), start, stop, flags);
} }
public Task<bool> LockExtendAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) public Task<bool> LockExtendAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockExtendAsync(this.ToInner(key), value, expiry, flags); return Inner.LockExtendAsync(ToInner(key), value, expiry, flags);
} }
public Task<RedisValue> LockQueryAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> LockQueryAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockQueryAsync(this.ToInner(key), flags); return Inner.LockQueryAsync(ToInner(key), flags);
} }
public Task<bool> LockReleaseAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> LockReleaseAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockReleaseAsync(this.ToInner(key), value, flags); return Inner.LockReleaseAsync(ToInner(key), value, flags);
} }
public Task<bool> LockTakeAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) public Task<bool> LockTakeAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.LockTakeAsync(this.ToInner(key), value, expiry, flags); return Inner.LockTakeAsync(ToInner(key), value, expiry, flags);
} }
public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.PublishAsync(this.ToInner(channel), message, flags); return Inner.PublishAsync(ToInner(channel), message, flags);
} }
public Task<RedisResult> ScriptEvaluateAsync(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) public Task<RedisResult> ScriptEvaluateAsync(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return this.Inner.ScriptEvaluateAsync(hash, this.ToInner(keys), values, flags); return Inner.ScriptEvaluateAsync(hash, ToInner(keys), values, flags);
} }
public Task<RedisResult> ScriptEvaluateAsync(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) public Task<RedisResult> ScriptEvaluateAsync(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None)
{ {
// TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those?
return this.Inner.ScriptEvaluateAsync(script, this.ToInner(keys), values, flags); return Inner.ScriptEvaluateAsync(script, ToInner(keys), values, flags);
} }
public Task<RedisResult> ScriptEvaluateAsync(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) public Task<RedisResult> ScriptEvaluateAsync(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ScriptEvaluateAsync(script, parameters, flags); return Inner.ScriptEvaluateAsync(script, parameters, flags);
} }
public Task<RedisResult> ScriptEvaluateAsync(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) public Task<RedisResult> ScriptEvaluateAsync(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ScriptEvaluateAsync(script, parameters, flags); return Inner.ScriptEvaluateAsync(script, parameters, flags);
} }
public Task<long> SetAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public Task<long> SetAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetAddAsync(this.ToInner(key), values, flags); return Inner.SetAddAsync(ToInner(key), values, flags);
} }
public Task<bool> SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetAddAsync(this.ToInner(key), value, flags); return Inner.SetAddAsync(ToInner(key), value, flags);
} }
public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAndStoreAsync(operation, this.ToInner(destination), this.ToInner(keys), flags); return Inner.SetCombineAndStoreAsync(operation, ToInner(destination), ToInner(keys), flags);
} }
public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAndStoreAsync(operation, this.ToInner(destination), this.ToInner(first), this.ToInner(second), flags); return Inner.SetCombineAndStoreAsync(operation, ToInner(destination), ToInner(first), ToInner(second), flags);
} }
public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAsync(operation, this.ToInner(keys), flags); return Inner.SetCombineAsync(operation, ToInner(keys), flags);
} }
public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetCombineAsync(operation, this.ToInner(first), this.ToInner(second), flags); return Inner.SetCombineAsync(operation, ToInner(first), ToInner(second), flags);
} }
public Task<bool> SetContainsAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> SetContainsAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetContainsAsync(this.ToInner(key), value, flags); return Inner.SetContainsAsync(ToInner(key), value, flags);
} }
public Task<long> SetLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<long> SetLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetLengthAsync(this.ToInner(key), flags); return Inner.SetLengthAsync(ToInner(key), flags);
} }
public Task<RedisValue[]> SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetMembersAsync(this.ToInner(key), flags); return Inner.SetMembersAsync(ToInner(key), flags);
} }
public Task<bool> SetMoveAsync(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> SetMoveAsync(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetMoveAsync(this.ToInner(source), this.ToInner(destination), value, flags); return Inner.SetMoveAsync(ToInner(source), ToInner(destination), value, flags);
} }
public Task<RedisValue> SetPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> SetPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetPopAsync(this.ToInner(key), flags); return Inner.SetPopAsync(ToInner(key), flags);
} }
public Task<RedisValue> SetRandomMemberAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> SetRandomMemberAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRandomMemberAsync(this.ToInner(key), flags); return Inner.SetRandomMemberAsync(ToInner(key), flags);
} }
public Task<RedisValue[]> SetRandomMembersAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SetRandomMembersAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRandomMembersAsync(this.ToInner(key), count, flags); return Inner.SetRandomMembersAsync(ToInner(key), count, flags);
} }
public Task<long> SetRemoveAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) public Task<long> SetRemoveAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRemoveAsync(this.ToInner(key), values, flags); return Inner.SetRemoveAsync(ToInner(key), values, flags);
} }
public Task<bool> SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<bool> SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SetRemoveAsync(this.ToInner(key), value, flags); return Inner.SetRemoveAsync(ToInner(key), value, flags);
} }
public Task<long> SortAndStoreAsync(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) public Task<long> SortAndStoreAsync(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortAndStoreAsync(this.ToInner(destination), this.ToInner(key), skip, take, order, sortType, this.SortByToInner(by), this.SortGetToInner(get), flags); return Inner.SortAndStoreAsync(ToInner(destination), ToInner(key), skip, take, order, sortType, SortByToInner(by), SortGetToInner(get), flags);
} }
public Task<RedisValue[]> SortAsync(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SortAsync(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortAsync(this.ToInner(key), skip, take, order, sortType, this.SortByToInner(by), this.SortGetToInner(get), flags); return Inner.SortAsync(ToInner(key), skip, take, order, sortType, SortByToInner(by), SortGetToInner(get), flags);
} }
public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetAddAsync(this.ToInner(key), values, flags); return Inner.SortedSetAddAsync(ToInner(key), values, flags);
} }
public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags = CommandFlags.None) public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetAddAsync(this.ToInner(key), member, score, flags); return Inner.SortedSetAddAsync(ToInner(key), member, score, flags);
} }
public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetCombineAndStoreAsync(operation, this.ToInner(destination), this.ToInner(keys), weights, aggregate, flags); return Inner.SortedSetCombineAndStoreAsync(operation, ToInner(destination), ToInner(keys), weights, aggregate, flags);
} }
public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetCombineAndStoreAsync(operation, this.ToInner(destination), this.ToInner(first), this.ToInner(second), aggregate, flags); return Inner.SortedSetCombineAndStoreAsync(operation, ToInner(destination), ToInner(first), ToInner(second), aggregate, flags);
} }
public Task<double> SortedSetDecrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) public Task<double> SortedSetDecrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetDecrementAsync(this.ToInner(key), member, value, flags); return Inner.SortedSetDecrementAsync(ToInner(key), member, value, flags);
} }
public Task<double> SortedSetIncrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) public Task<double> SortedSetIncrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetIncrementAsync(this.ToInner(key), member, value, flags); return Inner.SortedSetIncrementAsync(ToInner(key), member, value, flags);
} }
public Task<long> SortedSetLengthAsync(RedisKey key, double min = -1.0 / 0.0, double max = 1.0 / 0.0, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetLengthAsync(RedisKey key, double min = -1.0 / 0.0, double max = 1.0 / 0.0, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetLengthAsync(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetLengthAsync(ToInner(key), min, max, exclude, flags);
} }
public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetLengthByValueAsync(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetLengthByValueAsync(ToInner(key), min, max, exclude, flags);
} }
public Task<RedisValue[]> SortedSetRangeByRankAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SortedSetRangeByRankAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByRankAsync(this.ToInner(key), start, stop, order, flags); return Inner.SortedSetRangeByRankAsync(ToInner(key), start, stop, order, flags);
} }
public Task<SortedSetEntry[]> SortedSetRangeByRankWithScoresAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public Task<SortedSetEntry[]> SortedSetRangeByRankWithScoresAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByRankWithScoresAsync(this.ToInner(key), start, stop, order, flags); return Inner.SortedSetRangeByRankWithScoresAsync(ToInner(key), start, stop, order, flags);
} }
public Task<RedisValue[]> SortedSetRangeByScoreAsync(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SortedSetRangeByScoreAsync(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByScoreAsync(this.ToInner(key), start, stop, exclude, order, skip, take, flags); return Inner.SortedSetRangeByScoreAsync(ToInner(key), start, stop, exclude, order, skip, take, flags);
} }
public Task<SortedSetEntry[]> SortedSetRangeByScoreWithScoresAsync(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public Task<SortedSetEntry[]> SortedSetRangeByScoreWithScoresAsync(RedisKey key, double start = -1.0 / 0.0, double stop = 1.0 / 0.0, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByScoreWithScoresAsync(this.ToInner(key), start, stop, exclude, order, skip, take, flags); return Inner.SortedSetRangeByScoreWithScoresAsync(ToInner(key), start, stop, exclude, order, skip, take, flags);
} }
public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRangeByValueAsync(this.ToInner(key), min, max, exclude, skip, take, flags); return Inner.SortedSetRangeByValueAsync(ToInner(key), min, max, exclude, skip, take, flags);
} }
public Task<long?> SortedSetRankAsync(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) public Task<long?> SortedSetRankAsync(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRankAsync(this.ToInner(key), member, order, flags); return Inner.SortedSetRankAsync(ToInner(key), member, order, flags);
} }
public Task<long> SortedSetRemoveAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetRemoveAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveAsync(this.ToInner(key), members, flags); return Inner.SortedSetRemoveAsync(ToInner(key), members, flags);
} }
public Task<bool> SortedSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) public Task<bool> SortedSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveAsync(this.ToInner(key), member, flags); return Inner.SortedSetRemoveAsync(ToInner(key), member, flags);
} }
public Task<long> SortedSetRemoveRangeByRankAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetRemoveRangeByRankAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByRankAsync(this.ToInner(key), start, stop, flags); return Inner.SortedSetRemoveRangeByRankAsync(ToInner(key), start, stop, flags);
} }
public Task<long> SortedSetRemoveRangeByScoreAsync(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetRemoveRangeByScoreAsync(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByScoreAsync(this.ToInner(key), start, stop, exclude, flags); return Inner.SortedSetRemoveRangeByScoreAsync(ToInner(key), start, stop, exclude, flags);
} }
public Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) public Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetRemoveRangeByValueAsync(this.ToInner(key), min, max, exclude, flags); return Inner.SortedSetRemoveRangeByValueAsync(ToInner(key), min, max, exclude, flags);
} }
public Task<double?> SortedSetScoreAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) public Task<double?> SortedSetScoreAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.SortedSetScoreAsync(this.ToInner(key), member, flags); return Inner.SortedSetScoreAsync(ToInner(key), member, flags);
} }
public Task<long> StringAppendAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<long> StringAppendAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringAppendAsync(this.ToInner(key), value, flags); return Inner.StringAppendAsync(ToInner(key), value, flags);
} }
public Task<long> StringBitCountAsync(RedisKey key, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None) public Task<long> StringBitCountAsync(RedisKey key, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitCountAsync(this.ToInner(key), start, end, flags); return Inner.StringBitCountAsync(ToInner(key), start, end, flags);
} }
public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitOperationAsync(operation, this.ToInner(destination), this.ToInner(keys), flags); return Inner.StringBitOperationAsync(operation, ToInner(destination), ToInner(keys), flags);
} }
public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None) public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitOperationAsync(operation, this.ToInner(destination), this.ToInner(first), this.ToInnerOrDefault(second), flags); return Inner.StringBitOperationAsync(operation, ToInner(destination), ToInner(first), ToInnerOrDefault(second), flags);
} }
public Task<long> StringBitPositionAsync(RedisKey key, bool bit, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None) public Task<long> StringBitPositionAsync(RedisKey key, bool bit, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringBitPositionAsync(this.ToInner(key), bit, start, end, flags); return Inner.StringBitPositionAsync(ToInner(key), bit, start, end, flags);
} }
public Task<double> StringDecrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None) public Task<double> StringDecrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringDecrementAsync(this.ToInner(key), value, flags); return Inner.StringDecrementAsync(ToInner(key), value, flags);
} }
public Task<long> StringDecrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None) public Task<long> StringDecrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringDecrementAsync(this.ToInner(key), value, flags); return Inner.StringDecrementAsync(ToInner(key), value, flags);
} }
public Task<RedisValue[]> StringGetAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) public Task<RedisValue[]> StringGetAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetAsync(this.ToInner(keys), flags); return Inner.StringGetAsync(ToInner(keys), flags);
} }
public Task<RedisValue> StringGetAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValue> StringGetAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetAsync(this.ToInner(key), flags); return Inner.StringGetAsync(ToInner(key), flags);
} }
public Task<bool> StringGetBitAsync(RedisKey key, long offset, CommandFlags flags = CommandFlags.None) public Task<bool> StringGetBitAsync(RedisKey key, long offset, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetBitAsync(this.ToInner(key), offset, flags); return Inner.StringGetBitAsync(ToInner(key), offset, flags);
} }
public Task<RedisValue> StringGetRangeAsync(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None) public Task<RedisValue> StringGetRangeAsync(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetRangeAsync(this.ToInner(key), start, end, flags); return Inner.StringGetRangeAsync(ToInner(key), start, end, flags);
} }
public Task<RedisValue> StringGetSetAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<RedisValue> StringGetSetAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetSetAsync(this.ToInner(key), value, flags); return Inner.StringGetSetAsync(ToInner(key), value, flags);
} }
public Task<RedisValueWithExpiry> StringGetWithExpiryAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<RedisValueWithExpiry> StringGetWithExpiryAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringGetWithExpiryAsync(this.ToInner(key), flags); return Inner.StringGetWithExpiryAsync(ToInner(key), flags);
} }
public Task<double> StringIncrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None) public Task<double> StringIncrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringIncrementAsync(this.ToInner(key), value, flags); return Inner.StringIncrementAsync(ToInner(key), value, flags);
} }
public Task<long> StringIncrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None) public Task<long> StringIncrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringIncrementAsync(this.ToInner(key), value, flags); return Inner.StringIncrementAsync(ToInner(key), value, flags);
} }
public Task<long> StringLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) public Task<long> StringLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringLengthAsync(this.ToInner(key), flags); return Inner.StringLengthAsync(ToInner(key), flags);
} }
public Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetAsync(this.ToInner(values), when, flags); return Inner.StringSetAsync(ToInner(values), when, flags);
} }
public Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) public Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetAsync(this.ToInner(key), value, expiry, when, flags); return Inner.StringSetAsync(ToInner(key), value, expiry, when, flags);
} }
public Task<bool> StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) public Task<bool> StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetBitAsync(this.ToInner(key), offset, bit, flags); return Inner.StringSetBitAsync(ToInner(key), offset, bit, flags);
} }
public Task<RedisValue> StringSetRangeAsync(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) public Task<RedisValue> StringSetRangeAsync(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.StringSetRangeAsync(this.ToInner(key), offset, value, flags); return Inner.StringSetRangeAsync(ToInner(key), offset, value, flags);
} }
public Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None) public Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.PingAsync(flags); return Inner.PingAsync(flags);
} }
public bool TryWait(Task task) public bool TryWait(Task task)
{ {
return this.Inner.TryWait(task); return Inner.TryWait(task);
} }
public TResult Wait<TResult>(Task<TResult> task) public TResult Wait<TResult>(Task<TResult> task)
{ {
return this.Inner.Wait(task); return Inner.Wait(task);
} }
public void Wait(Task task) public void Wait(Task task)
{ {
this.Inner.Wait(task); Inner.Wait(task);
} }
public void WaitAll(params Task[] tasks) public void WaitAll(params Task[] tasks)
{ {
this.Inner.WaitAll(tasks); Inner.WaitAll(tasks);
} }
#if DEBUG #if DEBUG
public Task<string> ClientGetNameAsync(CommandFlags flags = CommandFlags.None) public Task<string> ClientGetNameAsync(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ClientGetNameAsync(flags); return Inner.ClientGetNameAsync(flags);
} }
#endif #endif
protected internal RedisKey ToInner(RedisKey outer) protected internal RedisKey ToInner(RedisKey outer)
{ {
return RedisKey.WithPrefix(_keyPrefix, outer); return RedisKey.WithPrefix(Prefix, outer);
} }
protected RedisKey ToInnerOrDefault(RedisKey outer) protected RedisKey ToInnerOrDefault(RedisKey outer)
...@@ -673,7 +661,7 @@ protected RedisKey ToInnerOrDefault(RedisKey outer) ...@@ -673,7 +661,7 @@ protected RedisKey ToInnerOrDefault(RedisKey outer)
} }
else else
{ {
return this.ToInner(outer); return ToInner(outer);
} }
} }
...@@ -689,7 +677,7 @@ protected RedisKey[] ToInner(RedisKey[] outer) ...@@ -689,7 +677,7 @@ protected RedisKey[] ToInner(RedisKey[] outer)
for (int i = 0; i < outer.Length; ++i) for (int i = 0; i < outer.Length; ++i)
{ {
inner[i] = this.ToInner(outer[i]); inner[i] = ToInner(outer[i]);
} }
return inner; return inner;
...@@ -698,7 +686,7 @@ protected RedisKey[] ToInner(RedisKey[] outer) ...@@ -698,7 +686,7 @@ protected RedisKey[] ToInner(RedisKey[] outer)
protected KeyValuePair<RedisKey, RedisValue> ToInner(KeyValuePair<RedisKey, RedisValue> outer) protected KeyValuePair<RedisKey, RedisValue> ToInner(KeyValuePair<RedisKey, RedisValue> outer)
{ {
return new KeyValuePair<RedisKey, RedisValue>(this.ToInner(outer.Key), outer.Value); return new KeyValuePair<RedisKey, RedisValue>(ToInner(outer.Key), outer.Value);
} }
protected KeyValuePair<RedisKey, RedisValue>[] ToInner(KeyValuePair<RedisKey, RedisValue>[] outer) protected KeyValuePair<RedisKey, RedisValue>[] ToInner(KeyValuePair<RedisKey, RedisValue>[] outer)
...@@ -713,7 +701,7 @@ protected RedisKey[] ToInner(RedisKey[] outer) ...@@ -713,7 +701,7 @@ protected RedisKey[] ToInner(RedisKey[] outer)
for (int i = 0; i < outer.Length; ++i) for (int i = 0; i < outer.Length; ++i)
{ {
inner[i] = this.ToInner(outer[i]); inner[i] = ToInner(outer[i]);
} }
return inner; return inner;
...@@ -722,7 +710,7 @@ protected RedisKey[] ToInner(RedisKey[] outer) ...@@ -722,7 +710,7 @@ protected RedisKey[] ToInner(RedisKey[] outer)
protected RedisValue ToInner(RedisValue outer) protected RedisValue ToInner(RedisValue outer)
{ {
return RedisKey.ConcatenateBytes(this.Prefix, null, (byte[])outer); return RedisKey.ConcatenateBytes(Prefix, null, (byte[])outer);
} }
protected RedisValue SortByToInner(RedisValue outer) protected RedisValue SortByToInner(RedisValue outer)
...@@ -733,7 +721,7 @@ protected RedisValue SortByToInner(RedisValue outer) ...@@ -733,7 +721,7 @@ protected RedisValue SortByToInner(RedisValue outer)
} }
else else
{ {
return this.ToInner(outer); return ToInner(outer);
} }
} }
...@@ -745,7 +733,7 @@ protected RedisValue SortGetToInner(RedisValue outer) ...@@ -745,7 +733,7 @@ protected RedisValue SortGetToInner(RedisValue outer)
} }
else else
{ {
return this.ToInner(outer); return ToInner(outer);
} }
} }
...@@ -761,7 +749,7 @@ protected RedisValue[] SortGetToInner(RedisValue[] outer) ...@@ -761,7 +749,7 @@ protected RedisValue[] SortGetToInner(RedisValue[] outer)
for (int i = 0; i < outer.Length; ++i) for (int i = 0; i < outer.Length; ++i)
{ {
inner[i] = this.SortGetToInner(outer[i]); inner[i] = SortGetToInner(outer[i]);
} }
return inner; return inner;
...@@ -770,14 +758,14 @@ protected RedisValue[] SortGetToInner(RedisValue[] outer) ...@@ -770,14 +758,14 @@ protected RedisValue[] SortGetToInner(RedisValue[] outer)
protected RedisChannel ToInner(RedisChannel outer) protected RedisChannel ToInner(RedisChannel outer)
{ {
return RedisKey.ConcatenateBytes(this.Prefix, null, (byte[])outer); return RedisKey.ConcatenateBytes(Prefix, null, (byte[])outer);
} }
private Func<RedisKey, RedisKey> mapFunction; private Func<RedisKey, RedisKey> mapFunction;
protected Func<RedisKey, RedisKey> GetMapFunction() protected Func<RedisKey, RedisKey> GetMapFunction()
{ {
// create as a delegate when first required, then re-use // create as a delegate when first required, then re-use
return mapFunction ?? (mapFunction = new Func<RedisKey, RedisKey>(this.ToInner)); return mapFunction ?? (mapFunction = new Func<RedisKey, RedisKey>(ToInner));
} }
} }
} }
...@@ -37,7 +37,7 @@ public sealed class LuaScript ...@@ -37,7 +37,7 @@ public sealed class LuaScript
// Arguments are in the order they have to passed to the script in // Arguments are in the order they have to passed to the script in
internal string[] Arguments { get; private set; } internal string[] Arguments { get; private set; }
bool HasArguments { get { return Arguments != null && Arguments.Length > 0; } } bool HasArguments => Arguments != null && Arguments.Length > 0;
Hashtable ParameterMappers; Hashtable ParameterMappers;
...@@ -106,7 +106,7 @@ internal void ExtractParameters(object ps, RedisKey? keyPrefix, out RedisKey[] k ...@@ -106,7 +106,7 @@ internal void ExtractParameters(object ps, RedisKey? keyPrefix, out RedisKey[] k
{ {
if (HasArguments) if (HasArguments)
{ {
if (ps == null) throw new ArgumentNullException("ps", "Script requires parameters"); if (ps == null) throw new ArgumentNullException(nameof(ps), "Script requires parameters");
var psType = ps.GetType(); var psType = ps.GetType();
var mapper = (Func<object, RedisKey?, ScriptParameterMapper.ScriptParameters>)ParameterMappers[psType]; var mapper = (Func<object, RedisKey?, ScriptParameterMapper.ScriptParameters>)ParameterMappers[psType];
...@@ -179,7 +179,7 @@ public LoadedLuaScript Load(IServer server, CommandFlags flags = CommandFlags.No ...@@ -179,7 +179,7 @@ public LoadedLuaScript Load(IServer server, CommandFlags flags = CommandFlags.No
{ {
if (flags.HasFlag(CommandFlags.FireAndForget)) if (flags.HasFlag(CommandFlags.FireAndForget))
{ {
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget"); throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
} }
var hash = server.ScriptLoad(ExecutableScript, flags); var hash = server.ScriptLoad(ExecutableScript, flags);
...@@ -197,7 +197,7 @@ public async Task<LoadedLuaScript> LoadAsync(IServer server, CommandFlags flags ...@@ -197,7 +197,7 @@ public async Task<LoadedLuaScript> LoadAsync(IServer server, CommandFlags flags
{ {
if (flags.HasFlag(CommandFlags.FireAndForget)) if (flags.HasFlag(CommandFlags.FireAndForget))
{ {
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget"); throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
} }
var hash = await server.ScriptLoadAsync(ExecutableScript, flags); var hash = await server.ScriptLoadAsync(ExecutableScript, flags);
...@@ -228,12 +228,12 @@ public sealed class LoadedLuaScript ...@@ -228,12 +228,12 @@ public sealed class LoadedLuaScript
/// <summary> /// <summary>
/// The original script that was used to create this LoadedLuaScript. /// The original script that was used to create this LoadedLuaScript.
/// </summary> /// </summary>
public string OriginalScript { get { return Original.OriginalScript; } } public string OriginalScript => Original.OriginalScript;
/// <summary> /// <summary>
/// The script that will actually be sent to Redis for execution. /// The script that will actually be sent to Redis for execution.
/// </summary> /// </summary>
public string ExecutableScript { get { return Original.ExecutableScript; } } public string ExecutableScript => Original.ExecutableScript;
/// <summary> /// <summary>
/// The SHA1 hash of ExecutableScript. /// The SHA1 hash of ExecutableScript.
......
...@@ -38,7 +38,7 @@ public sealed class RedisConnectionException : RedisException ...@@ -38,7 +38,7 @@ public sealed class RedisConnectionException : RedisException
#if FEATURE_SERIALIZATION #if FEATURE_SERIALIZATION
private RedisConnectionException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) private RedisConnectionException(SerializationInfo info, StreamingContext ctx) : base(info, ctx)
{ {
this.FailureType = (ConnectionFailureType)info.GetInt32("failureType"); FailureType = (ConnectionFailureType)info.GetInt32("failureType");
} }
/// <summary> /// <summary>
/// Serialization implementation; not intended for general usage /// Serialization implementation; not intended for general usage
...@@ -46,23 +46,23 @@ private RedisConnectionException(SerializationInfo info, StreamingContext ctx) : ...@@ -46,23 +46,23 @@ private RedisConnectionException(SerializationInfo info, StreamingContext ctx) :
public override void GetObjectData(SerializationInfo info, StreamingContext context) public override void GetObjectData(SerializationInfo info, StreamingContext context)
{ {
base.GetObjectData(info, context); base.GetObjectData(info, context);
info.AddValue("failureType", (int)this.FailureType); info.AddValue("failureType", (int)FailureType);
} }
#endif #endif
internal RedisConnectionException(ConnectionFailureType failureType, string message) : base(message) internal RedisConnectionException(ConnectionFailureType failureType, string message) : base(message)
{ {
this.FailureType = failureType; FailureType = failureType;
} }
internal RedisConnectionException(ConnectionFailureType failureType, string message, Exception innerException) : base(message, innerException) internal RedisConnectionException(ConnectionFailureType failureType, string message, Exception innerException) : base(message, innerException)
{ {
this.FailureType = failureType; FailureType = failureType;
} }
/// <summary> /// <summary>
/// The type of connection failure /// The type of connection failure
/// </summary> /// </summary>
public ConnectionFailureType FailureType { get; private set; } public ConnectionFailureType FailureType { get; }
} }
/// <summary> /// <summary>
...@@ -111,15 +111,10 @@ private LoggingMessage(TextWriter log, Message tail) : base(tail.Db, tail.Flags, ...@@ -111,15 +111,10 @@ private LoggingMessage(TextWriter log, Message tail) : base(tail.Db, tail.Flags,
{ {
this.log = log; this.log = log;
this.tail = tail; this.tail = tail;
this.FlagsRaw = tail.FlagsRaw; FlagsRaw = tail.FlagsRaw;
}
public override string CommandAndKey
{
get
{
return tail.CommandAndKey;
}
} }
public override string CommandAndKey => tail.CommandAndKey;
public override void AppendStormLog(StringBuilder sb) public override void AppendStormLog(StringBuilder sb)
{ {
tail.AppendStormLog(sb); tail.AppendStormLog(sb);
...@@ -138,7 +133,7 @@ internal override void WriteImpl(PhysicalConnection physical) ...@@ -138,7 +133,7 @@ internal override void WriteImpl(PhysicalConnection physical)
tail.WriteImpl(physical); tail.WriteImpl(physical);
} }
public TextWriter Log { get { return log; } } public TextWriter Log => log;
} }
abstract class Message : ICompletable abstract class Message : ICompletable
...@@ -173,7 +168,7 @@ abstract class Message : ICompletable ...@@ -173,7 +168,7 @@ abstract class Message : ICompletable
protected Message(int db, CommandFlags flags, RedisCommand command) protected Message(int db, CommandFlags flags, RedisCommand command)
{ {
bool dbNeeded = Message.RequiresDatabase(command); bool dbNeeded = RequiresDatabase(command);
if (db < 0) if (db < 0)
{ {
if (dbNeeded) if (dbNeeded)
...@@ -190,7 +185,7 @@ protected Message(int db, CommandFlags flags, RedisCommand command) ...@@ -190,7 +185,7 @@ protected Message(int db, CommandFlags flags, RedisCommand command)
} }
bool masterOnly = IsMasterOnly(command); bool masterOnly = IsMasterOnly(command);
this.Db = db; Db = db;
this.command = command; this.command = command;
this.flags = flags & UserSelectableFlags; this.flags = flags & UserSelectableFlags;
if (masterOnly) SetMasterOnly(); if (masterOnly) SetMasterOnly();
...@@ -201,17 +196,17 @@ protected Message(int db, CommandFlags flags, RedisCommand command) ...@@ -201,17 +196,17 @@ protected Message(int db, CommandFlags flags, RedisCommand command)
internal void SetMasterOnly() internal void SetMasterOnly()
{ {
switch (GetMasterSlaveFlags(this.flags)) switch (GetMasterSlaveFlags(flags))
{ {
case CommandFlags.DemandSlave: case CommandFlags.DemandSlave:
throw ExceptionFactory.MasterOnly(false, this.command, null, null); throw ExceptionFactory.MasterOnly(false, command, null, null);
case CommandFlags.DemandMaster: case CommandFlags.DemandMaster:
// already fine as-is // already fine as-is
break; break;
case CommandFlags.PreferMaster: case CommandFlags.PreferMaster:
case CommandFlags.PreferSlave: case CommandFlags.PreferSlave:
default: // we will run this on the master, then default: // we will run this on the master, then
this.flags = SetMasterSlaveFlags(this.flags, CommandFlags.DemandMaster); flags = SetMasterSlaveFlags(flags, CommandFlags.DemandMaster);
break; break;
} }
} }
...@@ -237,11 +232,11 @@ internal void PrepareToResend(ServerEndPoint resendTo, bool isMoved) ...@@ -237,11 +232,11 @@ internal void PrepareToResend(ServerEndPoint resendTo, bool isMoved)
performance.SetMessage(this); performance.SetMessage(this);
} }
public RedisCommand Command { get { return command; } } public RedisCommand Command => command;
public virtual string CommandAndKey { get { return Command.ToString(); } } public virtual string CommandAndKey => Command.ToString();
public CommandFlags Flags { get { return flags; } } public CommandFlags Flags => flags;
/// <summary> /// <summary>
/// Things with the potential to cause harm, or to reveal configuration information /// Things with the potential to cause harm, or to reveal configuration information
...@@ -275,36 +270,22 @@ public bool IsAdmin ...@@ -275,36 +270,22 @@ public bool IsAdmin
} }
} }
public bool IsAsking public bool IsAsking => (flags & AskingFlag) != 0;
{
get { return (flags & AskingFlag) != 0; } internal bool IsScriptUnavailable => (flags & ScriptUnavailableFlag) != 0;
}
internal bool IsScriptUnavailable
{
get { return (flags & ScriptUnavailableFlag) != 0; }
}
internal void SetScriptUnavailable() internal void SetScriptUnavailable()
{ {
flags |= ScriptUnavailableFlag; flags |= ScriptUnavailableFlag;
} }
public bool IsFireAndForget public bool IsFireAndForget => (flags & CommandFlags.FireAndForget) != 0;
{
get { return (flags & CommandFlags.FireAndForget) != 0; }
}
public bool IsHighPriority public bool IsHighPriority => (flags & CommandFlags.HighPriority) != 0;
{
get { return (flags & CommandFlags.HighPriority) != 0; }
}
public bool IsInternalCall public bool IsInternalCall => (flags & InternalCallFlag) != 0;
{
get { return (flags & InternalCallFlag) != 0; }
}
public ResultBox ResultBox { get { return resultBox; } } public ResultBox ResultBox => resultBox;
public static Message Create(int db, CommandFlags flags, RedisCommand command) public static Message Create(int db, CommandFlags flags, RedisCommand command)
{ {
...@@ -504,16 +485,12 @@ public void SetInternalCall() ...@@ -504,16 +485,12 @@ public void SetInternalCall()
public override string ToString() public override string ToString()
{ {
return string.Format("[{0}]:{1} ({2})", Db, CommandAndKey, return $"[{Db}]:{CommandAndKey} ({resultProcessor?.GetType().Name ?? "(n/a)"})";
resultProcessor == null ? "(n/a)" : resultProcessor.GetType().Name);
} }
public void SetResponseReceived() public void SetResponseReceived()
{ {
if (performance != null) performance?.SetResponseReceived();
{
performance.SetResponseReceived();
}
} }
public bool TryComplete(bool isAsync) public bool TryComplete(bool isAsync)
...@@ -525,21 +502,15 @@ public bool TryComplete(bool isAsync) ...@@ -525,21 +502,15 @@ public bool TryComplete(bool isAsync)
if (ret && isAsync) if (ret && isAsync)
{ {
resultBox = null; // in async mode TryComplete will have unwrapped and recycled resultBox; ensure we no longer reference it via this message resultBox = null; // in async mode TryComplete will have unwrapped and recycled resultBox; ensure we no longer reference it via this message
} }
if (performance != null) performance?.SetCompleted();
{
performance.SetCompleted();
}
return ret; return ret;
} }
else else
{ {
ConnectionMultiplexer.TraceWithoutContext("No result-box to complete for " + Command, "Message"); ConnectionMultiplexer.TraceWithoutContext("No result-box to complete for " + Command, "Message");
if (performance != null) performance?.SetCompleted();
{
performance.SetCompleted();
}
return true; return true;
} }
} }
...@@ -583,7 +554,7 @@ internal static Message Create(int db, CommandFlags flags, RedisCommand command, ...@@ -583,7 +554,7 @@ internal static Message Create(int db, CommandFlags flags, RedisCommand command,
internal static Message Create(int db, CommandFlags flags, RedisCommand command, RedisKey key, RedisValue[] values) internal static Message Create(int db, CommandFlags flags, RedisCommand command, RedisKey key, RedisValue[] values)
{ {
if (values == null) throw new ArgumentNullException("values"); if (values == null) throw new ArgumentNullException(nameof(values));
switch (values.Length) switch (values.Length)
{ {
case 0: return new CommandKeyMessage(db, flags, command, key); case 0: return new CommandKeyMessage(db, flags, command, key);
...@@ -597,7 +568,7 @@ internal static Message Create(int db, CommandFlags flags, RedisCommand command, ...@@ -597,7 +568,7 @@ internal static Message Create(int db, CommandFlags flags, RedisCommand command,
internal static Message Create(int db, CommandFlags flags, RedisCommand command, RedisKey key0, RedisValue[] values, RedisKey key1) internal static Message Create(int db, CommandFlags flags, RedisCommand command, RedisKey key0, RedisValue[] values, RedisKey key1)
{ {
if (values == null) throw new ArgumentNullException("values"); if (values == null) throw new ArgumentNullException(nameof(values));
return new CommandKeyValuesKeyMessage(db, flags, command, key0, values, key1); return new CommandKeyValuesKeyMessage(db, flags, command, key0, values, key1);
} }
...@@ -657,7 +628,7 @@ internal static CommandFlags SetMasterSlaveFlags(CommandFlags everything, Comman ...@@ -657,7 +628,7 @@ internal static CommandFlags SetMasterSlaveFlags(CommandFlags everything, Comman
internal void Cancel() internal void Cancel()
{ {
if (resultProcessor != null) resultProcessor.SetException(this, new TaskCanceledException()); resultProcessor?.SetException(this, new TaskCanceledException());
} }
// true if ready to be completed (i.e. false if re-issued to another server) // true if ready to be completed (i.e. false if re-issued to another server)
...@@ -669,26 +640,17 @@ internal bool ComputeResult(PhysicalConnection connection, RawResult result) ...@@ -669,26 +640,17 @@ internal bool ComputeResult(PhysicalConnection connection, RawResult result)
internal void Fail(ConnectionFailureType failure, Exception innerException) internal void Fail(ConnectionFailureType failure, Exception innerException)
{ {
PhysicalConnection.IdentifyFailureType(innerException, ref failure); PhysicalConnection.IdentifyFailureType(innerException, ref failure);
if (resultProcessor != null) resultProcessor?.ConnectionFail(this, failure, innerException);
{
resultProcessor.ConnectionFail(this, failure, innerException);
}
} }
internal void SetEnqueued() internal void SetEnqueued()
{ {
if(performance != null) performance?.SetEnqueued();
{
performance.SetEnqueued();
}
} }
internal void SetRequestSent() internal void SetRequestSent()
{ {
if (performance != null) performance?.SetRequestSent();
{
performance.SetRequestSent();
}
} }
internal void SetAsking(bool value) internal void SetAsking(bool value)
...@@ -699,7 +661,7 @@ internal void SetAsking(bool value) ...@@ -699,7 +661,7 @@ internal void SetAsking(bool value)
internal void SetNoRedirect() internal void SetNoRedirect()
{ {
this.flags |= CommandFlags.NoRedirect; flags |= CommandFlags.NoRedirect;
} }
internal void SetPreferMaster() internal void SetPreferMaster()
...@@ -737,7 +699,7 @@ internal void WriteTo(PhysicalConnection physical) ...@@ -737,7 +699,7 @@ internal void WriteTo(PhysicalConnection physical)
} }
catch (Exception ex) catch (Exception ex)
{ {
if (physical != null) physical.OnInternalError(ex); physical?.OnInternalError(ex);
Fail(ConnectionFailureType.InternalFailure, ex); Fail(ConnectionFailureType.InternalFailure, ex);
} }
} }
...@@ -748,10 +710,10 @@ internal abstract class CommandChannelBase : Message ...@@ -748,10 +710,10 @@ internal abstract class CommandChannelBase : Message
public CommandChannelBase(int db, CommandFlags flags, RedisCommand command, RedisChannel channel) : base(db, flags, command) public CommandChannelBase(int db, CommandFlags flags, RedisCommand command, RedisChannel channel) : base(db, flags, command)
{ {
channel.AssertNotNull(); channel.AssertNotNull();
this.Channel = channel; Channel = channel;
} }
public override string CommandAndKey { get { return Command + " " + Channel; } } public override string CommandAndKey => Command + " " + Channel;
} }
internal abstract class CommandKeyBase : Message internal abstract class CommandKeyBase : Message
...@@ -761,10 +723,11 @@ internal abstract class CommandKeyBase : Message ...@@ -761,10 +723,11 @@ internal abstract class CommandKeyBase : Message
public CommandKeyBase(int db, CommandFlags flags, RedisCommand command, RedisKey key) : base(db, flags, command) public CommandKeyBase(int db, CommandFlags flags, RedisCommand command, RedisKey key) : base(db, flags, command)
{ {
key.AssertNotNull(); key.AssertNotNull();
this.Key = key; Key = key;
} }
public override string CommandAndKey { get { return Command + " " + ((string)Key); } } public override string CommandAndKey => Command + " " + (string)Key;
public override int GetHashSlot(ServerSelectionStrategy serverSelectionStrategy) public override int GetHashSlot(ServerSelectionStrategy serverSelectionStrategy)
{ {
return serverSelectionStrategy.HashSlot(Key); return serverSelectionStrategy.HashSlot(Key);
......
...@@ -9,7 +9,7 @@ sealed partial class MessageQueue ...@@ -9,7 +9,7 @@ sealed partial class MessageQueue
regular = new Queue<Message>(), regular = new Queue<Message>(),
high = new Queue<Message>(); high = new Queue<Message>();
public object SyncLock { get { return regular; } } public object SyncLock => regular;
public Message Dequeue() public Message Dequeue()
{ {
......
...@@ -31,11 +31,8 @@ private static readonly Message ...@@ -31,11 +31,8 @@ private static readonly Message
ReusableAskingCommand = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.ASKING); ReusableAskingCommand = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.ASKING);
private readonly CompletionManager completionManager; private readonly CompletionManager completionManager;
private readonly ConnectionType connectionType;
private readonly ConnectionMultiplexer multiplexer;
readonly long[] profileLog = new long[ProfileLogSamples]; readonly long[] profileLog = new long[ProfileLogSamples];
private readonly MessageQueue queue = new MessageQueue(); private readonly MessageQueue queue = new MessageQueue();
private readonly ServerEndPoint serverEndPoint;
int activeWriters = 0; int activeWriters = 0;
private int beating; private int beating;
int failConnectCount = 0; int failConnectCount = 0;
...@@ -53,11 +50,11 @@ private static readonly Message ...@@ -53,11 +50,11 @@ private static readonly Message
private volatile int state = (int)State.Disconnected; private volatile int state = (int)State.Disconnected;
public PhysicalBridge(ServerEndPoint serverEndPoint, ConnectionType type) public PhysicalBridge(ServerEndPoint serverEndPoint, ConnectionType type)
{ {
this.serverEndPoint = serverEndPoint; ServerEndPoint = serverEndPoint;
this.connectionType = type; ConnectionType = type;
this.multiplexer = serverEndPoint.Multiplexer; Multiplexer = serverEndPoint.Multiplexer;
this.Name = Format.ToString(serverEndPoint.EndPoint) + "/" + connectionType.ToString(); Name = Format.ToString(serverEndPoint.EndPoint) + "/" + ConnectionType.ToString();
this.completionManager = new CompletionManager(multiplexer, Name); completionManager = new CompletionManager(Multiplexer, Name);
} }
public enum State : byte public enum State : byte
...@@ -68,19 +65,13 @@ public enum State : byte ...@@ -68,19 +65,13 @@ public enum State : byte
Disconnected Disconnected
} }
public ConnectionType ConnectionType { get { return connectionType; } } public ConnectionType ConnectionType { get; }
public bool IsConnected public bool IsConnected => state == (int)State.ConnectedEstablished;
{
get
{
return state == (int)State.ConnectedEstablished;
}
}
public ConnectionMultiplexer Multiplexer { get { return multiplexer; } } public ConnectionMultiplexer Multiplexer { get; }
public ServerEndPoint ServerEndPoint { get { return serverEndPoint; } } public ServerEndPoint ServerEndPoint { get; }
public long SubscriptionCount public long SubscriptionCount
{ {
...@@ -91,13 +82,11 @@ public long SubscriptionCount ...@@ -91,13 +82,11 @@ public long SubscriptionCount
} }
} }
internal State ConnectionState { get { return (State)state; } } internal State ConnectionState => (State)state;
internal bool IsBeating { get { return Interlocked.CompareExchange(ref beating, 0, 0) == 1; } } internal bool IsBeating => Interlocked.CompareExchange(ref beating, 0, 0) == 1;
internal long OperationCount => Interlocked.Read(ref operationCount);
internal long OperationCount
{
get { return Interlocked.Read(ref operationCount); }
}
public void CompleteSyncOrAsync(ICompletable operation) public void CompleteSyncOrAsync(ICompletable operation)
{ {
completionManager.CompleteSyncOrAsync(operation); completionManager.CompleteSyncOrAsync(operation);
...@@ -119,7 +108,7 @@ public void ReportNextFailure() ...@@ -119,7 +108,7 @@ public void ReportNextFailure()
public override string ToString() public override string ToString()
{ {
return connectionType + "/" + Format.ToString(serverEndPoint.EndPoint); return ConnectionType + "/" + Format.ToString(ServerEndPoint.EndPoint);
} }
public void TryConnect(TextWriter log) public void TryConnect(TextWriter log)
...@@ -154,7 +143,7 @@ public bool TryEnqueue(Message message, bool isSlave) ...@@ -154,7 +143,7 @@ public bool TryEnqueue(Message message, bool isSlave)
if (reqWrite) if (reqWrite)
{ {
multiplexer.RequestWrite(this, false); Multiplexer.RequestWrite(this, false);
} }
return true; return true;
} }
...@@ -204,11 +193,7 @@ internal void GetCounters(ConnectionCounters counters) ...@@ -204,11 +193,7 @@ internal void GetCounters(ConnectionCounters counters)
counters.WriterCount = Interlocked.CompareExchange(ref activeWriters, 0, 0); counters.WriterCount = Interlocked.CompareExchange(ref activeWriters, 0, 0);
counters.NonPreferredEndpointCount = Interlocked.Read(ref nonPreferredEndpointCount); counters.NonPreferredEndpointCount = Interlocked.Read(ref nonPreferredEndpointCount);
completionManager.GetCounters(counters); completionManager.GetCounters(counters);
var tmp = physical; physical?.GetCounters(counters);
if (tmp != null)
{
tmp.GetCounters(counters);
}
} }
internal int GetOutstandingCount(out int inst, out int qu, out int qs, out int qc, out int wr, out int wq, out int @in, out int ar) internal int GetOutstandingCount(out int inst, out int qu, out int qs, out int qc, out int wr, out int wq, out int @in, out int ar)
...@@ -237,12 +222,11 @@ internal int GetPendingCount() ...@@ -237,12 +222,11 @@ internal int GetPendingCount()
internal string GetStormLog() internal string GetStormLog()
{ {
var sb = new StringBuilder("Storm log for ").Append(Format.ToString(serverEndPoint.EndPoint)).Append(" / ").Append(connectionType) var sb = new StringBuilder("Storm log for ").Append(Format.ToString(ServerEndPoint.EndPoint)).Append(" / ").Append(ConnectionType)
.Append(" at ").Append(DateTime.UtcNow) .Append(" at ").Append(DateTime.UtcNow)
.AppendLine().AppendLine(); .AppendLine().AppendLine();
queue.GetStormLog(sb); queue.GetStormLog(sb);
var tmp = physical; physical?.GetStormLog(sb);
if (tmp != null) tmp.GetStormLog(sb);
completionManager.GetStormLog(sb); completionManager.GetStormLog(sb);
sb.Append("Circular op-count snapshot:"); sb.Append("Circular op-count snapshot:");
AppendProfile(sb); AppendProfile(sb);
...@@ -257,12 +241,12 @@ internal void IncrementOpCount() ...@@ -257,12 +241,12 @@ internal void IncrementOpCount()
internal void KeepAlive() internal void KeepAlive()
{ {
var commandMap = multiplexer.CommandMap; var commandMap = Multiplexer.CommandMap;
Message msg = null; Message msg = null;
switch (connectionType) switch (ConnectionType)
{ {
case ConnectionType.Interactive: case ConnectionType.Interactive:
msg = serverEndPoint.GetTracerMessage(false); msg = ServerEndPoint.GetTracerMessage(false);
msg.SetSource(ResultProcessor.Tracer, null); msg.SetSource(ResultProcessor.Tracer, null);
break; break;
case ConnectionType.Subscription: case ConnectionType.Subscription:
...@@ -277,10 +261,10 @@ internal void KeepAlive() ...@@ -277,10 +261,10 @@ internal void KeepAlive()
if (msg != null) if (msg != null)
{ {
msg.SetInternalCall(); msg.SetInternalCall();
multiplexer.Trace("Enqueue: " + msg); Multiplexer.Trace("Enqueue: " + msg);
if (!TryEnqueue(msg, serverEndPoint.IsSlave)) if (!TryEnqueue(msg, ServerEndPoint.IsSlave))
{ {
OnInternalError(ExceptionFactory.NoConnectionAvailable(multiplexer.IncludeDetailInExceptions, msg.Command, msg, serverEndPoint)); OnInternalError(ExceptionFactory.NoConnectionAvailable(Multiplexer.IncludeDetailInExceptions, msg.Command, msg, ServerEndPoint));
} }
} }
} }
...@@ -290,7 +274,7 @@ internal void OnConnected(PhysicalConnection connection, TextWriter log) ...@@ -290,7 +274,7 @@ internal void OnConnected(PhysicalConnection connection, TextWriter log)
Trace("OnConnected"); Trace("OnConnected");
if (physical == connection && !isDisposed && ChangeState(State.Connecting, State.ConnectedEstablishing)) if (physical == connection && !isDisposed && ChangeState(State.Connecting, State.ConnectedEstablishing))
{ {
serverEndPoint.OnEstablishing(connection, log); ServerEndPoint.OnEstablishing(connection, log);
} }
else else
{ {
...@@ -319,8 +303,8 @@ internal void OnConnectionFailed(PhysicalConnection connection, ConnectionFailur ...@@ -319,8 +303,8 @@ internal void OnConnectionFailed(PhysicalConnection connection, ConnectionFailur
if (reportNextFailure) if (reportNextFailure)
{ {
reportNextFailure = false; // until it is restored reportNextFailure = false; // until it is restored
var endpoint = serverEndPoint.EndPoint; var endpoint = ServerEndPoint.EndPoint;
multiplexer.OnConnectionFailed(endpoint, connectionType, failureType, innerException, reconfigureNextFailure); Multiplexer.OnConnectionFailed(endpoint, ConnectionType, failureType, innerException, reconfigureNextFailure);
} }
} }
...@@ -367,9 +351,9 @@ internal void OnFullyEstablished(PhysicalConnection connection) ...@@ -367,9 +351,9 @@ internal void OnFullyEstablished(PhysicalConnection connection)
{ {
reportNextFailure = reconfigureNextFailure = true; reportNextFailure = reconfigureNextFailure = true;
Interlocked.Exchange(ref failConnectCount, 0); Interlocked.Exchange(ref failConnectCount, 0);
serverEndPoint.OnFullyEstablished(connection); ServerEndPoint.OnFullyEstablished(connection);
multiplexer.RequestWrite(this, true); Multiplexer.RequestWrite(this, true);
if(connectionType == ConnectionType.Interactive) serverEndPoint.CheckInfoReplication(); if(ConnectionType == ConnectionType.Interactive) ServerEndPoint.CheckInfoReplication();
} }
else else
{ {
...@@ -395,7 +379,7 @@ internal void OnHeartbeat(bool ifConnectedOnly) ...@@ -395,7 +379,7 @@ internal void OnHeartbeat(bool ifConnectedOnly)
{ {
case (int)State.Connecting: case (int)State.Connecting:
int connectTimeMilliseconds = unchecked(Environment.TickCount - VolatileWrapper.Read(ref connectStartTicks)); int connectTimeMilliseconds = unchecked(Environment.TickCount - VolatileWrapper.Read(ref connectStartTicks));
if (connectTimeMilliseconds >= multiplexer.RawConfig.ConnectTimeout) if (connectTimeMilliseconds >= Multiplexer.RawConfig.ConnectTimeout)
{ {
Trace("Aborting connect"); Trace("Aborting connect");
// abort and reconnect // abort and reconnect
...@@ -421,12 +405,12 @@ internal void OnHeartbeat(bool ifConnectedOnly) ...@@ -421,12 +405,12 @@ internal void OnHeartbeat(bool ifConnectedOnly)
tmp.Bridge.ServerEndPoint.ClearUnselectable(UnselectableFlags.DidNotRespond); tmp.Bridge.ServerEndPoint.ClearUnselectable(UnselectableFlags.DidNotRespond);
} }
tmp.OnHeartbeat(); tmp.OnHeartbeat();
int writeEverySeconds = serverEndPoint.WriteEverySeconds, int writeEverySeconds = ServerEndPoint.WriteEverySeconds,
checkConfigSeconds = multiplexer.RawConfig.ConfigCheckSeconds; checkConfigSeconds = Multiplexer.RawConfig.ConfigCheckSeconds;
if(state == (int)State.ConnectedEstablished && connectionType == ConnectionType.Interactive if(state == (int)State.ConnectedEstablished && ConnectionType == ConnectionType.Interactive
&& checkConfigSeconds > 0 && serverEndPoint.LastInfoReplicationCheckSecondsAgo >= checkConfigSeconds && checkConfigSeconds > 0 && ServerEndPoint.LastInfoReplicationCheckSecondsAgo >= checkConfigSeconds
&& serverEndPoint.CheckInfoReplication()) && ServerEndPoint.CheckInfoReplication())
{ {
// that serves as a keep-alive, if it is accepted // that serves as a keep-alive, if it is accepted
} }
...@@ -457,7 +441,7 @@ internal void OnHeartbeat(bool ifConnectedOnly) ...@@ -457,7 +441,7 @@ internal void OnHeartbeat(bool ifConnectedOnly)
if (!ifConnectedOnly) if (!ifConnectedOnly)
{ {
AbortUnsent(); AbortUnsent();
multiplexer.Trace("Resurrecting " + this.ToString()); Multiplexer.Trace("Resurrecting " + this.ToString());
GetConnection(null); GetConnection(null);
} }
break; break;
...@@ -490,13 +474,13 @@ internal void RemovePhysical(PhysicalConnection connection) ...@@ -490,13 +474,13 @@ internal void RemovePhysical(PhysicalConnection connection)
[Conditional("VERBOSE")] [Conditional("VERBOSE")]
internal void Trace(string message) internal void Trace(string message)
{ {
multiplexer.Trace(message, ToString()); Multiplexer.Trace(message, ToString());
} }
[Conditional("VERBOSE")] [Conditional("VERBOSE")]
internal void Trace(bool condition, string message) internal void Trace(bool condition, string message)
{ {
if (condition) multiplexer.Trace(message, ToString()); if (condition) Multiplexer.Trace(message, ToString());
} }
internal bool TryEnqueue(List<Message> messages, bool isSlave) internal bool TryEnqueue(List<Message> messages, bool isSlave)
...@@ -520,7 +504,7 @@ internal bool TryEnqueue(List<Message> messages, bool isSlave) ...@@ -520,7 +504,7 @@ internal bool TryEnqueue(List<Message> messages, bool isSlave)
Trace("Now pending: " + GetPendingCount()); Trace("Now pending: " + GetPendingCount());
if (reqWrite) // was empty before if (reqWrite) // was empty before
{ {
multiplexer.RequestWrite(this, false); Multiplexer.RequestWrite(this, false);
} }
return true; return true;
} }
...@@ -584,7 +568,7 @@ internal WriteResult WriteQueue(int maxWork) ...@@ -584,7 +568,7 @@ internal WriteResult WriteQueue(int maxWork)
return WriteResult.NoConnection; return WriteResult.NoConnection;
} }
Message last = null; Message last;
int count = 0; int count = 0;
while (true) while (true)
{ {
...@@ -662,7 +646,7 @@ private State ChangeState(State newState) ...@@ -662,7 +646,7 @@ private State ChangeState(State newState)
#pragma warning restore 0420 #pragma warning restore 0420
if (oldState != newState) if (oldState != newState)
{ {
multiplexer.Trace(connectionType + " state changed from " + oldState + " to " + newState); Multiplexer.Trace(ConnectionType + " state changed from " + oldState + " to " + newState);
if (newState == State.Disconnected) if (newState == State.Disconnected)
{ {
...@@ -679,7 +663,7 @@ private bool ChangeState(State oldState, State newState) ...@@ -679,7 +663,7 @@ private bool ChangeState(State oldState, State newState)
#pragma warning restore 0420 #pragma warning restore 0420
if (result) if (result)
{ {
multiplexer.Trace(connectionType + " state changed from " + oldState + " to " + newState); Multiplexer.Trace(ConnectionType + " state changed from " + oldState + " to " + newState);
} }
return result; return result;
} }
...@@ -690,7 +674,7 @@ private PhysicalConnection GetConnection(TextWriter log) ...@@ -690,7 +674,7 @@ private PhysicalConnection GetConnection(TextWriter log)
{ {
try try
{ {
if (!multiplexer.IsDisposed) if (!Multiplexer.IsDisposed)
{ {
Multiplexer.LogLocked(log, "Connecting {0}...", Name); Multiplexer.LogLocked(log, "Connecting {0}...", Name);
Multiplexer.Trace("Connecting...", Name); Multiplexer.Trace("Connecting...", Name);
...@@ -736,7 +720,7 @@ private void LogNonPreferred(CommandFlags flags, bool isSlave) ...@@ -736,7 +720,7 @@ private void LogNonPreferred(CommandFlags flags, bool isSlave)
} }
private void OnInternalError(Exception exception, [CallerMemberName] string origin = null) private void OnInternalError(Exception exception, [CallerMemberName] string origin = null)
{ {
multiplexer.OnInternalError(exception, serverEndPoint.EndPoint, connectionType, origin); Multiplexer.OnInternalError(exception, ServerEndPoint.EndPoint, ConnectionType, origin);
} }
private void SelectDatabase(PhysicalConnection connection, Message message) private void SelectDatabase(PhysicalConnection connection, Message message)
{ {
...@@ -761,9 +745,9 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message ...@@ -761,9 +745,9 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message
{ {
var cmd = message.Command; var cmd = message.Command;
bool isMasterOnly = message.IsMasterOnly(); bool isMasterOnly = message.IsMasterOnly();
if (isMasterOnly && serverEndPoint.IsSlave && (serverEndPoint.SlaveReadOnly || !serverEndPoint.AllowSlaveWrites)) if (isMasterOnly && ServerEndPoint.IsSlave && (ServerEndPoint.SlaveReadOnly || !ServerEndPoint.AllowSlaveWrites))
{ {
throw ExceptionFactory.MasterOnly(multiplexer.IncludeDetailInExceptions, message.Command, message, ServerEndPoint); throw ExceptionFactory.MasterOnly(Multiplexer.IncludeDetailInExceptions, message.Command, message, ServerEndPoint);
} }
SelectDatabase(connection, message); SelectDatabase(connection, message);
...@@ -812,7 +796,7 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message ...@@ -812,7 +796,7 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message
{ {
case RedisCommand.EVAL: case RedisCommand.EVAL:
case RedisCommand.EVALSHA: case RedisCommand.EVALSHA:
if(!serverEndPoint.GetFeatures().ScriptingDatabaseSafe) if(!ServerEndPoint.GetFeatures().ScriptingDatabaseSafe)
{ {
connection.SetUnknownDatabase(); connection.SetUnknownDatabase();
} }
...@@ -846,7 +830,7 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message ...@@ -846,7 +830,7 @@ private bool WriteMessageToServer(PhysicalConnection connection, Message message
CompleteSyncOrAsync(message); CompleteSyncOrAsync(message);
// we're not sure *what* happened here; probably an IOException; kill the connection // we're not sure *what* happened here; probably an IOException; kill the connection
if(connection != null) connection.RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex); connection?.RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex);
return false; return false;
} }
} }
......
...@@ -34,7 +34,7 @@ private static Action<Task<int>> EndReadFactory(PhysicalConnection physical) ...@@ -34,7 +34,7 @@ private static Action<Task<int>> EndReadFactory(PhysicalConnection physical)
{ // can't capture AsyncState on SocketRead, so we'll do it once per physical instead { // can't capture AsyncState on SocketRead, so we'll do it once per physical instead
try try
{ {
physical.multiplexer.Trace("Completed asynchronously: processing in callback", physical.physicalName); physical.Multiplexer.Trace("Completed asynchronously: processing in callback", physical.physicalName);
if (physical.EndReading(result)) physical.BeginReading(); if (physical.EndReading(result)) physical.BeginReading();
} }
catch (Exception ex) catch (Exception ex)
...@@ -50,7 +50,7 @@ private static Action<Task<int>> EndReadFactory(PhysicalConnection physical) ...@@ -50,7 +50,7 @@ private static Action<Task<int>> EndReadFactory(PhysicalConnection physical)
if (result.CompletedSynchronously || (physical = result.AsyncState as PhysicalConnection) == null) return; if (result.CompletedSynchronously || (physical = result.AsyncState as PhysicalConnection) == null) return;
try try
{ {
physical.multiplexer.Trace("Completed asynchronously: processing in callback", physical.physicalName); physical.Multiplexer.Trace("Completed asynchronously: processing in callback", physical.physicalName);
if (physical.EndReading(result)) physical.BeginReading(); if (physical.EndReading(result)) physical.BeginReading();
} }
catch (Exception ex) catch (Exception ex)
...@@ -71,12 +71,8 @@ private static readonly Message ...@@ -71,12 +71,8 @@ private static readonly Message
private static int totalCount; private static int totalCount;
private readonly PhysicalBridge bridge;
private readonly ConnectionType connectionType; private readonly ConnectionType connectionType;
private readonly ConnectionMultiplexer multiplexer;
// things sent to this physical, but not yet received // things sent to this physical, but not yet received
private readonly Queue<Message> outstanding = new Queue<Message>(); private readonly Queue<Message> outstanding = new Queue<Message>();
...@@ -104,12 +100,12 @@ public PhysicalConnection(PhysicalBridge bridge) ...@@ -104,12 +100,12 @@ public PhysicalConnection(PhysicalBridge bridge)
lastWriteTickCount = lastReadTickCount = Environment.TickCount; lastWriteTickCount = lastReadTickCount = Environment.TickCount;
lastBeatTickCount = 0; lastBeatTickCount = 0;
this.connectionType = bridge.ConnectionType; this.connectionType = bridge.ConnectionType;
this.multiplexer = bridge.Multiplexer; this.Multiplexer = bridge.Multiplexer;
this.ChannelPrefix = multiplexer.RawConfig.ChannelPrefix; this.ChannelPrefix = Multiplexer.RawConfig.ChannelPrefix;
if (this.ChannelPrefix != null && this.ChannelPrefix.Length == 0) this.ChannelPrefix = null; // null tests are easier than null+empty if (this.ChannelPrefix != null && this.ChannelPrefix.Length == 0) this.ChannelPrefix = null; // null tests are easier than null+empty
var endpoint = bridge.ServerEndPoint.EndPoint; var endpoint = bridge.ServerEndPoint.EndPoint;
physicalName = connectionType + "#" + Interlocked.Increment(ref totalCount) + "@" + Format.ToString(endpoint); physicalName = connectionType + "#" + Interlocked.Increment(ref totalCount) + "@" + Format.ToString(endpoint);
this.bridge = bridge; this.Bridge = bridge;
#if CORE_CLR #if CORE_CLR
endRead = EndReadFactory(this); endRead = EndReadFactory(this);
#endif #endif
...@@ -119,10 +115,10 @@ public PhysicalConnection(PhysicalBridge bridge) ...@@ -119,10 +115,10 @@ public PhysicalConnection(PhysicalBridge bridge)
public void BeginConnect(TextWriter log) public void BeginConnect(TextWriter log)
{ {
VolatileWrapper.Write(ref firstUnansweredWriteTickCount, 0); VolatileWrapper.Write(ref firstUnansweredWriteTickCount, 0);
var endpoint = this.bridge.ServerEndPoint.EndPoint; var endpoint = this.Bridge.ServerEndPoint.EndPoint;
multiplexer.Trace("Connecting...", physicalName); Multiplexer.Trace("Connecting...", physicalName);
this.socketToken = multiplexer.SocketManager.BeginConnect(endpoint, this, multiplexer, log); this.socketToken = Multiplexer.SocketManager.BeginConnect(endpoint, this, Multiplexer, log);
} }
private enum ReadMode : byte private enum ReadMode : byte
...@@ -132,17 +128,11 @@ private enum ReadMode : byte ...@@ -132,17 +128,11 @@ private enum ReadMode : byte
ReadWrite ReadWrite
} }
public PhysicalBridge Bridge { get { return bridge; } } public PhysicalBridge Bridge { get; }
public long LastWriteSecondsAgo public long LastWriteSecondsAgo => unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastWriteTickCount)) / 1000;
{
get
{
return unchecked(Environment.TickCount - VolatileWrapper.Read(ref lastWriteTickCount)) / 1000;
}
}
public ConnectionMultiplexer Multiplexer { get { return multiplexer; } } public ConnectionMultiplexer Multiplexer { get; }
public long SubscriptionCount { get; set; } public long SubscriptionCount { get; set; }
...@@ -152,7 +142,7 @@ public void Dispose() ...@@ -152,7 +142,7 @@ public void Dispose()
{ {
if (outStream != null) if (outStream != null)
{ {
multiplexer.Trace("Disconnecting...", physicalName); Multiplexer.Trace("Disconnecting...", physicalName);
#if !CORE_CLR #if !CORE_CLR
try { outStream.Close(); } catch { } try { outStream.Close(); } catch { }
#endif #endif
...@@ -169,10 +159,9 @@ public void Dispose() ...@@ -169,10 +159,9 @@ public void Dispose()
} }
if (socketToken.HasValue) if (socketToken.HasValue)
{ {
var socketManager = multiplexer.SocketManager; Multiplexer.SocketManager?.Shutdown(socketToken);
if (socketManager != null) socketManager.Shutdown(socketToken);
socketToken = default(SocketToken); socketToken = default(SocketToken);
multiplexer.Trace("Disconnected", physicalName); Multiplexer.Trace("Disconnected", physicalName);
RecordConnectionFailed(ConnectionFailureType.ConnectionDisposed); RecordConnectionFailed(ConnectionFailureType.ConnectionDisposed);
} }
OnCloseEcho(); OnCloseEcho();
...@@ -200,12 +189,12 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket ...@@ -200,12 +189,12 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket
if (failureType == ConnectionFailureType.InternalFailure) OnInternalError(innerException, origin); if (failureType == ConnectionFailureType.InternalFailure) OnInternalError(innerException, origin);
// stop anything new coming in... // stop anything new coming in...
bridge.Trace("Failed: " + failureType); Bridge.Trace("Failed: " + failureType);
bool isCurrent; bool isCurrent;
PhysicalBridge.State oldState; PhysicalBridge.State oldState;
int @in = -1, ar = -1; int @in = -1, ar = -1;
managerState = SocketManager.ManagerState.RecordConnectionFailed_OnDisconnected; managerState = SocketManager.ManagerState.RecordConnectionFailed_OnDisconnected;
bridge.OnDisconnected(failureType, this, out isCurrent, out oldState); Bridge.OnDisconnected(failureType, this, out isCurrent, out oldState);
if(oldState == PhysicalBridge.State.ConnectedEstablished) if(oldState == PhysicalBridge.State.ConnectedEstablished)
{ {
try try
...@@ -222,11 +211,11 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket ...@@ -222,11 +211,11 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket
lastBeat = VolatileWrapper.Read(ref lastBeatTickCount); lastBeat = VolatileWrapper.Read(ref lastBeatTickCount);
int unansweredRead = VolatileWrapper.Read(ref firstUnansweredWriteTickCount); int unansweredRead = VolatileWrapper.Read(ref firstUnansweredWriteTickCount);
var exMessage = new StringBuilder(failureType + " on " + Format.ToString(bridge.ServerEndPoint.EndPoint) + "/" + connectionType); var exMessage = new StringBuilder(failureType + " on " + Format.ToString(Bridge.ServerEndPoint.EndPoint) + "/" + connectionType);
var data = new List<Tuple<string, string>> var data = new List<Tuple<string, string>>
{ {
Tuple.Create("FailureType", failureType.ToString()), Tuple.Create("FailureType", failureType.ToString()),
Tuple.Create("EndPoint", Format.ToString(bridge.ServerEndPoint.EndPoint)) Tuple.Create("EndPoint", Format.ToString(Bridge.ServerEndPoint.EndPoint))
}; };
Action<string, string, string> add = (lk, sk, v) => Action<string, string, string> add = (lk, sk, v) =>
{ {
...@@ -240,8 +229,8 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket ...@@ -240,8 +229,8 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket
add("Last-Read", "last-read", unchecked(now - lastRead) / 1000 + "s ago"); add("Last-Read", "last-read", unchecked(now - lastRead) / 1000 + "s ago");
add("Last-Write", "last-write", unchecked(now - lastWrite) / 1000 + "s ago"); add("Last-Write", "last-write", unchecked(now - lastWrite) / 1000 + "s ago");
add("Unanswered-Write", "unanswered-write", unchecked(now - unansweredRead) / 1000 + "s ago"); add("Unanswered-Write", "unanswered-write", unchecked(now - unansweredRead) / 1000 + "s ago");
add("Keep-Alive", "keep-alive", bridge.ServerEndPoint.WriteEverySeconds + "s"); add("Keep-Alive", "keep-alive", Bridge.ServerEndPoint.WriteEverySeconds + "s");
add("Pending", "pending", bridge.GetPendingCount().ToString()); add("Pending", "pending", Bridge.GetPendingCount().ToString());
add("Previous-Physical-State", "state", oldState.ToString()); add("Previous-Physical-State", "state", oldState.ToString());
if(@in >= 0) if(@in >= 0)
...@@ -250,11 +239,11 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket ...@@ -250,11 +239,11 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket
add("Active-Readers", "ar", ar.ToString()); add("Active-Readers", "ar", ar.ToString());
} }
add("Last-Heartbeat", "last-heartbeat", (lastBeat == 0 ? "never" : (unchecked(now - lastBeat)/1000 + "s ago"))+ (bridge.IsBeating ? " (mid-beat)" : "") ); add("Last-Heartbeat", "last-heartbeat", (lastBeat == 0 ? "never" : (unchecked(now - lastBeat)/1000 + "s ago"))+ (Bridge.IsBeating ? " (mid-beat)" : "") );
add("Last-Multiplexer-Heartbeat", "last-mbeat", multiplexer.LastHeartbeatSecondsAgo + "s ago"); add("Last-Multiplexer-Heartbeat", "last-mbeat", Multiplexer.LastHeartbeatSecondsAgo + "s ago");
add("Last-Global-Heartbeat", "global", ConnectionMultiplexer.LastGlobalHeartbeatSecondsAgo + "s ago"); add("Last-Global-Heartbeat", "global", ConnectionMultiplexer.LastGlobalHeartbeatSecondsAgo + "s ago");
#if FEATURE_SOCKET_MODE_POLL #if FEATURE_SOCKET_MODE_POLL
var mgr = bridge.Multiplexer.SocketManager; var mgr = Bridge.Multiplexer.SocketManager;
add("SocketManager-State", "mgr", mgr.State.ToString()); add("SocketManager-State", "mgr", mgr.State.ToString());
add("Last-Error", "err", mgr.LastErrorTimeRelative()); add("Last-Error", "err", mgr.LastErrorTimeRelative());
#endif #endif
...@@ -269,27 +258,26 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket ...@@ -269,27 +258,26 @@ public void RecordConnectionFailed(ConnectionFailureType failureType, ref Socket
} }
managerState = SocketManager.ManagerState.RecordConnectionFailed_OnConnectionFailed; managerState = SocketManager.ManagerState.RecordConnectionFailed_OnConnectionFailed;
bridge.OnConnectionFailed(this, failureType, ex); Bridge.OnConnectionFailed(this, failureType, ex);
} }
// cleanup // cleanup
managerState = SocketManager.ManagerState.RecordConnectionFailed_FailOutstanding; managerState = SocketManager.ManagerState.RecordConnectionFailed_FailOutstanding;
lock (outstanding) lock (outstanding)
{ {
bridge.Trace(outstanding.Count != 0, "Failing outstanding messages: " + outstanding.Count); Bridge.Trace(outstanding.Count != 0, "Failing outstanding messages: " + outstanding.Count);
while (outstanding.Count != 0) while (outstanding.Count != 0)
{ {
var next = outstanding.Dequeue(); var next = outstanding.Dequeue();
bridge.Trace("Failing: " + next); Bridge.Trace("Failing: " + next);
next.Fail(failureType, innerException); next.Fail(failureType, innerException);
bridge.CompleteSyncOrAsync(next); Bridge.CompleteSyncOrAsync(next);
} }
} }
// burn the socket // burn the socket
managerState = SocketManager.ManagerState.RecordConnectionFailed_ShutdownSocket; managerState = SocketManager.ManagerState.RecordConnectionFailed_ShutdownSocket;
var socketManager = multiplexer.SocketManager; Multiplexer.SocketManager?.Shutdown(socketToken);
if (socketManager != null) socketManager.Shutdown(socketToken);
} }
public override string ToString() public override string ToString()
...@@ -328,7 +316,7 @@ internal void GetCounters(ConnectionCounters counters) ...@@ -328,7 +316,7 @@ internal void GetCounters(ConnectionCounters counters)
internal Message GetReadModeCommand(bool isMasterOnly) internal Message GetReadModeCommand(bool isMasterOnly)
{ {
var serverEndpoint = bridge.ServerEndPoint; var serverEndpoint = Bridge.ServerEndPoint;
if (serverEndpoint.RequiresReadMode) if (serverEndpoint.RequiresReadMode)
{ {
ReadMode requiredReadMode = isMasterOnly ? ReadMode.ReadWrite : ReadMode.ReadOnly; ReadMode requiredReadMode = isMasterOnly ? ReadMode.ReadWrite : ReadMode.ReadOnly;
...@@ -356,7 +344,7 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message) ...@@ -356,7 +344,7 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message)
if (targetDatabase < 0) return null; if (targetDatabase < 0) return null;
if (targetDatabase != currentDatabase) if (targetDatabase != currentDatabase)
{ {
var serverEndpoint = bridge.ServerEndPoint; var serverEndpoint = Bridge.ServerEndPoint;
int available = serverEndpoint.Databases; int available = serverEndpoint.Databases;
if (!serverEndpoint.HasDatabases) // only db0 is available on cluster/twemproxy if (!serverEndpoint.HasDatabases) // only db0 is available on cluster/twemproxy
...@@ -371,7 +359,7 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message) ...@@ -371,7 +359,7 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message)
if(message.Command == RedisCommand.SELECT) if(message.Command == RedisCommand.SELECT)
{ {
// this could come from an EVAL/EVALSHA inside a transaction, for example; we'll accept it // this could come from an EVAL/EVALSHA inside a transaction, for example; we'll accept it
bridge.Trace("Switching database: " + targetDatabase); Bridge.Trace("Switching database: " + targetDatabase);
currentDatabase = targetDatabase; currentDatabase = targetDatabase;
return null; return null;
} }
...@@ -383,9 +371,9 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message) ...@@ -383,9 +371,9 @@ internal Message GetSelectDatabaseCommand(int targetDatabase, Message message)
if (available != 0 && targetDatabase >= available) // we positively know it is out of range if (available != 0 && targetDatabase >= available) // we positively know it is out of range
{ {
throw ExceptionFactory.DatabaseOutfRange(multiplexer.IncludeDetailInExceptions, targetDatabase, message, serverEndpoint); throw ExceptionFactory.DatabaseOutfRange(Multiplexer.IncludeDetailInExceptions, targetDatabase, message, serverEndpoint);
} }
bridge.Trace("Switching database: " + targetDatabase); Bridge.Trace("Switching database: " + targetDatabase);
currentDatabase = targetDatabase; currentDatabase = targetDatabase;
return GetSelectDatabaseCommand(targetDatabase); return GetSelectDatabaseCommand(targetDatabase);
} }
...@@ -429,7 +417,7 @@ internal void OnHeartbeat() ...@@ -429,7 +417,7 @@ internal void OnHeartbeat()
internal void OnInternalError(Exception exception, [CallerMemberName] string origin = null) internal void OnInternalError(Exception exception, [CallerMemberName] string origin = null)
{ {
multiplexer.OnInternalError(exception, bridge.ServerEndPoint.EndPoint, connectionType, origin); Multiplexer.OnInternalError(exception, Bridge.ServerEndPoint.EndPoint, connectionType, origin);
} }
internal void SetUnknownDatabase() internal void SetUnknownDatabase()
...@@ -469,10 +457,10 @@ internal void Write(RedisValue value) ...@@ -469,10 +457,10 @@ internal void Write(RedisValue value)
internal void WriteHeader(RedisCommand command, int arguments) internal void WriteHeader(RedisCommand command, int arguments)
{ {
var commandBytes = multiplexer.CommandMap.GetBytes(command); var commandBytes = Multiplexer.CommandMap.GetBytes(command);
if (commandBytes == null) if (commandBytes == null)
{ {
throw ExceptionFactory.CommandDisabled(multiplexer.IncludeDetailInExceptions, command, null, bridge.ServerEndPoint); throw ExceptionFactory.CommandDisabled(Multiplexer.IncludeDetailInExceptions, command, null, Bridge.ServerEndPoint);
} }
outStream.WriteByte((byte)'*'); outStream.WriteByte((byte)'*');
...@@ -699,14 +687,14 @@ void BeginReading() ...@@ -699,14 +687,14 @@ void BeginReading()
{ {
keepReading = false; keepReading = false;
int space = EnsureSpaceAndComputeBytesToRead(); int space = EnsureSpaceAndComputeBytesToRead();
multiplexer.Trace("Beginning async read...", physicalName); Multiplexer.Trace("Beginning async read...", physicalName);
#if CORE_CLR #if CORE_CLR
var result = netStream.ReadAsync(ioBuffer, ioBufferBytes, space); var result = netStream.ReadAsync(ioBuffer, ioBufferBytes, space);
switch(result.Status) switch(result.Status)
{ {
case TaskStatus.RanToCompletion: case TaskStatus.RanToCompletion:
case TaskStatus.Faulted: case TaskStatus.Faulted:
multiplexer.Trace("Completed synchronously: processing immediately", physicalName); Multiplexer.Trace("Completed synchronously: processing immediately", physicalName);
keepReading = EndReading(result); keepReading = EndReading(result);
break; break;
default: default:
...@@ -717,7 +705,7 @@ void BeginReading() ...@@ -717,7 +705,7 @@ void BeginReading()
var result = netStream.BeginRead(ioBuffer, ioBufferBytes, space, endRead, this); var result = netStream.BeginRead(ioBuffer, ioBufferBytes, space, endRead, this);
if (result.CompletedSynchronously) if (result.CompletedSynchronously)
{ {
multiplexer.Trace("Completed synchronously: processing immediately", physicalName); Multiplexer.Trace("Completed synchronously: processing immediately", physicalName);
keepReading = EndReading(result); keepReading = EndReading(result);
} }
#endif #endif
...@@ -731,7 +719,7 @@ void BeginReading() ...@@ -731,7 +719,7 @@ void BeginReading()
#endif #endif
catch (System.IO.IOException ex) catch (System.IO.IOException ex)
{ {
multiplexer.Trace("Could not connect: " + ex.Message, physicalName); Multiplexer.Trace("Could not connect: " + ex.Message, physicalName);
} }
} }
int haveReader; int haveReader;
...@@ -775,13 +763,13 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log) ...@@ -775,13 +763,13 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log)
// the order is important here: // the order is important here:
// [network]<==[ssl]<==[logging]<==[buffered] // [network]<==[ssl]<==[logging]<==[buffered]
var config = multiplexer.RawConfig; var config = Multiplexer.RawConfig;
if(config.Ssl) if(config.Ssl)
{ {
multiplexer.LogLocked(log, "Configuring SSL"); Multiplexer.LogLocked(log, "Configuring SSL");
var host = config.SslHost; var host = config.SslHost;
if (string.IsNullOrWhiteSpace(host)) host = Format.ToStringHostOnly(bridge.ServerEndPoint.EndPoint); if (string.IsNullOrWhiteSpace(host)) host = Format.ToStringHostOnly(Bridge.ServerEndPoint.EndPoint);
var ssl = new SslStream(stream, false, config.CertificateValidationCallback, var ssl = new SslStream(stream, false, config.CertificateValidationCallback,
config.CertificateSelectionCallback ?? GetAmbientCertificateCallback() config.CertificateSelectionCallback ?? GetAmbientCertificateCallback()
...@@ -796,7 +784,7 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log) ...@@ -796,7 +784,7 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log)
catch (AuthenticationException) catch (AuthenticationException)
{ {
RecordConnectionFailed(ConnectionFailureType.AuthenticationFailure); RecordConnectionFailed(ConnectionFailureType.AuthenticationFailure);
multiplexer.Trace("Encryption failure"); Multiplexer.Trace("Encryption failure");
return SocketMode.Abort; return SocketMode.Abort;
} }
stream = ssl; stream = ssl;
...@@ -811,15 +799,15 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log) ...@@ -811,15 +799,15 @@ SocketMode ISocketCallback.Connected(Stream stream, TextWriter log)
#else #else
this.outStream = bufferSize <= 0 ? stream : new BufferedStream(stream, bufferSize); this.outStream = bufferSize <= 0 ? stream : new BufferedStream(stream, bufferSize);
#endif #endif
multiplexer.LogLocked(log, "Connected {0}", bridge); Multiplexer.LogLocked(log, "Connected {0}", Bridge);
bridge.OnConnected(this, log); Bridge.OnConnected(this, log);
return socketMode; return socketMode;
} }
catch (Exception ex) catch (Exception ex)
{ {
RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex); // includes a bridge.OnDisconnected RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex); // includes a bridge.OnDisconnected
multiplexer.Trace("Could not connect: " + ex.Message, physicalName); Multiplexer.Trace("Could not connect: " + ex.Message, physicalName);
return SocketMode.Abort; return SocketMode.Abort;
} }
} }
...@@ -844,8 +832,7 @@ private bool EndReading(IAsyncResult result) ...@@ -844,8 +832,7 @@ private bool EndReading(IAsyncResult result)
{ {
try try
{ {
var tmp = netStream; int bytesRead = netStream?.EndRead(result) ?? 0;
int bytesRead = tmp == null ? 0 : tmp.EndRead(result);
return ProcessReadBytes(bytesRead); return ProcessReadBytes(bytesRead);
} }
catch (Exception ex) catch (Exception ex)
...@@ -879,7 +866,7 @@ void MatchResult(RawResult result) ...@@ -879,7 +866,7 @@ void MatchResult(RawResult result)
if (items.Length >= 3 && items[0].IsEqual(message)) if (items.Length >= 3 && items[0].IsEqual(message))
{ {
// special-case the configuration change broadcasts (we don't keep that in the usual pub/sub registry) // special-case the configuration change broadcasts (we don't keep that in the usual pub/sub registry)
var configChanged = multiplexer.ConfigurationChangedChannel; var configChanged = Multiplexer.ConfigurationChangedChannel;
if (configChanged != null && items[1].IsEqual(configChanged)) if (configChanged != null && items[1].IsEqual(configChanged))
{ {
EndPoint blame = null; EndPoint blame = null;
...@@ -891,45 +878,45 @@ void MatchResult(RawResult result) ...@@ -891,45 +878,45 @@ void MatchResult(RawResult result)
} }
} }
catch { /* no biggie */ } catch { /* no biggie */ }
multiplexer.Trace("Configuration changed: " + Format.ToString(blame), physicalName); Multiplexer.Trace("Configuration changed: " + Format.ToString(blame), physicalName);
multiplexer.ReconfigureIfNeeded(blame, true, "broadcast"); Multiplexer.ReconfigureIfNeeded(blame, true, "broadcast");
} }
// invoke the handlers // invoke the handlers
var channel = items[1].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal); var channel = items[1].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal);
multiplexer.Trace("MESSAGE: " + channel, physicalName); Multiplexer.Trace("MESSAGE: " + channel, physicalName);
if (!channel.IsNull) if (!channel.IsNull)
{ {
multiplexer.OnMessage(channel, channel, items[2].AsRedisValue()); Multiplexer.OnMessage(channel, channel, items[2].AsRedisValue());
} }
return; // AND STOP PROCESSING! return; // AND STOP PROCESSING!
} }
else if (items.Length >= 4 && items[0].IsEqual(pmessage)) else if (items.Length >= 4 && items[0].IsEqual(pmessage))
{ {
var channel = items[2].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal); var channel = items[2].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal);
multiplexer.Trace("PMESSAGE: " + channel, physicalName); Multiplexer.Trace("PMESSAGE: " + channel, physicalName);
if (!channel.IsNull) if (!channel.IsNull)
{ {
var sub = items[1].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Pattern); var sub = items[1].AsRedisChannel(ChannelPrefix, RedisChannel.PatternMode.Pattern);
multiplexer.OnMessage(sub, channel, items[3].AsRedisValue()); Multiplexer.OnMessage(sub, channel, items[3].AsRedisValue());
} }
return; // AND STOP PROCESSING! return; // AND STOP PROCESSING!
} }
// if it didn't look like "[p]message", then we still need to process the pending queue // if it didn't look like "[p]message", then we still need to process the pending queue
} }
multiplexer.Trace("Matching result...", physicalName); Multiplexer.Trace("Matching result...", physicalName);
Message msg; Message msg;
lock (outstanding) lock (outstanding)
{ {
multiplexer.Trace(outstanding.Count == 0, "Nothing to respond to!", physicalName); Multiplexer.Trace(outstanding.Count == 0, "Nothing to respond to!", physicalName);
msg = outstanding.Dequeue(); msg = outstanding.Dequeue();
} }
multiplexer.Trace("Response to: " + msg.ToString(), physicalName); Multiplexer.Trace("Response to: " + msg.ToString(), physicalName);
if (msg.ComputeResult(this, result)) if (msg.ComputeResult(this, result))
{ {
bridge.CompleteSyncOrAsync(msg); Bridge.CompleteSyncOrAsync(msg);
} }
} }
partial void OnCloseEcho(); partial void OnCloseEcho();
...@@ -940,7 +927,7 @@ void ISocketCallback.OnHeartbeat() ...@@ -940,7 +927,7 @@ void ISocketCallback.OnHeartbeat()
{ {
try try
{ {
bridge.OnHeartbeat(true); // all the fun code is here Bridge.OnHeartbeat(true); // all the fun code is here
} }
catch (Exception ex) catch (Exception ex)
{ {
...@@ -965,7 +952,7 @@ private int ProcessBuffer(byte[] underlying, ref int offset, ref int count) ...@@ -965,7 +952,7 @@ private int ProcessBuffer(byte[] underlying, ref int offset, ref int count)
offset = tmpOffset; offset = tmpOffset;
count = tmpCount; count = tmpCount;
multiplexer.Trace(result.ToString(), physicalName); Multiplexer.Trace(result.ToString(), physicalName);
MatchResult(result); MatchResult(result);
} }
} while (result.HasValue); } while (result.HasValue);
...@@ -975,7 +962,7 @@ private bool ProcessReadBytes(int bytesRead) ...@@ -975,7 +962,7 @@ private bool ProcessReadBytes(int bytesRead)
{ {
if (bytesRead <= 0) if (bytesRead <= 0)
{ {
multiplexer.Trace("EOF", physicalName); Multiplexer.Trace("EOF", physicalName);
RecordConnectionFailed(ConnectionFailureType.SocketClosed); RecordConnectionFailed(ConnectionFailureType.SocketClosed);
return false; return false;
} }
...@@ -986,16 +973,16 @@ private bool ProcessReadBytes(int bytesRead) ...@@ -986,16 +973,16 @@ private bool ProcessReadBytes(int bytesRead)
VolatileWrapper.Write(ref firstUnansweredWriteTickCount, 0); VolatileWrapper.Write(ref firstUnansweredWriteTickCount, 0);
ioBufferBytes += bytesRead; ioBufferBytes += bytesRead;
multiplexer.Trace("More bytes available: " + bytesRead + " (" + ioBufferBytes + ")", physicalName); Multiplexer.Trace("More bytes available: " + bytesRead + " (" + ioBufferBytes + ")", physicalName);
int offset = 0, count = ioBufferBytes; int offset = 0, count = ioBufferBytes;
int handled = ProcessBuffer(ioBuffer, ref offset, ref count); int handled = ProcessBuffer(ioBuffer, ref offset, ref count);
multiplexer.Trace("Processed: " + handled, physicalName); Multiplexer.Trace("Processed: " + handled, physicalName);
if (handled != 0) if (handled != 0)
{ {
// read stuff // read stuff
if (count != 0) if (count != 0)
{ {
multiplexer.Trace("Copying remaining bytes: " + count, physicalName); Multiplexer.Trace("Copying remaining bytes: " + count, physicalName);
// if anything was left over, we need to copy it to // if anything was left over, we need to copy it to
// the start of the buffer so it can be used next time // the start of the buffer so it can be used next time
Buffer.BlockCopy(ioBuffer, offset, ioBuffer, 0, count); Buffer.BlockCopy(ioBuffer, offset, ioBuffer, 0, count);
...@@ -1013,12 +1000,11 @@ void ISocketCallback.Read() ...@@ -1013,12 +1000,11 @@ void ISocketCallback.Read()
do do
{ {
int space = EnsureSpaceAndComputeBytesToRead(); int space = EnsureSpaceAndComputeBytesToRead();
var tmp = netStream; int bytesRead = netStream?.Read(ioBuffer, ioBufferBytes, space) ?? 0;
int bytesRead = tmp == null ? 0 : tmp.Read(ioBuffer, ioBufferBytes, space);
if (!ProcessReadBytes(bytesRead)) return; // EOF if (!ProcessReadBytes(bytesRead)) return; // EOF
} while (socketToken.Available != 0); } while (socketToken.Available != 0);
multiplexer.Trace("Buffer exhausted", physicalName); Multiplexer.Trace("Buffer exhausted", physicalName);
// ^^^ note that the socket manager will call us again when there is something to do // ^^^ note that the socket manager will call us again when there is something to do
} }
catch (Exception ex) catch (Exception ex)
...@@ -1044,7 +1030,7 @@ private RawResult ReadArray(byte[] buffer, ref int offset, ref int count) ...@@ -1044,7 +1030,7 @@ private RawResult ReadArray(byte[] buffer, ref int offset, ref int count)
if (itemCount.HasValue) if (itemCount.HasValue)
{ {
long i64; long i64;
if (!itemCount.TryGetInt64(out i64)) throw ExceptionFactory.ConnectionFailure(multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid array length", bridge.ServerEndPoint); if (!itemCount.TryGetInt64(out i64)) throw ExceptionFactory.ConnectionFailure(Multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid array length", Bridge.ServerEndPoint);
int itemCountActual = checked((int)i64); int itemCountActual = checked((int)i64);
if (itemCountActual < 0) if (itemCountActual < 0)
...@@ -1075,7 +1061,7 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count) ...@@ -1075,7 +1061,7 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count)
if (prefix.HasValue) if (prefix.HasValue)
{ {
long i64; long i64;
if (!prefix.TryGetInt64(out i64)) throw ExceptionFactory.ConnectionFailure(multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid bulk string length", bridge.ServerEndPoint); if (!prefix.TryGetInt64(out i64)) throw ExceptionFactory.ConnectionFailure(Multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid bulk string length", Bridge.ServerEndPoint);
int bodySize = checked((int)i64); int bodySize = checked((int)i64);
if (bodySize < 0) if (bodySize < 0)
{ {
...@@ -1085,7 +1071,7 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count) ...@@ -1085,7 +1071,7 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count)
{ {
if (buffer[offset + bodySize] != '\r' || buffer[offset + bodySize + 1] != '\n') if (buffer[offset + bodySize] != '\r' || buffer[offset + bodySize + 1] != '\n')
{ {
throw ExceptionFactory.ConnectionFailure(multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid bulk string terminator", bridge.ServerEndPoint); throw ExceptionFactory.ConnectionFailure(Multiplexer.IncludeDetailInExceptions, ConnectionFailureType.ProtocolFailure, "Invalid bulk string terminator", Bridge.ServerEndPoint);
} }
var result = new RawResult(ResultType.BulkString, buffer, offset, bodySize); var result = new RawResult(ResultType.BulkString, buffer, offset, bodySize);
offset += bodySize + 2; offset += bodySize + 2;
...@@ -1096,7 +1082,6 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count) ...@@ -1096,7 +1082,6 @@ private RawResult ReadBulkString(byte[] buffer, ref int offset, ref int count)
return RawResult.Nil; return RawResult.Nil;
} }
private RawResult ReadLineTerminatedString(ResultType type, byte[] buffer, ref int offset, ref int count) private RawResult ReadLineTerminatedString(ResultType type, byte[] buffer, ref int offset, ref int count)
{ {
int max = offset + count - 2; int max = offset + count - 2;
...@@ -1145,14 +1130,13 @@ RawResult TryParseResult(byte[] buffer, ref int offset, ref int count) ...@@ -1145,14 +1130,13 @@ RawResult TryParseResult(byte[] buffer, ref int offset, ref int count)
public void CheckForStaleConnection(ref SocketManager.ManagerState managerState) public void CheckForStaleConnection(ref SocketManager.ManagerState managerState)
{ {
int firstUnansweredWrite; int firstUnansweredWrite = VolatileWrapper.Read(ref firstUnansweredWriteTickCount);
firstUnansweredWrite = VolatileWrapper.Read(ref firstUnansweredWriteTickCount);
DebugEmulateStaleConnection(ref firstUnansweredWrite); DebugEmulateStaleConnection(ref firstUnansweredWrite);
int now = Environment.TickCount; int now = Environment.TickCount;
if (firstUnansweredWrite != 0 && (now - firstUnansweredWrite) > this.multiplexer.RawConfig.ResponseTimeout) if (firstUnansweredWrite != 0 && (now - firstUnansweredWrite) > this.Multiplexer.RawConfig.ResponseTimeout)
{ {
this.RecordConnectionFailed(ConnectionFailureType.SocketFailure, ref managerState, origin: "CheckForStaleConnection"); this.RecordConnectionFailed(ConnectionFailureType.SocketFailure, ref managerState, origin: "CheckForStaleConnection");
} }
......
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -140,7 +137,7 @@ public int GetHashCode(ProfileContextCell obj) ...@@ -140,7 +137,7 @@ public int GetHashCode(ProfileContextCell obj)
private long lastCleanupSweep; private long lastCleanupSweep;
private ConcurrentDictionary<ProfileContextCell, ConcurrentProfileStorageCollection> profiledCommands; private ConcurrentDictionary<ProfileContextCell, ConcurrentProfileStorageCollection> profiledCommands;
public int ContextCount { get { return profiledCommands.Count; } } public int ContextCount => profiledCommands.Count;
public ProfileContextTracker() public ProfileContextTracker()
{ {
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
class ProfileStorage : IProfiledCommand class ProfileStorage : IProfiledCommand
{ {
#region IProfiledCommand Impl #region IProfiledCommand Impl
public EndPoint EndPoint public EndPoint EndPoint => Server.EndPoint;
{
get { return Server.EndPoint; }
}
public int Db public int Db => Message.Db;
{
get { return Message.Db; }
}
public string Command public string Command => Message.Command.ToString();
{
get { return Message.Command.ToString(); }
}
public CommandFlags Flags public CommandFlags Flags => Message.Flags;
{
get { return Message.Flags; }
}
public DateTime CommandCreated public DateTime CommandCreated => MessageCreatedDateTime;
{
get { return MessageCreatedDateTime; }
}
public TimeSpan CreationToEnqueued public TimeSpan CreationToEnqueued => TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp);
{
get { return TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp); }
}
public TimeSpan EnqueuedToSending public TimeSpan EnqueuedToSending => TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp);
{
get { return TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp); }
}
public TimeSpan SentToResponse public TimeSpan SentToResponse => TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp);
{
get { return TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp); }
}
public TimeSpan ResponseToCompletion public TimeSpan ResponseToCompletion => TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp);
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp); }
}
public TimeSpan ElapsedTime public TimeSpan ElapsedTime => TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp);
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp); }
}
public IProfiledCommand RetransmissionOf public IProfiledCommand RetransmissionOf => OriginalProfiling;
{
get { return OriginalProfiling; } public RetransmissionReasonType? RetransmissionReason { get; }
}
public RetransmissionReasonType? RetransmissionReason
{
get { return Reason; }
}
#endregion #endregion
public ProfileStorage NextElement { get; set; } public ProfileStorage NextElement { get; set; }
...@@ -79,7 +39,6 @@ public IProfiledCommand RetransmissionOf ...@@ -79,7 +39,6 @@ public IProfiledCommand RetransmissionOf
private Message Message; private Message Message;
private ServerEndPoint Server; private ServerEndPoint Server;
private ProfileStorage OriginalProfiling; private ProfileStorage OriginalProfiling;
private RetransmissionReasonType? Reason;
private DateTime MessageCreatedDateTime; private DateTime MessageCreatedDateTime;
private long MessageCreatedTimeStamp; private long MessageCreatedTimeStamp;
...@@ -95,7 +54,7 @@ private ProfileStorage(ConcurrentProfileStorageCollection pushTo, ServerEndPoint ...@@ -95,7 +54,7 @@ private ProfileStorage(ConcurrentProfileStorageCollection pushTo, ServerEndPoint
PushToWhenFinished = pushTo; PushToWhenFinished = pushTo;
OriginalProfiling = resentFor; OriginalProfiling = resentFor;
Server = server; Server = server;
Reason = reason; RetransmissionReason = reason;
} }
public static ProfileStorage NewWithContext(ConcurrentProfileStorageCollection pushTo, ServerEndPoint server) public static ProfileStorage NewWithContext(ConcurrentProfileStorageCollection pushTo, ServerEndPoint server)
...@@ -159,30 +118,17 @@ public void SetCompleted() ...@@ -159,30 +118,17 @@ public void SetCompleted()
public override string ToString() public override string ToString()
{ {
return return
string.Format( $@"EndPoint = {EndPoint}
@"EndPoint = {0} Db = {Db}
Db = {1} Command = {Command}
Command = {2} CommandCreated = {CommandCreated:u}
CommandCreated = {3:u} CreationToEnqueued = {CreationToEnqueued}
CreationToEnqueued = {4} EnqueuedToSending = {EnqueuedToSending}
EnqueuedToSending = {5} SentToResponse = {SentToResponse}
SentToResponse = {6} ResponseToCompletion = {ResponseToCompletion}
ResponseToCompletion = {7} ElapsedTime = {ElapsedTime}
ElapsedTime = {8} Flags = {Flags}
Flags = {9} RetransmissionOf = ({RetransmissionOf})";
RetransmissionOf = ({10})",
EndPoint,
Db,
Command,
CommandCreated,
CreationToEnqueued,
EnqueuedToSending,
SentToResponse,
ResponseToCompletion,
ElapsedTime,
Flags,
RetransmissionOf
);
} }
} }
} }
...@@ -11,7 +11,6 @@ internal struct RawResult ...@@ -11,7 +11,6 @@ internal struct RawResult
public static readonly RawResult Nil = new RawResult(); public static readonly RawResult Nil = new RawResult();
private static readonly byte[] emptyBlob = new byte[0]; private static readonly byte[] emptyBlob = new byte[0];
private readonly int offset, count; private readonly int offset, count;
private readonly ResultType resultType;
private Array arr; private Array arr;
public RawResult(ResultType resultType, byte[] buffer, int offset, int count) public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
{ {
...@@ -23,29 +22,30 @@ public RawResult(ResultType resultType, byte[] buffer, int offset, int count) ...@@ -23,29 +22,30 @@ public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
case ResultType.BulkString: case ResultType.BulkString:
break; break;
default: default:
throw new ArgumentOutOfRangeException("resultType"); throw new ArgumentOutOfRangeException(nameof(resultType));
} }
this.resultType = resultType; Type = resultType;
this.arr = buffer; arr = buffer;
this.offset = offset; this.offset = offset;
this.count = count; this.count = count;
} }
public RawResult(RawResult[] arr) public RawResult(RawResult[] arr)
{ {
if (arr == null) throw new ArgumentNullException("arr"); if (arr == null) throw new ArgumentNullException(nameof(arr));
this.resultType = ResultType.MultiBulk; Type = ResultType.MultiBulk;
this.offset = 0; offset = 0;
this.count = arr.Length; count = arr.Length;
this.arr = arr; this.arr = arr;
} }
public bool HasValue { get { return resultType != ResultType.None; } } public bool HasValue => Type != ResultType.None;
public bool IsError { get { return resultType == ResultType.Error; } } public bool IsError => Type == ResultType.Error;
public ResultType Type { get { return resultType; } } public ResultType Type { get; }
internal bool IsNull { get { return arr == null; } }
internal bool IsNull => arr == null;
public override string ToString() public override string ToString()
{ {
...@@ -53,23 +53,23 @@ public override string ToString() ...@@ -53,23 +53,23 @@ public override string ToString()
{ {
return "(null)"; return "(null)";
} }
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.Integer: case ResultType.Integer:
case ResultType.Error: case ResultType.Error:
return string.Format("{0}: {1}", resultType, GetString()); return $"{Type}: {GetString()}";
case ResultType.BulkString: case ResultType.BulkString:
return string.Format("{0}: {1} bytes", resultType, count); return $"{Type}: {count} bytes";
case ResultType.MultiBulk: case ResultType.MultiBulk:
return string.Format("{0}: {1} items", resultType, count); return $"{Type}: {count} items";
default: default:
return "(unknown)"; return "(unknown)";
} }
} }
internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode) internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode)
{ {
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.BulkString: case ResultType.BulkString:
...@@ -87,24 +87,24 @@ internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternM ...@@ -87,24 +87,24 @@ internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternM
} }
return default(RedisChannel); return default(RedisChannel);
default: default:
throw new InvalidCastException("Cannot convert to RedisChannel: " + resultType); throw new InvalidCastException("Cannot convert to RedisChannel: " + Type);
} }
} }
internal RedisKey AsRedisKey() internal RedisKey AsRedisKey()
{ {
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.BulkString: case ResultType.BulkString:
return (RedisKey)GetBlob(); return (RedisKey)GetBlob();
default: default:
throw new InvalidCastException("Cannot convert to RedisKey: " + resultType); throw new InvalidCastException("Cannot convert to RedisKey: " + Type);
} }
} }
internal RedisValue AsRedisValue() internal RedisValue AsRedisValue()
{ {
switch (resultType) switch (Type)
{ {
case ResultType.Integer: case ResultType.Integer:
long i64; long i64;
...@@ -114,12 +114,12 @@ internal RedisValue AsRedisValue() ...@@ -114,12 +114,12 @@ internal RedisValue AsRedisValue()
case ResultType.BulkString: case ResultType.BulkString:
return (RedisValue)GetBlob(); return (RedisValue)GetBlob();
} }
throw new InvalidCastException("Cannot convert to RedisValue: " + resultType); throw new InvalidCastException("Cannot convert to RedisValue: " + Type);
} }
internal unsafe bool IsEqual(byte[] expected) internal unsafe bool IsEqual(byte[] expected)
{ {
if (expected == null) throw new ArgumentNullException("expected"); if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length != count) return false; if (expected.Length != count) return false;
var actual = arr as byte[]; var actual = arr as byte[];
if (actual == null) return false; if (actual == null) return false;
...@@ -146,7 +146,7 @@ internal unsafe bool IsEqual(byte[] expected) ...@@ -146,7 +146,7 @@ internal unsafe bool IsEqual(byte[] expected)
internal bool AssertStarts(byte[] expected) internal bool AssertStarts(byte[] expected)
{ {
if (expected == null) throw new ArgumentNullException("expected"); if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length > count) return false; if (expected.Length > count) return false;
var actual = arr as byte[]; var actual = arr as byte[];
if (actual == null) return false; if (actual == null) return false;
...@@ -171,7 +171,7 @@ internal byte[] GetBlob() ...@@ -171,7 +171,7 @@ internal byte[] GetBlob()
internal bool GetBoolean() internal bool GetBoolean()
{ {
if (this.count != 1) throw new InvalidCastException(); if (count != 1) throw new InvalidCastException();
byte[] actual = arr as byte[]; byte[] actual = arr as byte[];
if (actual == null) throw new InvalidCastException(); if (actual == null) throw new InvalidCastException();
switch (actual[offset]) switch (actual[offset])
......
...@@ -16,7 +16,8 @@ internal RedisBase(ConnectionMultiplexer multiplexer, object asyncState) ...@@ -16,7 +16,8 @@ internal RedisBase(ConnectionMultiplexer multiplexer, object asyncState)
this.asyncState = asyncState; this.asyncState = asyncState;
} }
ConnectionMultiplexer IRedisAsync.Multiplexer { get { return multiplexer; } } ConnectionMultiplexer IRedisAsync.Multiplexer => multiplexer;
public virtual TimeSpan Ping(CommandFlags flags = CommandFlags.None) public virtual TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{ {
var msg = GetTimerMessage(flags); var msg = GetTimerMessage(flags);
...@@ -163,14 +164,14 @@ internal abstract class CursorEnumerable<T> : IEnumerable<T>, IScanningCursor ...@@ -163,14 +164,14 @@ internal abstract class CursorEnumerable<T> : IEnumerable<T>, IScanningCursor
protected CursorEnumerable(RedisBase redis, ServerEndPoint server, int db, int pageSize, long cursor, int pageOffset, CommandFlags flags) protected CursorEnumerable(RedisBase redis, ServerEndPoint server, int db, int pageSize, long cursor, int pageOffset, CommandFlags flags)
{ {
if (pageOffset < 0) throw new ArgumentOutOfRangeException("pageOffset"); if (pageOffset < 0) throw new ArgumentOutOfRangeException(nameof(pageOffset));
this.redis = redis; this.redis = redis;
this.server = server; this.server = server;
this.db = db; this.db = db;
this.pageSize = pageSize; this.pageSize = pageSize;
this.flags = flags; this.flags = flags;
this.initialCursor = cursor; initialCursor = cursor;
this.initialOffset = pageOffset; initialOffset = pageOffset;
} }
public IEnumerator<T> GetEnumerator() public IEnumerator<T> GetEnumerator()
...@@ -187,8 +188,8 @@ internal struct ScanResult ...@@ -187,8 +188,8 @@ internal struct ScanResult
public readonly T[] Values; public readonly T[] Values;
public ScanResult(long cursor, T[] values) public ScanResult(long cursor, T[] values)
{ {
this.Cursor = cursor; Cursor = cursor;
this.Values = values; Values = values;
} }
} }
...@@ -199,12 +200,12 @@ public ScanResult(long cursor, T[] values) ...@@ -199,12 +200,12 @@ public ScanResult(long cursor, T[] values)
protected ScanResult GetNextPageSync(IScanningCursor obj, long cursor) protected ScanResult GetNextPageSync(IScanningCursor obj, long cursor)
{ {
this.activeCursor = obj; activeCursor = obj;
return redis.ExecuteSync(CreateMessage(cursor), Processor, server); return redis.ExecuteSync(CreateMessage(cursor), Processor, server);
} }
protected Task<ScanResult> GetNextPageAsync(IScanningCursor obj, long cursor) protected Task<ScanResult> GetNextPageAsync(IScanningCursor obj, long cursor)
{ {
this.activeCursor = obj; activeCursor = obj;
return redis.ExecuteAsync(CreateMessage(cursor), Processor, server); return redis.ExecuteAsync(CreateMessage(cursor), Processor, server);
} }
protected ScanResult Wait(Task<ScanResult> pending) protected ScanResult Wait(Task<ScanResult> pending)
...@@ -217,21 +218,15 @@ class CursorEnumerator : IEnumerator<T>, IScanningCursor ...@@ -217,21 +218,15 @@ class CursorEnumerator : IEnumerator<T>, IScanningCursor
private CursorEnumerable<T> parent; private CursorEnumerable<T> parent;
public CursorEnumerator(CursorEnumerable<T> parent) public CursorEnumerator(CursorEnumerable<T> parent)
{ {
if (parent == null) throw new ArgumentNullException("parent"); if (parent == null) throw new ArgumentNullException(nameof(parent));
this.parent = parent; this.parent = parent;
Reset(); Reset();
} }
public T Current public T Current => page[pageIndex];
{
get { return page[pageIndex]; }
}
void IDisposable.Dispose() { parent = null; state = State.Disposed; } void IDisposable.Dispose() { parent = null; state = State.Disposed; }
object System.Collections.IEnumerator.Current object System.Collections.IEnumerator.Current => page[pageIndex];
{
get { return page[pageIndex]; }
}
private void LoadNextPageAsync() private void LoadNextPageAsync()
{ {
...@@ -322,34 +317,23 @@ public void Reset() ...@@ -322,34 +317,23 @@ public void Reset()
pending = null; pending = null;
} }
long IScanningCursor.Cursor long IScanningCursor.Cursor => currentCursor;
{
get { return currentCursor; }
}
int IScanningCursor.PageSize int IScanningCursor.PageSize => parent.pageSize;
{
get { return parent.pageSize; }
}
int IScanningCursor.PageOffset int IScanningCursor.PageOffset => pageIndex;
{
get { return pageIndex; }
}
} }
long IScanningCursor.Cursor long IScanningCursor.Cursor
{ {
get { var tmp = activeCursor; return tmp == null ? initialCursor : tmp.Cursor; } get { var tmp = activeCursor; return tmp?.Cursor ?? initialCursor; }
} }
int IScanningCursor.PageSize int IScanningCursor.PageSize => pageSize;
{
get { return pageSize; }
}
int IScanningCursor.PageOffset int IScanningCursor.PageOffset
{ {
get { var tmp = activeCursor; return tmp == null ? initialOffset : tmp.PageOffset; } get { var tmp = activeCursor; return tmp?.PageOffset ?? initialOffset; }
} }
} }
} }
......
...@@ -8,7 +8,6 @@ namespace StackExchange.Redis ...@@ -8,7 +8,6 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public struct RedisChannel : IEquatable<RedisChannel> public struct RedisChannel : IEquatable<RedisChannel>
{ {
internal static readonly RedisChannel[] EmptyArray = new RedisChannel[0]; internal static readonly RedisChannel[] EmptyArray = new RedisChannel[0];
private readonly byte[] value; private readonly byte[] value;
...@@ -30,7 +29,7 @@ public RedisChannel(string value, PatternMode mode) : this(value == null ? null ...@@ -30,7 +29,7 @@ public RedisChannel(string value, PatternMode mode) : this(value == null ? null
private RedisChannel(byte[] value, bool isPatternBased) private RedisChannel(byte[] value, bool isPatternBased)
{ {
this.value = value; this.value = value;
this.IsPatternBased = isPatternBased; IsPatternBased = isPatternBased;
} }
private static bool DeterminePatternBased(byte[] value, PatternMode mode) private static bool DeterminePatternBased(byte[] value, PatternMode mode)
{ {
...@@ -41,27 +40,18 @@ private static bool DeterminePatternBased(byte[] value, PatternMode mode) ...@@ -41,27 +40,18 @@ private static bool DeterminePatternBased(byte[] value, PatternMode mode)
case PatternMode.Literal: return false; case PatternMode.Literal: return false;
case PatternMode.Pattern: return true; case PatternMode.Pattern: return true;
default: default:
throw new ArgumentOutOfRangeException("mode"); throw new ArgumentOutOfRangeException(nameof(mode));
} }
} }
/// <summary> /// <summary>
/// Indicates whether the channel-name is either null or a zero-length value /// Indicates whether the channel-name is either null or a zero-length value
/// </summary> /// </summary>
public bool IsNullOrEmpty public bool IsNullOrEmpty => value == null || value.Length == 0;
{
get
{
return value == null || value.Length == 0;
}
}
internal bool IsNull internal bool IsNull => value == null;
{
get { return value == null; }
}
internal byte[] Value { get { return value; } } internal byte[] Value => value;
/// <summary> /// <summary>
/// Indicate whether two channel names are not equal /// Indicate whether two channel names are not equal
...@@ -150,15 +140,15 @@ public override bool Equals(object obj) ...@@ -150,15 +140,15 @@ public override bool Equals(object obj)
{ {
if (obj is RedisChannel) if (obj is RedisChannel)
{ {
return RedisValue.Equals(this.value, ((RedisChannel)obj).value); return RedisValue.Equals(value, ((RedisChannel)obj).value);
} }
if (obj is string) if (obj is string)
{ {
return RedisValue.Equals(this.value, Encoding.UTF8.GetBytes((string)obj)); return RedisValue.Equals(value, Encoding.UTF8.GetBytes((string)obj));
} }
if (obj is byte[]) if (obj is byte[])
{ {
return RedisValue.Equals(this.value, (byte[])obj); return RedisValue.Equals(value, (byte[])obj);
} }
return false; return false;
} }
...@@ -168,8 +158,8 @@ public override bool Equals(object obj) ...@@ -168,8 +158,8 @@ public override bool Equals(object obj)
/// </summary> /// </summary>
public bool Equals(RedisChannel other) public bool Equals(RedisChannel other)
{ {
return this.IsPatternBased == other.IsPatternBased && return IsPatternBased == other.IsPatternBased &&
RedisValue.Equals(this.value, other.value); RedisValue.Equals(value, other.value);
} }
/// <summary> /// <summary>
...@@ -177,7 +167,7 @@ public bool Equals(RedisChannel other) ...@@ -177,7 +167,7 @@ public bool Equals(RedisChannel other)
/// </summary> /// </summary>
public override int GetHashCode() public override int GetHashCode()
{ {
return RedisValue.GetHashCode(this.value) + (IsPatternBased ? 1 : 0); return RedisValue.GetHashCode(value) + (IsPatternBased ? 1 : 0);
} }
/// <summary> /// <summary>
...@@ -204,7 +194,7 @@ internal void AssertNotNull() ...@@ -204,7 +194,7 @@ internal void AssertNotNull()
internal RedisChannel Clone() internal RedisChannel Clone()
{ {
byte[] clone = value == null ? null : (byte[])value.Clone(); byte[] clone = (byte[]) value?.Clone();
return clone; return clone;
} }
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -9,9 +9,7 @@ namespace StackExchange.Redis ...@@ -9,9 +9,7 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class RedisErrorEventArgs : EventArgs, ICompletable public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{ {
private readonly EndPoint endpoint;
private readonly EventHandler<RedisErrorEventArgs> handler; private readonly EventHandler<RedisErrorEventArgs> handler;
private readonly string message;
private readonly object sender; private readonly object sender;
internal RedisErrorEventArgs( internal RedisErrorEventArgs(
EventHandler<RedisErrorEventArgs> handler, object sender, EventHandler<RedisErrorEventArgs> handler, object sender,
...@@ -19,29 +17,28 @@ public sealed class RedisErrorEventArgs : EventArgs, ICompletable ...@@ -19,29 +17,28 @@ public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.message = message; Message = message;
this.endpoint = endpoint; EndPoint = endpoint;
} }
/// <summary> /// <summary>
/// The origin of the message /// The origin of the message
/// </summary> /// </summary>
public EndPoint EndPoint { get { return endpoint; } } public EndPoint EndPoint { get; }
/// <summary> /// <summary>
/// The message from the server /// The message from the server
/// </summary> /// </summary>
public string Message { get { return message; } } public string Message { get; }
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, error: ").Append(message); sb.Append("event, error: ").Append(Message);
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
{ {
return ConnectionMultiplexer.TryCompleteHandler(handler, sender, this, isAsync); return ConnectionMultiplexer.TryCompleteHandler(handler, sender, this, isAsync);
} }
} }
} }
...@@ -34,119 +34,120 @@ public struct RedisFeatures ...@@ -34,119 +34,120 @@ public struct RedisFeatures
/// </summary> /// </summary>
public RedisFeatures(Version version) public RedisFeatures(Version version)
{ {
if (version == null) throw new ArgumentNullException("version"); if (version == null) throw new ArgumentNullException(nameof(version));
this.version = version; this.version = version;
} }
/// <summary> /// <summary>
/// Does BITOP / BITCOUNT exist? /// Does BITOP / BITCOUNT exist?
/// </summary> /// </summary>
public bool BitwiseOperations { get { return Version >= v2_5_10; } } public bool BitwiseOperations => Version >= v2_5_10;
/// <summary> /// <summary>
/// Is CLIENT SETNAME available? /// Is CLIENT SETNAME available?
/// </summary> /// </summary>
public bool ClientName { get { return Version >= v2_6_9; } } public bool ClientName => Version >= v2_6_9;
/// <summary> /// <summary>
/// Does EXEC support EXECABORT if there are errors? /// Does EXEC support EXECABORT if there are errors?
/// </summary> /// </summary>
public bool ExecAbort { get { return Version >= v2_6_5 && Version != v2_9_5; } } public bool ExecAbort => Version >= v2_6_5 && Version != v2_9_5;
/// <summary> /// <summary>
/// Can EXPIRE be used to set expiration on a key that is already volatile (i.e. has an expiration)? /// Can EXPIRE be used to set expiration on a key that is already volatile (i.e. has an expiration)?
/// </summary> /// </summary>
public bool ExpireOverwrite { get { return Version >= v2_1_3; } } public bool ExpireOverwrite => Version >= v2_1_3;
/// <summary> /// <summary>
/// Does HDEL support varadic usage? /// Does HDEL support varadic usage?
/// </summary> /// </summary>
public bool HashVaradicDelete { get { return Version >= v2_4_0; } } public bool HashVaradicDelete => Version >= v2_4_0;
/// <summary> /// <summary>
/// Does INCRBYFLOAT / HINCRBYFLOAT exist? /// Does INCRBYFLOAT / HINCRBYFLOAT exist?
/// </summary> /// </summary>
public bool IncrementFloat { get { return Version >= v2_5_7; } } public bool IncrementFloat => Version >= v2_5_7;
/// <summary> /// <summary>
/// Does INFO support sections? /// Does INFO support sections?
/// </summary> /// </summary>
public bool InfoSections { get { return Version >= v2_8_0; } } public bool InfoSections => Version >= v2_8_0;
/// <summary> /// <summary>
/// Is LINSERT available? /// Is LINSERT available?
/// </summary> /// </summary>
public bool ListInsert { get { return Version >= v2_1_1; } } public bool ListInsert => Version >= v2_1_1;
/// <summary> /// <summary>
/// Indicates whether PEXPIRE and PTTL are supported /// Indicates whether PEXPIRE and PTTL are supported
/// </summary> /// </summary>
public bool MillisecondExpiry { get { return Version >= v2_6_0; } } public bool MillisecondExpiry => Version >= v2_6_0;
/// <summary> /// <summary>
/// Does SRANDMEMBER support "count"? /// Does SRANDMEMBER support "count"?
/// </summary> /// </summary>
public bool MultipleRandom { get { return Version >= v2_5_14; } } public bool MultipleRandom => Version >= v2_5_14;
/// <summary> /// <summary>
/// Is the PERSIST operation supported? /// Is the PERSIST operation supported?
/// </summary> /// </summary>
public bool Persist { get { return Version >= v2_1_2; } } public bool Persist => Version >= v2_1_2;
/// <summary> /// <summary>
/// Is RPUSHX and LPUSHX available? /// Is RPUSHX and LPUSHX available?
/// </summary> /// </summary>
public bool PushIfNotExists { get { return Version >= v2_1_1; } } public bool PushIfNotExists => Version >= v2_1_1;
/// <summary> /// <summary>
/// Are cursor-based scans available? /// Are cursor-based scans available?
/// </summary> /// </summary>
public bool Scan { get { return Version >= v2_8_0; } } public bool Scan => Version >= v2_8_0;
/// <summary> /// <summary>
/// Does EVAL / EVALSHA / etc exist? /// Does EVAL / EVALSHA / etc exist?
/// </summary> /// </summary>
public bool Scripting { get { return Version >= v2_5_7; } } public bool Scripting => Version >= v2_5_7;
/// <summary> /// <summary>
/// Does SET have the EX|PX|NX|XX extensions? /// Does SET have the EX|PX|NX|XX extensions?
/// </summary> /// </summary>
public bool SetConditional { get { return Version >= v2_6_12; } } public bool SetConditional => Version >= v2_6_12;
/// <summary> /// <summary>
/// Does SADD support varadic usage? /// Does SADD support varadic usage?
/// </summary> /// </summary>
public bool SetVaradicAddRemove { get { return Version >= v2_4_0; } } public bool SetVaradicAddRemove => Version >= v2_4_0;
/// <summary> /// <summary>
/// Is STRLEN available? /// Is STRLEN available?
/// </summary> /// </summary>
public bool StringLength { get { return Version >= v2_1_2; } } public bool StringLength => Version >= v2_1_2;
/// <summary> /// <summary>
/// Is SETRANGE available? /// Is SETRANGE available?
/// </summary> /// </summary>
public bool StringSetRange { get { return Version >= v2_1_8; } } public bool StringSetRange => Version >= v2_1_8;
/// <summary> /// <summary>
/// Does TIME exist? /// Does TIME exist?
/// </summary> /// </summary>
public bool Time { get { return Version >= v2_6_0; } } public bool Time => Version >= v2_6_0;
/// <summary> /// <summary>
/// Are Lua changes to the calling database transparent to the calling client? /// Are Lua changes to the calling database transparent to the calling client?
/// </summary> /// </summary>
public bool ScriptingDatabaseSafe { get { return Version >= v2_8_12; } } public bool ScriptingDatabaseSafe => Version >= v2_8_12;
/// <summary> /// <summary>
/// Is PFCOUNT supported on slaves? /// Is PFCOUNT supported on slaves?
/// </summary> /// </summary>
public bool HyperLogLogCountSlaveSafe { get { return Version >= v2_8_18; } } public bool HyperLogLogCountSlaveSafe => Version >= v2_8_18;
/// <summary> /// <summary>
/// The Redis version of the server /// The Redis version of the server
/// </summary> /// </summary>
public Version Version { get { return version ?? v2_0_0; } } public Version Version => version ?? v2_0_0;
/// <summary> /// <summary>
/// Create a string representation of the available features /// Create a string representation of the available features
/// </summary> /// </summary>
......
...@@ -21,10 +21,7 @@ internal RedisKey AsPrefix() ...@@ -21,10 +21,7 @@ internal RedisKey AsPrefix()
{ {
return new RedisKey((byte[])this, null); return new RedisKey((byte[])this, null);
} }
internal bool IsNull internal bool IsNull => keyPrefix == null && keyValue == null;
{
get { return keyPrefix == null && keyValue == null; }
}
internal bool IsEmpty internal bool IsEmpty
{ {
...@@ -37,8 +34,8 @@ internal bool IsEmpty ...@@ -37,8 +34,8 @@ internal bool IsEmpty
} }
} }
internal byte[] KeyPrefix { get { return keyPrefix; } } internal byte[] KeyPrefix => keyPrefix;
internal object KeyValue { get { return keyValue; } } internal object KeyValue => keyValue;
/// <summary> /// <summary>
/// Indicate whether two keys are not equal /// Indicate whether two keys are not equal
...@@ -164,7 +161,7 @@ private static bool CompositeEquals(byte[] keyPrefix0, object keyValue0, byte[] ...@@ -164,7 +161,7 @@ private static bool CompositeEquals(byte[] keyPrefix0, object keyValue0, byte[]
/// </summary> /// </summary>
public override int GetHashCode() public override int GetHashCode()
{ {
int chk0 = (keyPrefix == null) ? 0 : RedisValue.GetHashCode(this.keyPrefix), int chk0 = keyPrefix == null ? 0 : RedisValue.GetHashCode(this.keyPrefix),
chk1 = keyValue is string ? keyValue.GetHashCode() : RedisValue.GetHashCode((byte[])keyValue); chk1 = keyValue is string ? keyValue.GetHashCode() : RedisValue.GetHashCode((byte[])keyValue);
return unchecked((17 * chk0) + chk1); return unchecked((17 * chk0) + chk1);
...@@ -272,11 +269,11 @@ internal static byte[] ConcatenateBytes(byte[] a, object b, byte[] c) ...@@ -272,11 +269,11 @@ internal static byte[] ConcatenateBytes(byte[] a, object b, byte[] c)
return (byte[])b; return (byte[])b;
} }
int aLen = a == null ? 0 : a.Length, int aLen = a?.Length ?? 0,
bLen = b == null ? 0 : (b is string bLen = b == null ? 0 : (b is string
? Encoding.UTF8.GetByteCount((string)b) ? Encoding.UTF8.GetByteCount((string)b)
: ((byte[])b).Length), : ((byte[])b).Length),
cLen = c == null ? 0 : c.Length; cLen = c?.Length ?? 0;
byte[] result = new byte[aLen + bLen + cLen]; byte[] result = new byte[aLen + bLen + cLen];
if (aLen != 0) Buffer.BlockCopy(a, 0, result, 0, aLen); if (aLen != 0) Buffer.BlockCopy(a, 0, result, 0, aLen);
......
...@@ -102,7 +102,7 @@ internal static RedisValue Get(Bitwise operation) ...@@ -102,7 +102,7 @@ internal static RedisValue Get(Bitwise operation)
case Bitwise.Or: return OR; case Bitwise.Or: return OR;
case Bitwise.Xor: return XOR; case Bitwise.Xor: return XOR;
case Bitwise.Not: return NOT; case Bitwise.Not: return NOT;
default: throw new ArgumentOutOfRangeException("operation"); default: throw new ArgumentOutOfRangeException(nameof(operation));
} }
} }
} }
......
...@@ -38,7 +38,7 @@ internal static RedisResult TryCreate(PhysicalConnection connection, RawResult r ...@@ -38,7 +38,7 @@ internal static RedisResult TryCreate(PhysicalConnection connection, RawResult r
} }
} catch(Exception ex) } catch(Exception ex)
{ {
if(connection != null) connection.OnInternalError(ex); connection?.OnInternalError(ex);
return null; // will be logged as a protocol fail by the processor return null; // will be logged as a protocol fail by the processor
} }
} }
...@@ -181,7 +181,7 @@ public override bool IsNull ...@@ -181,7 +181,7 @@ public override bool IsNull
private readonly RedisResult[] value; private readonly RedisResult[] value;
public ArrayRedisResult(RedisResult[] value) public ArrayRedisResult(RedisResult[] value)
{ {
if (value == null) throw new ArgumentNullException("value"); if (value == null) throw new ArgumentNullException(nameof(value));
this.value = value; this.value = value;
} }
public override string ToString() public override string ToString()
...@@ -282,13 +282,10 @@ private sealed class ErrorRedisResult : RedisResult ...@@ -282,13 +282,10 @@ private sealed class ErrorRedisResult : RedisResult
private readonly string value; private readonly string value;
public ErrorRedisResult(string value) public ErrorRedisResult(string value)
{ {
if (value == null) throw new ArgumentNullException("value"); if (value == null) throw new ArgumentNullException(nameof(value));
this.value = value; this.value = value;
} }
public override bool IsNull public override bool IsNull => value == null;
{
get { return value == null; }
}
public override string ToString() { return value; } public override string ToString() { return value; }
internal override bool AsBoolean() { throw new RedisServerException(value); } internal override bool AsBoolean() { throw new RedisServerException(value); }
...@@ -340,10 +337,7 @@ public SingleRedisResult(RedisValue value) ...@@ -340,10 +337,7 @@ public SingleRedisResult(RedisValue value)
this.value = value; this.value = value;
} }
public override bool IsNull public override bool IsNull => value.IsNull;
{
get { return value.IsNull; }
}
public override string ToString() { return value.ToString(); } public override string ToString() { return value.ToString(); }
internal override bool AsBoolean() { return (bool)value; } internal override bool AsBoolean() { return (bool)value; }
......
...@@ -16,25 +16,19 @@ internal sealed partial class RedisServer : RedisBase, IServer ...@@ -16,25 +16,19 @@ internal sealed partial class RedisServer : RedisBase, IServer
internal RedisServer(ConnectionMultiplexer multiplexer, ServerEndPoint server, object asyncState) : base(multiplexer, asyncState) internal RedisServer(ConnectionMultiplexer multiplexer, ServerEndPoint server, object asyncState) : base(multiplexer, asyncState)
{ {
if (server == null) throw new ArgumentNullException("server"); if (server == null) throw new ArgumentNullException(nameof(server));
this.server = server; this.server = server;
} }
public ClusterConfiguration ClusterConfiguration public ClusterConfiguration ClusterConfiguration => server.ClusterConfiguration;
{
get { return server.ClusterConfiguration; }
}
public EndPoint EndPoint { get { return server.EndPoint; } } public EndPoint EndPoint => server.EndPoint;
public RedisFeatures Features public RedisFeatures Features => server.GetFeatures();
{
get { return server.GetFeatures(); }
}
public bool IsConnected { get { return server.IsConnected; } } public bool IsConnected => server.IsConnected;
public bool IsSlave { get { return server.IsSlave; } } public bool IsSlave => server.IsSlave;
public bool AllowSlaveWrites public bool AllowSlaveWrites
{ {
...@@ -42,9 +36,9 @@ public bool AllowSlaveWrites ...@@ -42,9 +36,9 @@ public bool AllowSlaveWrites
set { server.AllowSlaveWrites = value; } set { server.AllowSlaveWrites = value; }
} }
public ServerType ServerType { get { return server.ServerType; } } public ServerType ServerType => server.ServerType;
public Version Version { get { return server.Version; } } public Version Version => server.Version;
public void ClientKill(EndPoint endpoint, CommandFlags flags = CommandFlags.None) public void ClientKill(EndPoint endpoint, CommandFlags flags = CommandFlags.None)
{ {
...@@ -71,8 +65,10 @@ public Task<long> ClientKillAsync(long? id = null, ClientType? clientType = null ...@@ -71,8 +65,10 @@ public Task<long> ClientKillAsync(long? id = null, ClientType? clientType = null
} }
Message GetClientKillMessage(EndPoint endpoint, long? id, ClientType? clientType, bool skipMe, CommandFlags flags) Message GetClientKillMessage(EndPoint endpoint, long? id, ClientType? clientType, bool skipMe, CommandFlags flags)
{ {
List<RedisValue> parts = new List<RedisValue>(9); List<RedisValue> parts = new List<RedisValue>(9)
parts.Add(RedisLiterals.KILL); {
RedisLiterals.KILL
};
if(id != null) if(id != null)
{ {
parts.Add(RedisLiterals.ID); parts.Add(RedisLiterals.ID);
...@@ -93,7 +89,7 @@ Message GetClientKillMessage(EndPoint endpoint, long? id, ClientType? clientType ...@@ -93,7 +89,7 @@ Message GetClientKillMessage(EndPoint endpoint, long? id, ClientType? clientType
parts.Add(RedisLiterals.pubsub); parts.Add(RedisLiterals.pubsub);
break; break;
default: default:
throw new ArgumentOutOfRangeException("clientType"); throw new ArgumentOutOfRangeException(nameof(clientType));
} }
parts.Add(id.Value); parts.Add(id.Value);
} }
...@@ -281,7 +277,7 @@ IEnumerable<RedisKey> IServer.Keys(int database, RedisValue pattern, int pageSiz ...@@ -281,7 +277,7 @@ IEnumerable<RedisKey> IServer.Keys(int database, RedisValue pattern, int pageSiz
public IEnumerable<RedisKey> Keys(int database = 0, RedisValue pattern = default(RedisValue), int pageSize = CursorUtils.DefaultPageSize, long cursor = CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None) public IEnumerable<RedisKey> Keys(int database = 0, RedisValue pattern = default(RedisValue), int pageSize = CursorUtils.DefaultPageSize, long cursor = CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
{ {
if (pageSize <= 0) throw new ArgumentOutOfRangeException("pageSize"); if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
if (CursorUtils.IsNil(pattern)) pattern = RedisLiterals.Wildcard; if (CursorUtils.IsNil(pattern)) pattern = RedisLiterals.Wildcard;
if (multiplexer.CommandMap.IsAvailable(RedisCommand.SCAN)) if (multiplexer.CommandMap.IsAvailable(RedisCommand.SCAN))
...@@ -399,7 +395,7 @@ public void Shutdown(ShutdownMode shutdownMode = ShutdownMode.Default, CommandFl ...@@ -399,7 +395,7 @@ public void Shutdown(ShutdownMode shutdownMode = ShutdownMode.Default, CommandFl
msg = Message.Create(-1, flags, RedisCommand.SHUTDOWN, RedisLiterals.NOSAVE); msg = Message.Create(-1, flags, RedisCommand.SHUTDOWN, RedisLiterals.NOSAVE);
break; break;
default: default:
throw new ArgumentOutOfRangeException("shutdownMode"); throw new ArgumentOutOfRangeException(nameof(shutdownMode));
} }
try try
{ {
...@@ -638,7 +634,7 @@ Message GetSaveMessage(SaveType type, CommandFlags flags = CommandFlags.None) ...@@ -638,7 +634,7 @@ Message GetSaveMessage(SaveType type, CommandFlags flags = CommandFlags.None)
#pragma warning disable 0618 #pragma warning disable 0618
case SaveType.ForegroundSave: return Message.Create(-1, flags, RedisCommand.SAVE); case SaveType.ForegroundSave: return Message.Create(-1, flags, RedisCommand.SAVE);
#pragma warning restore 0618 #pragma warning restore 0618
default: throw new ArgumentOutOfRangeException("type"); default: throw new ArgumentOutOfRangeException(nameof(type));
} }
} }
...@@ -651,7 +647,7 @@ ResultProcessor<bool> GetSaveResultProcessor(SaveType type) ...@@ -651,7 +647,7 @@ ResultProcessor<bool> GetSaveResultProcessor(SaveType type)
#pragma warning disable 0618 #pragma warning disable 0618
case SaveType.ForegroundSave: return ResultProcessor.DemandOK; case SaveType.ForegroundSave: return ResultProcessor.DemandOK;
#pragma warning restore 0618 #pragma warning restore 0618
default: throw new ArgumentOutOfRangeException("type"); default: throw new ArgumentOutOfRangeException(nameof(type));
} }
} }
...@@ -719,10 +715,7 @@ protected override Message CreateMessage(long cursor) ...@@ -719,10 +715,7 @@ protected override Message CreateMessage(long cursor)
} }
} }
} }
protected override ResultProcessor<ScanResult> Processor protected override ResultProcessor<ScanResult> Processor => processor;
{
get { return processor; }
}
public static readonly ResultProcessor<ScanResult> processor = new KeysResultProcessor(); public static readonly ResultProcessor<ScanResult> processor = new KeysResultProcessor();
private class KeysResultProcessor : ResultProcessor<ScanResult> private class KeysResultProcessor : ResultProcessor<ScanResult>
......
...@@ -6,10 +6,8 @@ ...@@ -6,10 +6,8 @@
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
partial class ConnectionMultiplexer partial class ConnectionMultiplexer
{ {
private readonly Dictionary<RedisChannel, Subscription> subscriptions = new Dictionary<RedisChannel, Subscription>(); private readonly Dictionary<RedisChannel, Subscription> subscriptions = new Dictionary<RedisChannel, Subscription>();
internal static bool TryCompleteHandler<T>(EventHandler<T> handler, object sender, T args, bool isAsync) where T : EventArgs internal static bool TryCompleteHandler<T>(EventHandler<T> handler, object sender, T args, bool isAsync) where T : EventArgs
...@@ -291,14 +289,14 @@ public override Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None) ...@@ -291,14 +289,14 @@ public override Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None)
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{ {
if (channel.IsNullOrEmpty) throw new ArgumentNullException("channel"); if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message); var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message);
return ExecuteSync(msg, ResultProcessor.Int64); return ExecuteSync(msg, ResultProcessor.Int64);
} }
public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{ {
if (channel.IsNullOrEmpty) throw new ArgumentNullException("channel"); if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message); var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message);
return ExecuteAsync(msg, ResultProcessor.Int64); return ExecuteAsync(msg, ResultProcessor.Int64);
} }
...@@ -312,7 +310,7 @@ public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> han ...@@ -312,7 +310,7 @@ public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> han
public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None) public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None)
{ {
if (channel.IsNullOrEmpty) throw new ArgumentNullException("channel"); if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
return multiplexer.AddSubscription(channel, handler, flags, asyncState); return multiplexer.AddSubscription(channel, handler, flags, asyncState);
} }
...@@ -320,7 +318,7 @@ public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue ...@@ -320,7 +318,7 @@ public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue
public EndPoint SubscribedEndpoint(RedisChannel channel) public EndPoint SubscribedEndpoint(RedisChannel channel)
{ {
var server = multiplexer.GetSubscribedServer(channel); var server = multiplexer.GetSubscribedServer(channel);
return server == null ? null : server.EndPoint; return server?.EndPoint;
} }
public void Unsubscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None) public void Unsubscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
...@@ -342,7 +340,7 @@ public Task UnsubscribeAllAsync(CommandFlags flags = CommandFlags.None) ...@@ -342,7 +340,7 @@ public Task UnsubscribeAllAsync(CommandFlags flags = CommandFlags.None)
public Task UnsubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None) public Task UnsubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
{ {
if (channel.IsNullOrEmpty) throw new ArgumentNullException("channel"); if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
return multiplexer.RemoveSubscription(channel, handler, flags, asyncState); return multiplexer.RemoveSubscription(channel, handler, flags, asyncState);
} }
} }
......
...@@ -23,7 +23,7 @@ public RedisTransaction(RedisDatabase wrapped, object asyncState) : base(wrapped ...@@ -23,7 +23,7 @@ public RedisTransaction(RedisDatabase wrapped, object asyncState) : base(wrapped
public ConditionResult AddCondition(Condition condition) public ConditionResult AddCondition(Condition condition)
{ {
if (condition == null) throw new ArgumentNullException("condition"); if (condition == null) throw new ArgumentNullException(nameof(condition));
var commandMap = multiplexer.CommandMap; var commandMap = multiplexer.CommandMap;
if (conditions == null) if (conditions == null)
...@@ -146,7 +146,8 @@ public bool WasQueued ...@@ -146,7 +146,8 @@ public bool WasQueued
set { wasQueued = value; } set { wasQueued = value; }
} }
public Message Wrapped { get { return wrapped; } } public Message Wrapped => wrapped;
internal override void WriteImpl(PhysicalConnection physical) internal override void WriteImpl(PhysicalConnection physical)
{ {
wrapped.WriteImpl(physical); wrapped.WriteImpl(physical);
...@@ -189,12 +190,9 @@ public TransactionMessage(int db, CommandFlags flags, List<ConditionResult> cond ...@@ -189,12 +190,9 @@ public TransactionMessage(int db, CommandFlags flags, List<ConditionResult> cond
this.conditions = (conditions == null || conditions.Count == 0) ? NixConditions : conditions.ToArray(); this.conditions = (conditions == null || conditions.Count == 0) ? NixConditions : conditions.ToArray();
} }
public QueuedMessage[] InnerOperations { get { return operations; } } public QueuedMessage[] InnerOperations => operations;
public bool IsAborted public bool IsAborted => command != RedisCommand.EXEC;
{
get { return command != RedisCommand.EXEC; }
}
public override void AppendStormLog(StringBuilder sb) public override void AppendStormLog(StringBuilder sb)
{ {
......
...@@ -16,10 +16,6 @@ public struct RedisValue : IEquatable<RedisValue>, IComparable<RedisValue>, ICom ...@@ -16,10 +16,6 @@ public struct RedisValue : IEquatable<RedisValue>, IComparable<RedisValue>, ICom
static readonly byte[] EmptyByteArr = new byte[0]; static readonly byte[] EmptyByteArr = new byte[0];
private static readonly RedisValue
@null = new RedisValue(0, null),
emptyString = new RedisValue(0, EmptyByteArr);
private static readonly byte[] IntegerSentinel = new byte[0]; private static readonly byte[] IntegerSentinel = new byte[0];
private readonly byte[] valueBlob; private readonly byte[] valueBlob;
...@@ -36,44 +32,32 @@ private RedisValue(long valueInt64, byte[] valueBlob) ...@@ -36,44 +32,32 @@ private RedisValue(long valueInt64, byte[] valueBlob)
/// <summary> /// <summary>
/// Represents the string <c>""</c> /// Represents the string <c>""</c>
/// </summary> /// </summary>
public static RedisValue EmptyString { get { return emptyString; } } public static RedisValue EmptyString { get; } = new RedisValue(0, EmptyByteArr);
/// <summary> /// <summary>
/// A null value /// A null value
/// </summary> /// </summary>
public static RedisValue Null { get { return @null; } } public static RedisValue Null { get; } = new RedisValue(0, null);
/// <summary> /// <summary>
/// Indicates whether the value is a primitive integer /// Indicates whether the value is a primitive integer
/// </summary> /// </summary>
public bool IsInteger { get { return valueBlob == IntegerSentinel; } } public bool IsInteger => valueBlob == IntegerSentinel;
/// <summary> /// <summary>
/// Indicates whether the value should be considered a null value /// Indicates whether the value should be considered a null value
/// </summary> /// </summary>
public bool IsNull { get { return valueBlob == null; } } public bool IsNull => valueBlob == null;
/// <summary> /// <summary>
/// Indicates whether the value is either null or a zero-length value /// Indicates whether the value is either null or a zero-length value
/// </summary> /// </summary>
public bool IsNullOrEmpty public bool IsNullOrEmpty => valueBlob == null || (valueBlob.Length == 0 && !(valueBlob == IntegerSentinel));
{
get
{
return valueBlob == null || (valueBlob.Length == 0 && !(valueBlob == IntegerSentinel));
}
}
/// <summary> /// <summary>
/// Indicates whether the value is greater than zero-length /// Indicates whether the value is greater than zero-length
/// </summary> /// </summary>
public bool HasValue public bool HasValue => valueBlob != null && valueBlob.Length > 0;
{
get
{
return valueBlob != null && valueBlob.Length > 0;
}
}
/// <summary> /// <summary>
/// Indicates whether two RedisValue values are equivalent /// Indicates whether two RedisValue values are equivalent
...@@ -345,7 +329,7 @@ int IComparable.CompareTo(object obj) ...@@ -345,7 +329,7 @@ int IComparable.CompareTo(object obj)
/// </summary> /// </summary>
public static implicit operator RedisValue(int? value) public static implicit operator RedisValue(int? value)
{ {
return value == null ? @null : (RedisValue)value.GetValueOrDefault(); return value == null ? Null : (RedisValue)value.GetValueOrDefault();
} }
/// <summary> /// <summary>
/// Creates a new RedisValue from an Int64 /// Creates a new RedisValue from an Int64
...@@ -359,7 +343,7 @@ int IComparable.CompareTo(object obj) ...@@ -359,7 +343,7 @@ int IComparable.CompareTo(object obj)
/// </summary> /// </summary>
public static implicit operator RedisValue(long? value) public static implicit operator RedisValue(long? value)
{ {
return value == null ? @null : (RedisValue)value.GetValueOrDefault(); return value == null ? Null : (RedisValue)value.GetValueOrDefault();
} }
/// <summary> /// <summary>
/// Creates a new RedisValue from a Double /// Creates a new RedisValue from a Double
...@@ -374,7 +358,7 @@ int IComparable.CompareTo(object obj) ...@@ -374,7 +358,7 @@ int IComparable.CompareTo(object obj)
/// </summary> /// </summary>
public static implicit operator RedisValue(double? value) public static implicit operator RedisValue(double? value)
{ {
return value == null ? @null : (RedisValue)value.GetValueOrDefault(); return value == null ? Null : (RedisValue)value.GetValueOrDefault();
} }
/// <summary> /// <summary>
/// Creates a new RedisValue from a String /// Creates a new RedisValue from a String
...@@ -410,7 +394,7 @@ int IComparable.CompareTo(object obj) ...@@ -410,7 +394,7 @@ int IComparable.CompareTo(object obj)
/// </summary> /// </summary>
public static implicit operator RedisValue(bool? value) public static implicit operator RedisValue(bool? value)
{ {
return value == null ? @null : (RedisValue)value.GetValueOrDefault(); return value == null ? Null : (RedisValue)value.GetValueOrDefault();
} }
/// <summary> /// <summary>
/// Converts the value to a Boolean /// Converts the value to a Boolean
...@@ -540,74 +524,35 @@ static bool TryParseDouble(byte[] blob, out double value) ...@@ -540,74 +524,35 @@ static bool TryParseDouble(byte[] blob, out double value)
return valueBlob; return valueBlob;
} }
TypeCode IConvertible.GetTypeCode() TypeCode IConvertible.GetTypeCode() => TypeCode.Object;
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider) bool IConvertible.ToBoolean(IFormatProvider provider) => (bool)this;
{
return (bool)this;
}
byte IConvertible.ToByte(IFormatProvider provider) byte IConvertible.ToByte(IFormatProvider provider) => (byte)this;
{
return (byte)this;
}
char IConvertible.ToChar(IFormatProvider provider) char IConvertible.ToChar(IFormatProvider provider) => (char)this;
{
return (char)this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider) DateTime IConvertible.ToDateTime(IFormatProvider provider) => DateTime.Parse((string)this, provider);
{
return DateTime.Parse((string)this, provider);
}
decimal IConvertible.ToDecimal(IFormatProvider provider) decimal IConvertible.ToDecimal(IFormatProvider provider) => (decimal)this;
{
return (decimal)this;
}
double IConvertible.ToDouble(IFormatProvider provider) double IConvertible.ToDouble(IFormatProvider provider) => (double)this;
{
return (double)this;
}
short IConvertible.ToInt16(IFormatProvider provider) short IConvertible.ToInt16(IFormatProvider provider) => (short)this;
{
return (short)this;
}
int IConvertible.ToInt32(IFormatProvider provider) int IConvertible.ToInt32(IFormatProvider provider) => (int)this;
{
return (int)this;
}
long IConvertible.ToInt64(IFormatProvider provider) long IConvertible.ToInt64(IFormatProvider provider) => (long)this;
{
return (long)this;
}
sbyte IConvertible.ToSByte(IFormatProvider provider) sbyte IConvertible.ToSByte(IFormatProvider provider) => (sbyte)this;
{
return (sbyte)this;
}
float IConvertible.ToSingle(IFormatProvider provider) float IConvertible.ToSingle(IFormatProvider provider) => (float)this;
{
return (float)this;
}
string IConvertible.ToString(IFormatProvider provider) string IConvertible.ToString(IFormatProvider provider) => (string)this;
{
return (string)this;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider) object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{ {
if (conversionType== null) throw new ArgumentNullException("conversionType"); if (conversionType== null) throw new ArgumentNullException(nameof(conversionType));
if (conversionType== typeof(byte[])) return (byte[])this; if (conversionType== typeof(byte[])) return (byte[])this;
if (conversionType == typeof(RedisValue)) return this; if (conversionType == typeof(RedisValue)) return this;
switch(conversionType.GetTypeCode()) switch(conversionType.GetTypeCode())
...@@ -633,21 +578,12 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) ...@@ -633,21 +578,12 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider)
} }
} }
ushort IConvertible.ToUInt16(IFormatProvider provider) ushort IConvertible.ToUInt16(IFormatProvider provider) => (ushort)this;
{
return (ushort)this;
}
uint IConvertible.ToUInt32(IFormatProvider provider) uint IConvertible.ToUInt32(IFormatProvider provider) => (uint)this;
{
return (uint)this; ulong IConvertible.ToUInt64(IFormatProvider provider) => (ulong)this;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return (ulong)this;
}
/// <summary> /// <summary>
/// Convert to a long if possible, returning true. /// Convert to a long if possible, returning true.
/// ///
......
...@@ -120,8 +120,8 @@ public void ServerFail(Message message, string errorMessage) ...@@ -120,8 +120,8 @@ public void ServerFail(Message message, string errorMessage)
public void SetException(Message message, Exception ex) public void SetException(Message message, Exception ex)
{ {
var box = message == null ? null : message.ResultBox; var box = message?.ResultBox;
if (box != null) box.SetException(ex); box?.SetException(ex);
} }
// true if ready to be completed (i.e. false if re-issued to another server) // true if ready to be completed (i.e. false if re-issued to another server)
public virtual bool SetResult(PhysicalConnection connection, Message message, RawResult result) public virtual bool SetResult(PhysicalConnection connection, Message message, RawResult result)
...@@ -192,7 +192,7 @@ public virtual bool SetResult(PhysicalConnection connection, Message message, Ra ...@@ -192,7 +192,7 @@ public virtual bool SetResult(PhysicalConnection connection, Message message, Ra
private void UnexpectedResponse(Message message, RawResult result) private void UnexpectedResponse(Message message, RawResult result)
{ {
ConnectionMultiplexer.TraceWithoutContext("From " + GetType().Name, "Unexpected Response"); ConnectionMultiplexer.TraceWithoutContext("From " + GetType().Name, "Unexpected Response");
ConnectionFail(message, ConnectionFailureType.ProtocolFailure, "Unexpected response to " + (message == null ? "n/a" : message.Command.ToString()) +": " + result.ToString()); ConnectionFail(message, ConnectionFailureType.ProtocolFailure, "Unexpected response to " + (message?.Command.ToString() ?? "n/a") +": " + result.ToString());
} }
public sealed class TimeSpanProcessor : ResultProcessor<TimeSpan?> public sealed class TimeSpanProcessor : ResultProcessor<TimeSpan?>
...@@ -1226,12 +1226,12 @@ protected override bool SetResultCore(PhysicalConnection connection, Message mes ...@@ -1226,12 +1226,12 @@ protected override bool SetResultCore(PhysicalConnection connection, Message mes
var arr = result.GetItemsAsValues(); var arr = result.GetItemsAsValues();
int port; int port;
if (arr.Count() == 2 && int.TryParse(arr[1], out port)) if (arr.Length == 2 && int.TryParse(arr[1], out port))
{ {
SetResult(message, Format.ParseEndPoint(arr[0], port)); SetResult(message, Format.ParseEndPoint(arr[0], port));
return true; return true;
} }
else if (arr.Count() == 0) else if (arr.Length == 0)
{ {
SetResult(message, null); SetResult(message, null);
return true; return true;
...@@ -1257,9 +1257,9 @@ protected override bool SetResultCore(PhysicalConnection connection, Message mes ...@@ -1257,9 +1257,9 @@ protected override bool SetResultCore(PhysicalConnection connection, Message mes
case ResultType.MultiBulk: case ResultType.MultiBulk:
var arrayOfArrays = result.GetArrayOfRawResults(); var arrayOfArrays = result.GetArrayOfRawResults();
var returnArray = new KeyValuePair<string, string>[arrayOfArrays.Count()][]; var returnArray = new KeyValuePair<string, string>[arrayOfArrays.Length][];
for (int i = 0; i < arrayOfArrays.Count(); i++) for (int i = 0; i < arrayOfArrays.Length; i++)
{ {
var rawInnerArray = arrayOfArrays[i]; var rawInnerArray = arrayOfArrays[i];
KeyValuePair<string, string>[] kvpArray; KeyValuePair<string, string>[] kvpArray;
...@@ -1285,7 +1285,7 @@ protected void SetResult(Message message, T value) ...@@ -1285,7 +1285,7 @@ protected void SetResult(Message message, T value)
var box = message.ResultBox as ResultBox<T>; var box = message.ResultBox as ResultBox<T>;
message.SetResponseReceived(); message.SetResponseReceived();
if (box != null) box.SetResult(value); box?.SetResult(value);
} }
} }
} }
...@@ -226,7 +226,7 @@ public static bool IsValidParameterHash(Type t, LuaScript script, out string mis ...@@ -226,7 +226,7 @@ public static bool IsValidParameterHash(Type t, LuaScript script, out string mis
for (var i = 0; i < script.Arguments.Length; i++) for (var i = 0; i < script.Arguments.Length; i++)
{ {
var argName = script.Arguments[i]; var argName = script.Arguments[i];
var member = t.GetMember(argName).Where(m => m is PropertyInfo || m is FieldInfo).SingleOrDefault(); var member = t.GetMember(argName).SingleOrDefault(m => m is PropertyInfo || m is FieldInfo);
if (member == null) if (member == null)
{ {
missingMember = argName; missingMember = argName;
...@@ -292,7 +292,7 @@ static void PrefixIfNeeded(ILGenerator il, LocalBuilder needsPrefixBool, ref Loc ...@@ -292,7 +292,7 @@ static void PrefixIfNeeded(ILGenerator il, LocalBuilder needsPrefixBool, ref Loc
for (var i = 0; i < script.Arguments.Length; i++) for (var i = 0; i < script.Arguments.Length; i++)
{ {
var argName = script.Arguments[i]; var argName = script.Arguments[i];
var member = t.GetMember(argName).Where(m => m is PropertyInfo || m is FieldInfo).SingleOrDefault(); var member = t.GetMember(argName).SingleOrDefault(m => m is PropertyInfo || m is FieldInfo);
var memberType = member is FieldInfo ? ((FieldInfo)member).FieldType : ((PropertyInfo)member).PropertyType; var memberType = member is FieldInfo ? ((FieldInfo)member).FieldType : ((PropertyInfo)member).PropertyType;
......
...@@ -10,35 +10,35 @@ public class ServerCounters ...@@ -10,35 +10,35 @@ public class ServerCounters
{ {
internal ServerCounters(EndPoint endpoint) internal ServerCounters(EndPoint endpoint)
{ {
this.EndPoint = endpoint; EndPoint = endpoint;
this.Interactive = new ConnectionCounters(ConnectionType.Interactive); Interactive = new ConnectionCounters(ConnectionType.Interactive);
this.Subscription = new ConnectionCounters(ConnectionType.Subscription); Subscription = new ConnectionCounters(ConnectionType.Subscription);
this.Other = new ConnectionCounters(ConnectionType.None); Other = new ConnectionCounters(ConnectionType.None);
} }
/// <summary> /// <summary>
/// The endpoint to which this data relates (this can be null if the data represents all servers) /// The endpoint to which this data relates (this can be null if the data represents all servers)
/// </summary> /// </summary>
public EndPoint EndPoint { get; private set; } public EndPoint EndPoint { get; }
/// <summary> /// <summary>
/// Counters associated with the interactive (non pub-sub) connection /// Counters associated with the interactive (non pub-sub) connection
/// </summary> /// </summary>
public ConnectionCounters Interactive { get; private set; } public ConnectionCounters Interactive { get; }
/// <summary> /// <summary>
/// Counters associated with other ambient activity /// Counters associated with other ambient activity
/// </summary> /// </summary>
public ConnectionCounters Other { get; private set; } public ConnectionCounters Other { get; }
/// <summary> /// <summary>
/// Counters associated with the subscription (pub-sub) connection /// Counters associated with the subscription (pub-sub) connection
/// </summary> /// </summary>
public ConnectionCounters Subscription { get; private set; } public ConnectionCounters Subscription { get; }
/// <summary> /// <summary>
/// Indicates the total number of outstanding items against this server /// Indicates the total number of outstanding items against this server
/// </summary> /// </summary>
public long TotalOutstanding { get { return Interactive.TotalOutstanding + Subscription.TotalOutstanding + Other.TotalOutstanding; } } public long TotalOutstanding => Interactive.TotalOutstanding + Subscription.TotalOutstanding + Other.TotalOutstanding;
/// <summary> /// <summary>
/// See Object.ToString(); /// See Object.ToString();
...@@ -61,9 +61,8 @@ public override string ToString() ...@@ -61,9 +61,8 @@ public override string ToString()
internal void Add(ServerCounters other) internal void Add(ServerCounters other)
{ {
if (other == null) return; if (other == null) return;
this.Interactive.Add(other.Interactive); Interactive.Add(other.Interactive);
this.Subscription.Add(other.Subscription); Subscription.Add(other.Subscription);
} }
} }
}
} \ No newline at end of file
...@@ -7,7 +7,6 @@ ...@@ -7,7 +7,6 @@
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
...@@ -51,10 +50,8 @@ internal sealed partial class ServerEndPoint : IDisposable ...@@ -51,10 +50,8 @@ internal sealed partial class ServerEndPoint : IDisposable
internal void ResetNonConnected() internal void ResetNonConnected()
{ {
var tmp = interactive; interactive?.ResetNonConnected();
if (tmp != null) tmp.ResetNonConnected(); subscription?.ResetNonConnected();
tmp = subscription;
if (tmp != null) tmp.ResetNonConnected();
} }
public ServerEndPoint(ConnectionMultiplexer multiplexer, EndPoint endpoint, TextWriter log) public ServerEndPoint(ConnectionMultiplexer multiplexer, EndPoint endpoint, TextWriter log)
{ {
...@@ -81,9 +78,9 @@ public ServerEndPoint(ConnectionMultiplexer multiplexer, EndPoint endpoint, Text ...@@ -81,9 +78,9 @@ public ServerEndPoint(ConnectionMultiplexer multiplexer, EndPoint endpoint, Text
public int Databases { get { return databases; } set { SetConfig(ref databases, value); } } public int Databases { get { return databases; } set { SetConfig(ref databases, value); } }
public EndPoint EndPoint { get { return endpoint; } } public EndPoint EndPoint => endpoint;
public bool HasDatabases { get { return serverType == ServerType.Standalone; } } public bool HasDatabases => serverType == ServerType.Standalone;
public bool IsConnected public bool IsConnected
{ {
...@@ -109,7 +106,7 @@ public long OperationCount ...@@ -109,7 +106,7 @@ public long OperationCount
} }
} }
public bool RequiresReadMode { get { return serverType == ServerType.Cluster && IsSlave; } } public bool RequiresReadMode => serverType == ServerType.Cluster && IsSlave;
public ServerType ServerType { get { return serverType; } set { SetConfig(ref serverType, value); } } public ServerType ServerType { get { return serverType; } set { SetConfig(ref serverType, value); } }
...@@ -120,7 +117,7 @@ public long OperationCount ...@@ -120,7 +117,7 @@ public long OperationCount
public Version Version { get { return version; } set { SetConfig(ref version, value); } } public Version Version { get { return version; } set { SetConfig(ref version, value); } }
public int WriteEverySeconds { get { return writeEverySeconds; } set { SetConfig(ref writeEverySeconds, value); } } public int WriteEverySeconds { get { return writeEverySeconds; } set { SetConfig(ref writeEverySeconds, value); } }
internal ConnectionMultiplexer Multiplexer { get { return multiplexer; } } internal ConnectionMultiplexer Multiplexer => multiplexer;
public void ClearUnselectable(UnselectableFlags flags) public void ClearUnselectable(UnselectableFlags flags)
{ {
...@@ -140,11 +137,11 @@ public void Dispose() ...@@ -140,11 +137,11 @@ public void Dispose()
isDisposed = true; isDisposed = true;
var tmp = interactive; var tmp = interactive;
interactive = null; interactive = null;
if (tmp != null) tmp.Dispose(); tmp?.Dispose();
tmp = subscription; tmp = subscription;
subscription = null; subscription = null;
if (tmp != null) tmp.Dispose(); tmp?.Dispose();
} }
public PhysicalBridge GetBridge(ConnectionType type, bool create = true, TextWriter log = null) public PhysicalBridge GetBridge(ConnectionType type, bool create = true, TextWriter log = null)
...@@ -207,7 +204,7 @@ public void SetClusterConfiguration(ClusterConfiguration configuration) ...@@ -207,7 +204,7 @@ public void SetClusterConfiguration(ClusterConfiguration configuration)
} }
} }
Master = master; Master = master;
Slaves = slaves == null ? NoSlaves : slaves.ToArray(); Slaves = slaves?.ToArray() ?? NoSlaves;
} }
multiplexer.Trace("Cluster configured"); multiplexer.Trace("Cluster configured");
} }
...@@ -358,10 +355,8 @@ internal string RunId ...@@ -358,10 +355,8 @@ internal string RunId
internal ServerCounters GetCounters() internal ServerCounters GetCounters()
{ {
var counters = new ServerCounters(endpoint); var counters = new ServerCounters(endpoint);
var tmp = interactive; interactive?.GetCounters(counters.Interactive);
if (tmp != null) tmp.GetCounters(counters.Interactive); subscription?.GetCounters(counters.Subscription);
tmp = subscription;
if (tmp != null) tmp.GetCounters(counters.Subscription);
return counters; return counters;
} }
...@@ -380,11 +375,9 @@ internal string GetProfile() ...@@ -380,11 +375,9 @@ internal string GetProfile()
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("Circular op-count snapshot; int:"); sb.Append("Circular op-count snapshot; int:");
var tmp = interactive; interactive?.AppendProfile(sb);
if (tmp != null) tmp.AppendProfile(sb);
sb.Append("; sub:"); sb.Append("; sub:");
tmp = subscription; subscription?.AppendProfile(sb);
if (tmp != null) tmp.AppendProfile(sb);
return sb.ToString(); return sb.ToString();
} }
...@@ -406,7 +399,7 @@ internal byte[] GetScriptHash(string script, RedisCommand command) ...@@ -406,7 +399,7 @@ internal byte[] GetScriptHash(string script, RedisCommand command)
internal string GetStormLog(RedisCommand command) internal string GetStormLog(RedisCommand command)
{ {
var bridge = GetBridge(command); var bridge = GetBridge(command);
return bridge == null ? null : bridge.GetStormLog(); return bridge?.GetStormLog();
} }
internal Message GetTracerMessage(bool assertIdentity) internal Message GetTracerMessage(bool assertIdentity)
...@@ -480,7 +473,6 @@ internal void OnFullyEstablished(PhysicalConnection connection) ...@@ -480,7 +473,6 @@ internal void OnFullyEstablished(PhysicalConnection connection)
connection.RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex); connection.RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex);
} }
} }
internal int LastInfoReplicationCheckSecondsAgo internal int LastInfoReplicationCheckSecondsAgo
{ {
...@@ -515,10 +507,8 @@ internal void OnHeartbeat() ...@@ -515,10 +507,8 @@ internal void OnHeartbeat()
{ {
try try
{ {
var tmp = interactive; interactive?.OnHeartbeat(false);
if (tmp != null) tmp.OnHeartbeat(false); subscription?.OnHeartbeat(false);
tmp = subscription;
if (tmp != null) tmp.OnHeartbeat(false);
} catch(Exception ex) } catch(Exception ex)
{ {
multiplexer.OnInternalError(ex, EndPoint); multiplexer.OnInternalError(ex, EndPoint);
...@@ -551,10 +541,8 @@ internal void QueueDirectFireAndForget<T>(Message message, ResultProcessor<T> pr ...@@ -551,10 +541,8 @@ internal void QueueDirectFireAndForget<T>(Message message, ResultProcessor<T> pr
internal void ReportNextFailure() internal void ReportNextFailure()
{ {
var tmp = interactive; interactive?.ReportNextFailure();
if (tmp != null) tmp.ReportNextFailure(); subscription?.ReportNextFailure();
tmp = subscription;
if (tmp != null) tmp.ReportNextFailure();
} }
internal Task<bool> SendTracer(TextWriter log = null) internal Task<bool> SendTracer(TextWriter log = null)
...@@ -574,7 +562,7 @@ internal string Summary() ...@@ -574,7 +562,7 @@ internal string Summary()
if (writeEverySeconds > 0) if (writeEverySeconds > 0)
sb.Append("; keep-alive: ").Append(TimeSpan.FromSeconds(writeEverySeconds)); sb.Append("; keep-alive: ").Append(TimeSpan.FromSeconds(writeEverySeconds));
var tmp = interactive; var tmp = interactive;
sb.Append("; int: ").Append(tmp == null ? "n/a" : tmp.ConnectionState.ToString()); sb.Append("; int: ").Append(tmp?.ConnectionState.ToString() ?? "n/a");
tmp = subscription; tmp = subscription;
if(tmp == null) if(tmp == null)
{ {
......
...@@ -57,7 +57,8 @@ public ServerSelectionStrategy(ConnectionMultiplexer multiplexer) ...@@ -57,7 +57,8 @@ public ServerSelectionStrategy(ConnectionMultiplexer multiplexer)
} }
public ServerType ServerType { get { return serverType; } set { serverType = value; } } public ServerType ServerType { get { return serverType; } set { serverType = value; } }
internal int TotalSlots { get { return RedisClusterSlotCount; } } internal int TotalSlots => RedisClusterSlotCount;
/// <summary> /// <summary>
/// Computes the hash-slot that would be used by the given key /// Computes the hash-slot that would be used by the given key
/// </summary> /// </summary>
...@@ -89,7 +90,7 @@ public unsafe int HashSlot(RedisKey key) ...@@ -89,7 +90,7 @@ public unsafe int HashSlot(RedisKey key)
public ServerEndPoint Select(Message message) public ServerEndPoint Select(Message message)
{ {
if (message == null) throw new ArgumentNullException("message"); if (message == null) throw new ArgumentNullException(nameof(message));
int slot = NoSlot; int slot = NoSlot;
switch (serverType) switch (serverType)
{ {
...@@ -163,7 +164,7 @@ public bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool isM ...@@ -163,7 +164,7 @@ public bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool isM
arr[hashSlot] = server; arr[hashSlot] = server;
if (oldServer != server) if (oldServer != server)
{ {
multiplexer.OnHashSlotMoved(hashSlot, oldServer == null ? null : oldServer.EndPoint, endpoint); multiplexer.OnHashSlotMoved(hashSlot, oldServer?.EndPoint, endpoint);
} }
} }
......
...@@ -8,8 +8,6 @@ ...@@ -8,8 +8,6 @@
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
partial class SocketManager partial class SocketManager
{ {
internal const SocketMode DefaultSocketMode = SocketMode.Poll; internal const SocketMode DefaultSocketMode = SocketMode.Poll;
...@@ -70,8 +68,8 @@ private static void ProcessItems(Queue<ISocketCallback> queue, CallbackOperation ...@@ -70,8 +68,8 @@ private static void ProcessItems(Queue<ISocketCallback> queue, CallbackOperation
private void OnAddRead(Socket socket, ISocketCallback callback) private void OnAddRead(Socket socket, ISocketCallback callback)
{ {
if (socket == null) throw new ArgumentNullException("socket"); if (socket == null) throw new ArgumentNullException(nameof(socket));
if (callback == null) throw new ArgumentNullException("callback"); if (callback == null) throw new ArgumentNullException(nameof(callback));
lock (socketLookup) lock (socketLookup)
{ {
...@@ -142,10 +140,7 @@ private void Read() ...@@ -142,10 +140,7 @@ private void Read()
} }
} }
internal ManagerState State internal ManagerState State => managerState;
{
get { return managerState; }
}
private volatile ManagerState managerState; private volatile ManagerState managerState;
private volatile int lastErrorTicks; private volatile int lastErrorTicks;
internal string LastErrorTimeRelative() internal string LastErrorTimeRelative()
...@@ -174,7 +169,7 @@ private void ReadImpl() ...@@ -174,7 +169,7 @@ private void ReadImpl()
managerState = ManagerState.CheckForHeartbeat; managerState = ManagerState.CheckForHeartbeat;
active.Clear(); active.Clear();
activeCallbacks.Clear(); activeCallbacks.Clear();
if (dead != null) dead.Clear(); dead?.Clear();
// this check is actually a pace-maker; sometimes the Timer callback stalls for // this check is actually a pace-maker; sometimes the Timer callback stalls for
// extended periods of time, which can cause socket disconnect // extended periods of time, which can cause socket disconnect
...@@ -375,11 +370,13 @@ private void ReadImpl() ...@@ -375,11 +370,13 @@ private void ReadImpl()
} }
private void StartReader() private void StartReader()
{ {
var thread = new Thread(read, 32 * 1024); // don't need a huge stack var thread = new Thread(read, 32*1024) // don't need a huge stack
thread.Priority = useHighPrioritySocketThreads ? ThreadPriority.AboveNormal : ThreadPriority.Normal; {
thread.Name = name + ":Read"; Priority = useHighPrioritySocketThreads ? ThreadPriority.AboveNormal : ThreadPriority.Normal,
thread.IsBackground = true; Name = name + ":Read",
IsBackground = true
};
thread.Start(this); thread.Start(this);
} }
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
...@@ -400,19 +397,18 @@ struct SocketPair ...@@ -400,19 +397,18 @@ struct SocketPair
public readonly Socket Socket; public readonly Socket Socket;
public SocketPair(Socket socket, ISocketCallback callback) public SocketPair(Socket socket, ISocketCallback callback)
{ {
this.Socket = socket; Socket = socket;
this.Callback = callback; Callback = callback;
} }
} }
sealed class QueueDrainSyncLock sealed class QueueDrainSyncLock
{ {
private readonly SocketManager manager;
private int workers; private int workers;
public QueueDrainSyncLock(SocketManager manager) public QueueDrainSyncLock(SocketManager manager)
{ {
this.manager = manager; Manager = manager;
} }
public SocketManager Manager { get { return manager; } } public SocketManager Manager { get; }
internal bool Consume() internal bool Consume()
{ {
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
#if CORE_CLR
using System.Runtime.InteropServices;
using System.Threading.Tasks; using System.Threading.Tasks;
#endif
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -52,11 +53,11 @@ internal struct SocketToken ...@@ -52,11 +53,11 @@ internal struct SocketToken
internal readonly Socket Socket; internal readonly Socket Socket;
public SocketToken(Socket socket) public SocketToken(Socket socket)
{ {
this.Socket = socket; Socket = socket;
} }
public int Available { get { return Socket == null ? 0 : Socket.Available; } } public int Available => Socket?.Available ?? 0;
public bool HasValue { get { return Socket != null; } } public bool HasValue => Socket != null;
} }
/// <summary> /// <summary>
...@@ -155,7 +156,8 @@ private enum CallbackOperation ...@@ -155,7 +156,8 @@ private enum CallbackOperation
/// <summary> /// <summary>
/// Gets the name of this SocketManager instance /// Gets the name of this SocketManager instance
/// </summary> /// </summary>
public string Name { get { return name; } } public string Name => name;
/// <summary> /// <summary>
/// Releases all resources associated with this instance /// Releases all resources associated with this instance
/// </summary> /// </summary>
...@@ -197,11 +199,11 @@ internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback, C ...@@ -197,11 +199,11 @@ internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback, C
}); });
#else #else
CompletionTypeHelper.RunWithCompletionType( CompletionTypeHelper.RunWithCompletionType(
(cb) => { cb => {
multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint);
return socket.BeginConnect(dnsEndpoint.Host, dnsEndpoint.Port, cb, tuple); return socket.BeginConnect(dnsEndpoint.Host, dnsEndpoint.Port, cb, tuple);
}, },
(ar) => { ar => {
multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint);
EndConnectImpl(ar, multiplexer, log, tuple); EndConnectImpl(ar, multiplexer, log, tuple);
multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint); multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint);
...@@ -220,11 +222,11 @@ internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback, C ...@@ -220,11 +222,11 @@ internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback, C
}); });
#else #else
CompletionTypeHelper.RunWithCompletionType( CompletionTypeHelper.RunWithCompletionType(
(cb) => { cb => {
multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint);
return socket.BeginConnect(endpoint, cb, tuple); return socket.BeginConnect(endpoint, cb, tuple);
}, },
(ar) => { ar => {
multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint);
EndConnectImpl(ar, multiplexer, log, tuple); EndConnectImpl(ar, multiplexer, log, tuple);
multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint); multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint);
...@@ -318,7 +320,7 @@ private void EndConnectImpl(IAsyncResult ar, ConnectionMultiplexer multiplexer, ...@@ -318,7 +320,7 @@ private void EndConnectImpl(IAsyncResult ar, ConnectionMultiplexer multiplexer,
socket.EndConnect(ar); socket.EndConnect(ar);
#endif #endif
var netStream = new NetworkStream(socket, false); var netStream = new NetworkStream(socket, false);
var socketMode = callback == null ? SocketMode.Abort : callback.Connected(netStream, log); var socketMode = callback?.Connected(netStream, log) ?? SocketMode.Abort;
switch (socketMode) switch (socketMode)
{ {
case SocketMode.Poll: case SocketMode.Poll:
......
...@@ -23,11 +23,12 @@ public SortedSetEntry(RedisValue element, double score) ...@@ -23,11 +23,12 @@ public SortedSetEntry(RedisValue element, double score)
/// <summary> /// <summary>
/// The unique element stored in the sorted set /// The unique element stored in the sorted set
/// </summary> /// </summary>
public RedisValue Element { get { return element; } } public RedisValue Element => element;
/// <summary> /// <summary>
/// The score against the element /// The score against the element
/// </summary> /// </summary>
public double Score { get { return score; } } public double Score => score;
/// <summary> /// <summary>
/// The score against the element /// The score against the element
...@@ -89,7 +90,7 @@ public override bool Equals(object obj) ...@@ -89,7 +90,7 @@ public override bool Equals(object obj)
/// </summary> /// </summary>
public bool Equals(SortedSetEntry value) public bool Equals(SortedSetEntry value)
{ {
return this.score == value.score && this.element == value.element; return score == value.score && element == value.element;
} }
/// <summary> /// <summary>
...@@ -97,7 +98,7 @@ public bool Equals(SortedSetEntry value) ...@@ -97,7 +98,7 @@ public bool Equals(SortedSetEntry value)
/// </summary> /// </summary>
public int CompareTo(SortedSetEntry value) public int CompareTo(SortedSetEntry value)
{ {
return this.score.CompareTo(value.score); return score.CompareTo(value.score);
} }
/// <summary> /// <summary>
......
using System; using System.Threading.Tasks;
#if !PLAT_SAFE_CONTINUATIONS
using System;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Threading.Tasks; #endif
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment