This repository has been archived by the owner on Dec 24, 2022. It is now read-only.
/
RedisNativeClient_Utils.cs
1235 lines (1011 loc) · 40 KB
/
RedisNativeClient_Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of Redis: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using ServiceStack.Text;
namespace ServiceStack.Redis
{
public partial class RedisNativeClient
{
private const string OK = "OK";
private const string QUEUED = "QUEUED";
private static Timer UsageTimer;
private static int __requestsPerHour = 0;
public static int RequestsPerHour
{
get { return __requestsPerHour; }
}
private const int Unknown = -1;
public int ServerVersionNumber { get; set; }
public int AssertServerVersionNumber()
{
if (ServerVersionNumber == 0)
AssertConnectedSocket();
return ServerVersionNumber;
}
public static void DisposeTimers()
{
if (UsageTimer == null) return;
try
{
UsageTimer.Dispose();
}
finally
{
UsageTimer = null;
}
}
private void Connect()
{
if (UsageTimer == null)
{
//Save Timer Resource for licensed usage
if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
{
UsageTimer = new Timer(delegate
{
__requestsPerHour = 0;
}, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
}
}
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
SendTimeout = SendTimeout,
ReceiveTimeout = ReceiveTimeout
};
try
{
if (ConnectTimeout <= 0)
{
socket.Connect(Host, Port);
}
else
{
var connectResult = socket.BeginConnect(Host, Port, null, null);
connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
}
if (!socket.Connected)
{
socket.Close();
socket = null;
DeactivatedAt = DateTime.UtcNow;
return;
}
Stream networkStream = new NetworkStream(socket);
if (Ssl)
{
if (Env.IsMono)
{
//Mono doesn't support EncryptionPolicy
sslStream = new SslStream(networkStream,
leaveInnerStreamOpen: false,
userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
}
else
{
var ctor = typeof(SslStream).GetConstructors()
.First(x => x.GetParameters().Length == 5);
var policyType = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
var policyValue = Enum.Parse(policyType, "RequireEncryption");
sslStream = (SslStream)ctor.Invoke(new[] {
networkStream,
false,
RedisConfig.CertificateValidationCallback,
RedisConfig.CertificateSelectionCallback,
policyValue,
});
}
sslStream.AuthenticateAsClient(Host);
if (!sslStream.IsEncrypted)
throw new Exception("Could not establish an encrypted connection to " + Host);
networkStream = sslStream;
}
Bstream = new BufferedStream(networkStream, 16 * 1024);
if (!string.IsNullOrEmpty(Password))
SendUnmanagedExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
if (db != 0)
SendUnmanagedExpectSuccess(Commands.Select, db.ToUtf8Bytes());
if (Client != null)
SendUnmanagedExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
try
{
if (ServerVersionNumber == 0)
{
ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0);
if (ServerVersionNumber <= 0)
{
var parts = ServerVersion.Split('.');
var version = int.Parse(parts[0]) * 1000;
if (parts.Length > 1)
version += int.Parse(parts[1]) * 100;
if (parts.Length > 2)
version += int.Parse(parts[2]);
ServerVersionNumber = version;
}
}
}
catch (Exception)
{
//Twemproxy doesn't support the INFO command so automatically closes the socket
//Fallback to ServerVersionNumber=Unknown then try re-connecting
ServerVersionNumber = Unknown;
Connect();
return;
}
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
OnConnected();
if (ConnectionFilter != null)
{
ConnectionFilter(this);
}
}
catch (SocketException)
{
log.Error(ErrorConnect.Fmt(Host, Port));
throw;
}
}
public static string ErrorConnect = "Could not connect to redis Instance at {0}:{1}";
public virtual void OnConnected()
{
}
protected string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = Bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
public bool HasConnected
{
get { return socket != null; }
}
public bool IsSocketConnected()
{
var part1 = socket.Poll(1000, SelectMode.SelectRead);
var part2 = (socket.Available == 0);
return !(part1 & part2);
}
internal bool AssertConnectedSocket()
{
try
{
TryConnectIfNeeded();
var isConnected = socket != null;
return isConnected;
}
catch (SocketException ex)
{
log.Error(ErrorConnect.Fmt(Host, Port));
if (socket != null)
socket.Close();
socket = null;
DeactivatedAt = DateTime.UtcNow;
var message = "" + Host + ":" + Port;
var throwEx = new RedisException(message, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
private void TryConnectIfNeeded()
{
if (LastConnectedAtTimestamp > 0)
{
var now = Stopwatch.GetTimestamp();
var elapsedSecs = (now - LastConnectedAtTimestamp) / Stopwatch.Frequency;
if (socket == null || (elapsedSecs > IdleTimeOutSecs && !socket.IsConnected()))
{
Reconnect();
}
LastConnectedAtTimestamp = now;
}
if (socket == null)
{
Connect();
}
}
private bool Reconnect()
{
var previousDb = db;
SafeConnectionClose();
Connect(); //sets db to 0
if (previousDb != RedisConfig.DefaultDb) this.Db = previousDb;
return socket != null;
}
private RedisResponseException CreateResponseError(string error)
{
DeactivatedAt = DateTime.UtcNow;
if (!RedisConfig.DisableVerboseLogging)
{
var safeLastCommand = string.IsNullOrEmpty(Password)
? lastCommand
: (lastCommand ?? "").Replace(Password, "");
if (!string.IsNullOrEmpty(safeLastCommand))
error = string.Format("{0}, LastCommand:'{1}', srcPort:{2}", error, safeLastCommand, clientPort);
}
var throwEx = new RedisResponseException(error);
log.Error(error);
return throwEx;
}
private RedisRetryableException CreateNoMoreDataError()
{
Reconnect();
return CreateRetryableResponseError("No more data");
}
private RedisRetryableException CreateRetryableResponseError(string error)
{
string safeLastCommand = string.IsNullOrEmpty(Password) ? lastCommand : (lastCommand ?? "").Replace(Password, "");
var throwEx = new RedisRetryableException(
string.Format("{0}, sPort: {1}, LastCommand: {2}",
error, clientPort, safeLastCommand));
log.Error(throwEx.Message);
throw throwEx;
}
private RedisException CreateConnectionError()
{
DeactivatedAt = DateTime.UtcNow;
var throwEx = new RedisException(
string.Format("Unable to Connect: sPort: {0}",
clientPort), lastSocketException);
log.Error(throwEx.Message);
throw throwEx;
}
private static byte[] GetCmdBytes(char cmdPrefix, int noOfLines)
{
var strLines = noOfLines.ToString();
var strLinesLength = strLines.Length;
var cmdBytes = new byte[1 + strLinesLength + 2];
cmdBytes[0] = (byte)cmdPrefix;
for (var i = 0; i < strLinesLength; i++)
cmdBytes[i + 1] = (byte)strLines[i];
cmdBytes[1 + strLinesLength] = 0x0D; // \r
cmdBytes[2 + strLinesLength] = 0x0A; // \n
return cmdBytes;
}
/// <summary>
/// Command to set multuple binary safe arguments
/// </summary>
/// <param name="cmdWithBinaryArgs"></param>
/// <returns></returns>
protected void WriteCommandToSendBuffer(params byte[][] cmdWithBinaryArgs)
{
if (Pipeline == null && Transaction == null)
{
Interlocked.Increment(ref __requestsPerHour);
if (__requestsPerHour % 20 == 0)
LicenseUtils.AssertValidUsage(LicenseFeature.Redis, QuotaType.RequestsPerHour, __requestsPerHour);
}
if (log.IsDebugEnabled && !RedisConfig.DisableVerboseLogging)
CmdLog(cmdWithBinaryArgs);
//Total command lines count
WriteAllToSendBuffer(cmdWithBinaryArgs);
}
/// <summary>
/// Send command outside of managed Write Buffer
/// </summary>
/// <param name="cmdWithBinaryArgs"></param>
protected void SendUnmanagedExpectSuccess(params byte[][] cmdWithBinaryArgs)
{
var bytes = GetCmdBytes('*', cmdWithBinaryArgs.Length);
foreach (var safeBinaryValue in cmdWithBinaryArgs)
{
bytes = bytes.Combine(GetCmdBytes('$', safeBinaryValue.Length), safeBinaryValue, endData);
}
Bstream.Write(bytes, 0, bytes.Length);
ExpectSuccess();
}
public void WriteAllToSendBuffer(params byte[][] cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('*', cmdWithBinaryArgs.Length));
foreach (var safeBinaryValue in cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('$', safeBinaryValue.Length));
WriteToSendBuffer(safeBinaryValue);
WriteToSendBuffer(endData);
}
}
readonly IList<ArraySegment<byte>> cmdBuffer = new List<ArraySegment<byte>>();
byte[] currentBuffer = BufferPool.GetBuffer();
int currentBufferIndex;
public void WriteToSendBuffer(byte[] cmdBytes)
{
if (CouldAddToCurrentBuffer(cmdBytes)) return;
PushCurrentBuffer();
if (CouldAddToCurrentBuffer(cmdBytes)) return;
var bytesCopied = 0;
while (bytesCopied < cmdBytes.Length)
{
var copyOfBytes = BufferPool.GetBuffer(cmdBytes.Length);
var bytesToCopy = Math.Min(cmdBytes.Length - bytesCopied, copyOfBytes.Length);
Buffer.BlockCopy(cmdBytes, bytesCopied, copyOfBytes, 0, bytesToCopy);
cmdBuffer.Add(new ArraySegment<byte>(copyOfBytes, 0, bytesToCopy));
bytesCopied += bytesToCopy;
}
}
private bool CouldAddToCurrentBuffer(byte[] cmdBytes)
{
if (cmdBytes.Length + currentBufferIndex < RedisConfig.BufferLength)
{
Buffer.BlockCopy(cmdBytes, 0, currentBuffer, currentBufferIndex, cmdBytes.Length);
currentBufferIndex += cmdBytes.Length;
return true;
}
return false;
}
private void PushCurrentBuffer()
{
cmdBuffer.Add(new ArraySegment<byte>(currentBuffer, 0, currentBufferIndex));
currentBuffer = BufferPool.GetBuffer();
currentBufferIndex = 0;
}
public Action OnBeforeFlush { get; set; }
internal void FlushAndResetSendBuffer()
{
FlushSendBuffer();
ResetSendBuffer();
}
internal void FlushSendBuffer()
{
if (currentBufferIndex > 0)
PushCurrentBuffer();
if (cmdBuffer.Count > 0)
{
if (OnBeforeFlush != null)
OnBeforeFlush();
if (!Env.IsMono && sslStream == null)
{
socket.Send(cmdBuffer); //Optimized for Windows
}
else
{
//Sendling IList<ArraySegment> Throws 'Message to Large' SocketException in Mono
foreach (var segment in cmdBuffer)
{
var buffer = segment.Array;
if (sslStream == null)
{
socket.Send(buffer, segment.Offset, segment.Count, SocketFlags.None);
}
else
{
sslStream.Write(buffer, segment.Offset, segment.Count);
}
}
}
}
}
/// <summary>
/// reset buffer index in send buffer
/// </summary>
public void ResetSendBuffer()
{
currentBufferIndex = 0;
for (int i = cmdBuffer.Count - 1; i >= 0; i--)
{
var buffer = cmdBuffer[i].Array;
BufferPool.ReleaseBufferToPool(ref buffer);
cmdBuffer.RemoveAt(i);
}
}
private int SafeReadByte()
{
return Bstream.ReadByte();
}
protected T SendReceive<T>(byte[][] cmdWithBinaryArgs,
Func<T> fn,
Action<Func<T>> completePipelineFn = null,
bool sendWithoutRead = false)
{
var i = 0;
Exception originalEx = null;
var firstAttempt = DateTime.UtcNow;
while (true)
{
try
{
TryConnectIfNeeded();
if (i == 0) //only write to buffer once
WriteCommandToSendBuffer(cmdWithBinaryArgs);
if (Pipeline == null) //pipeline will handle flush if in pipeline
{
FlushSendBuffer();
}
else if (!sendWithoutRead)
{
if (completePipelineFn == null)
throw new NotSupportedException("Pipeline is not supported.");
completePipelineFn(fn);
return default(T);
}
var result = default(T);
if (fn != null)
result = fn();
if (Pipeline == null)
ResetSendBuffer();
if (i > 0)
Interlocked.Increment(ref RedisState.TotalRetrySuccess);
Interlocked.Increment(ref RedisState.TotalCommandsSent);
return result;
}
catch (Exception outerEx)
{
var retryableEx = outerEx as RedisRetryableException;
if (retryableEx == null && outerEx is RedisException
|| outerEx is LicenseException)
{
ResetSendBuffer();
throw;
}
var ex = retryableEx ?? GetRetryableException(outerEx);
if (ex == null)
throw CreateConnectionError();
if (originalEx == null)
originalEx = ex;
var retry = DateTime.UtcNow - firstAttempt < retryTimeout;
if (!retry)
{
if (Pipeline == null)
ResetSendBuffer();
Interlocked.Increment(ref RedisState.TotalRetryTimedout);
throw CreateRetryTimeoutException(retryTimeout, originalEx);
}
Interlocked.Increment(ref RedisState.TotalRetryCount);
Thread.Sleep(GetBackOffMultiplier(++i));
}
}
}
private RedisException CreateRetryTimeoutException(TimeSpan retryTimeout, Exception originalEx)
{
DeactivatedAt = DateTime.UtcNow;
var message = "Exceeded timeout of {0}".Fmt(retryTimeout);
log.Error(message);
return new RedisException(message, originalEx);
}
private Exception GetRetryableException(Exception outerEx)
{
// several stream commands wrap SocketException in IOException
var socketEx = outerEx.InnerException as SocketException
?? outerEx as SocketException;
if (socketEx == null)
return null;
log.Error("SocketException in SendReceive, retrying...", socketEx);
lastSocketException = socketEx;
if (socket != null)
socket.Close();
socket = null;
return socketEx;
}
private static int GetBackOffMultiplier(int i)
{
var nextTryMs = (2 ^ i) * RedisConfig.BackOffMultiplier;
return nextTryMs;
}
protected void SendWithoutRead(params byte[][] cmdWithBinaryArgs)
{
SendReceive<long>(cmdWithBinaryArgs, null, null, sendWithoutRead: true);
}
protected void SendExpectSuccess(params byte[][] cmdWithBinaryArgs)
{
//Turn Action into Func Hack
var completePipelineFn = Pipeline != null
? f => { Pipeline.CompleteVoidQueuedCommand(() => f()); }
: (Action<Func<long>>)null;
SendReceive(cmdWithBinaryArgs, ExpectSuccessFn, completePipelineFn);
}
protected long SendExpectLong(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadLong, Pipeline != null ? Pipeline.CompleteLongQueuedCommand : (Action<Func<long>>)null);
}
protected byte[] SendExpectData(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadData, Pipeline != null ? Pipeline.CompleteBytesQueuedCommand : (Action<Func<byte[]>>)null);
}
protected double SendExpectDouble(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadDouble, Pipeline != null ? Pipeline.CompleteDoubleQueuedCommand : (Action<Func<double>>)null);
}
protected string SendExpectCode(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ExpectCode, Pipeline != null ? Pipeline.CompleteStringQueuedCommand : (Action<Func<string>>)null);
}
protected byte[][] SendExpectMultiData(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadMultiData, Pipeline != null ? Pipeline.CompleteMultiBytesQueuedCommand : (Action<Func<byte[][]>>)null)
?? new byte[0][];
}
protected object[] SendExpectDeeplyNestedMultiData(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadDeeplyNestedMultiData);
}
protected RedisData SendExpectComplexResponse(params byte[][] cmdWithBinaryArgs)
{
return SendReceive(cmdWithBinaryArgs, ReadComplexResponse);
}
protected string SendExpectString(params byte[][] cmdWithBinaryArgs)
{
var bytes = SendExpectData(cmdWithBinaryArgs);
return bytes.FromUtf8Bytes();
}
protected void Log(string fmt, params object[] args)
{
if (RedisConfig.DisableVerboseLogging)
return;
log.DebugFormat("{0}", string.Format(fmt, args).Trim());
}
protected void CmdLog(byte[][] args)
{
var sb = new StringBuilder();
foreach (var arg in args)
{
var strArg = arg.FromUtf8Bytes();
if (strArg == Password) continue;
if (sb.Length > 0)
sb.Append(" ");
sb.Append(strArg);
if (sb.Length > 100)
break;
}
this.lastCommand = sb.ToString();
if (this.lastCommand.Length > 100)
{
this.lastCommand = this.lastCommand.Substring(0, 100) + "...";
}
log.Debug("S: " + this.lastCommand);
}
//Turn Action into Func Hack
protected long ExpectSuccessFn()
{
ExpectSuccess();
return 0;
}
protected void ExpectSuccess()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") && s.Length >= 4 ? s.Substring(4) : s);
}
private void ExpectWord(string word)
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (s != word)
throw CreateResponseError(string.Format("Expected '{0}' got '{1}'", word, s));
}
private string ExpectCode()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
return s;
}
internal void ExpectOk()
{
ExpectWord(OK);
}
internal void ExpectQueued()
{
ExpectWord(QUEUED);
}
public long ReadLong()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log("R: {0}", s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':' || c == '$')//really strange why ZRANK needs the '$' here
{
long i;
if (long.TryParse(s, out i))
return i;
}
throw CreateResponseError("Unknown reply on integer response: " + c + s);
}
public double ReadDouble()
{
var bytes = ReadData();
return (bytes == null) ? double.NaN : ParseDouble(bytes);
}
public static double ParseDouble(byte[] doubleBytes)
{
var doubleString = Encoding.UTF8.GetString(doubleBytes);
double d;
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out d);
return d;
}
private byte[] ReadData()
{
var r = ReadLine();
return ParseSingleLine(r);
}
private byte[] ParseSingleLine(string r)
{
if (log.IsDebugEnabled)
Log("R: {0}", r);
if (r.Length == 0)
throw CreateResponseError("Zero length response");
char c = r[0];
if (c == '-')
throw CreateResponseError(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int count;
if (int.TryParse(r.Substring(1), out count))
{
var retbuf = new byte[count];
var offset = 0;
while (count > 0)
{
var readCount = Bstream.Read(retbuf, offset, count);
if (readCount <= 0)
throw CreateResponseError("Unexpected end of Stream");
offset += readCount;
count -= readCount;
}
if (Bstream.ReadByte() != '\r' || Bstream.ReadByte() != '\n')
throw CreateResponseError("Invalid termination");
return retbuf;
}
throw CreateResponseError("Invalid length");
}
if (c == ':' || c == '+')
{
//match the return value
return r.Substring(1).ToUtf8Bytes();
}
throw CreateResponseError("Unexpected reply: " + r);
}
private byte[][] ReadMultiData()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log("R: {0}", s);
switch (c)
{
// Some commands like BRPOPLPUSH may return Bulk Reply instead of Multi-bulk
case '$':
var t = new byte[2][];
t[1] = ParseSingleLine(string.Concat(char.ToString((char)c), s));
return t;
case '-':
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
case '*':
int count;
if (int.TryParse(s, out count))
{
if (count == -1)
{
//redis is in an invalid state
return new byte[0][];
}
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
break;
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private object[] ReadDeeplyNestedMultiData()
{
var result = ReadDeeplyNestedMultiDataItem();
return (object[])result;
}
private object ReadDeeplyNestedMultiDataItem()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log("R: {0}", s);
switch (c)
{
case '$':
return ParseSingleLine(string.Concat(char.ToString((char)c), s));
case '-':
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
case '*':
int count;
if (int.TryParse(s, out count))
{
var array = new object[count];
for (int i = 0; i < count; i++)
{
array[i] = ReadDeeplyNestedMultiDataItem();
}
return array;
}
break;
default:
return s;
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
internal RedisData ReadComplexResponse()
{
int c = SafeReadByte();
if (c == -1)
throw CreateNoMoreDataError();
var s = ReadLine();
if (log.IsDebugEnabled)
Log("R: {0}", s);
switch (c)
{
case '$':
return new RedisData
{
Data = ParseSingleLine(string.Concat(char.ToString((char)c), s))
};
case '-':
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
case '*':
int count;
if (int.TryParse(s, out count))
{
var ret = new RedisData { Children = new List<RedisData>() };
for (var i = 0; i < count; i++)
{
ret.Children.Add(ReadComplexResponse());
}
return ret;
}
break;
default:
return new RedisData { Data = s.ToUtf8Bytes() };
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
internal int ReadMultiDataResultCount()
{
int c = SafeReadByte();
if (c == -1)