-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathResultProcessor.cs
2418 lines (2180 loc) · 101 KB
/
ResultProcessor.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
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Pipelines.Sockets.Unofficial.Arenas;
namespace StackExchange.Redis
{
internal abstract class ResultProcessor
{
public static readonly ResultProcessor<bool>
Boolean = new BooleanProcessor(),
DemandOK = new ExpectBasicStringProcessor(CommonReplies.OK),
DemandPONG = new ExpectBasicStringProcessor(CommonReplies.PONG),
DemandZeroOrOne = new DemandZeroOrOneProcessor(),
AutoConfigure = new AutoConfigureProcessor(),
TrackSubscriptions = new TrackSubscriptionsProcessor(null),
Tracer = new TracerProcessor(false),
EstablishConnection = new TracerProcessor(true),
BackgroundSaveStarted = new ExpectBasicStringProcessor(CommonReplies.backgroundSavingStarted_trimmed, startsWith: true),
BackgroundSaveAOFStarted = new ExpectBasicStringProcessor(CommonReplies.backgroundSavingAOFStarted_trimmed, startsWith: true);
public static readonly ResultProcessor<byte[]>
ByteArray = new ByteArrayProcessor(),
ScriptLoad = new ScriptLoadProcessor();
public static readonly ResultProcessor<ClusterConfiguration>
ClusterNodes = new ClusterNodesProcessor();
public static readonly ResultProcessor<EndPoint>
ConnectionIdentity = new ConnectionIdentityProcessor();
public static readonly ResultProcessor<DateTime>
DateTime = new DateTimeProcessor();
public static readonly ResultProcessor<double>
Double = new DoubleProcessor();
public static readonly ResultProcessor<IGrouping<string, KeyValuePair<string, string>>[]>
Info = new InfoProcessor();
public static readonly MultiStreamProcessor
MultiStream = new MultiStreamProcessor();
public static readonly ResultProcessor<long>
Int64 = new Int64Processor(),
PubSubNumSub = new PubSubNumSubProcessor();
public static readonly ResultProcessor<double?>
NullableDouble = new NullableDoubleProcessor();
public static readonly ResultProcessor<long?>
NullableInt64 = new NullableInt64Processor();
public static readonly ResultProcessor<RedisChannel[]>
RedisChannelArrayLiteral = new RedisChannelArrayProcessor(RedisChannel.PatternMode.Literal);
public static readonly ResultProcessor<RedisKey>
RedisKey = new RedisKeyProcessor();
public static readonly ResultProcessor<RedisKey[]>
RedisKeyArray = new RedisKeyArrayProcessor();
public static readonly ResultProcessor<RedisType>
RedisType = new RedisTypeProcessor();
public static readonly ResultProcessor<RedisValue>
RedisValue = new RedisValueProcessor();
public static readonly ResultProcessor<Lease<byte>>
Lease = new LeaseProcessor();
public static readonly ResultProcessor<RedisValue[]>
RedisValueArray = new RedisValueArrayProcessor();
public static readonly ResultProcessor<string[]>
StringArray = new StringArrayProcessor();
public static readonly ResultProcessor<GeoPosition?[]>
RedisGeoPositionArray = new RedisValueGeoPositionArrayProcessor();
public static readonly ResultProcessor<GeoPosition?>
RedisGeoPosition = new RedisValueGeoPositionProcessor();
public static readonly ResultProcessor<TimeSpan>
ResponseTimer = new TimingProcessor();
public static readonly ResultProcessor<Role>
Role = new RoleProcessor();
public static readonly ResultProcessor<RedisResult>
ScriptResult = new ScriptResultProcessor();
public static readonly SortedSetEntryProcessor
SortedSetEntry = new SortedSetEntryProcessor();
public static readonly SortedSetEntryArrayProcessor
SortedSetWithScores = new SortedSetEntryArrayProcessor();
public static readonly SingleStreamProcessor
SingleStream = new SingleStreamProcessor();
public static readonly SingleStreamProcessor
SingleStreamWithNameSkip = new SingleStreamProcessor(skipStreamName: true);
public static readonly StreamConsumerInfoProcessor
StreamConsumerInfo = new StreamConsumerInfoProcessor();
public static readonly StreamGroupInfoProcessor
StreamGroupInfo = new StreamGroupInfoProcessor();
public static readonly StreamInfoProcessor
StreamInfo = new StreamInfoProcessor();
public static readonly StreamPendingInfoProcessor
StreamPendingInfo = new StreamPendingInfoProcessor();
public static readonly StreamPendingMessagesProcessor
StreamPendingMessages = new StreamPendingMessagesProcessor();
public static ResultProcessor<GeoRadiusResult[]> GeoRadiusArray(GeoRadiusOptions options) => GeoRadiusResultArrayProcessor.Get(options);
public static readonly ResultProcessor<string>
String = new StringProcessor(),
TieBreaker = new TieBreakerProcessor(),
ClusterNodesRaw = new ClusterNodesRawProcessor();
#region Sentinel
public static readonly ResultProcessor<EndPoint>
SentinelPrimaryEndpoint = new SentinelGetPrimaryAddressByNameProcessor();
public static readonly ResultProcessor<EndPoint[]>
SentinelAddressesEndPoints = new SentinelGetSentinelAddressesProcessor();
public static readonly ResultProcessor<EndPoint[]>
SentinelReplicaEndPoints = new SentinelGetReplicaAddressesProcessor();
public static readonly ResultProcessor<KeyValuePair<string, string>[][]>
SentinelArrayOfArrays = new SentinelArrayOfArraysProcessor();
#endregion
public static readonly ResultProcessor<KeyValuePair<string, string>[]>
StringPairInterleaved = new StringPairInterleavedProcessor();
public static readonly TimeSpanProcessor
TimeSpanFromMilliseconds = new TimeSpanProcessor(true),
TimeSpanFromSeconds = new TimeSpanProcessor(false);
public static readonly HashEntryArrayProcessor
HashEntryArray = new HashEntryArrayProcessor();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Conditionally run on instance")]
public void ConnectionFail(Message message, ConnectionFailureType fail, Exception innerException, string annotation, ConnectionMultiplexer muxer)
{
PhysicalConnection.IdentifyFailureType(innerException, ref fail);
var sb = new StringBuilder(fail.ToString());
if (message is not null)
{
sb.Append(" on ");
sb.Append(muxer?.RawConfig.IncludeDetailInExceptions == true ? message.ToString() : message.ToStringCommandOnly());
}
if (!string.IsNullOrWhiteSpace(annotation))
{
sb.Append(", ");
sb.Append(annotation);
}
var ex = new RedisConnectionException(fail, sb.ToString(), innerException);
SetException(message, ex);
}
public static void ConnectionFail(Message message, ConnectionFailureType fail, string errorMessage)
{
SetException(message, new RedisConnectionException(fail, errorMessage));
}
public static void HashSlotMigratedAndNoRedirectAllowedFail(Message message, int hashSlot, string endpoint, string errorMessage)
{
SetException(message, new RedisHashslotMigratedAndNoRedirectException(errorMessage, hashSlot, endpoint));
}
public static void ServerFail(Message message, string errorMessage)
{
SetException(message, new RedisServerException(errorMessage));
}
public static void SetException(Message message, Exception ex)
{
var box = message?.ResultBox;
box?.SetException(ex);
}
// true if ready to be completed (i.e. false if re-issued to another server)
public virtual bool SetResult(PhysicalConnection connection, Message message, in RawResult result)
{
var bridge = connection.BridgeCouldBeNull;
if (message is LoggingMessage logging)
{
try
{
logging.Log?.WriteLine($"Response from {bridge?.Name} / {message.CommandAndKey}: {result}");
}
catch { }
}
if (result.IsError)
{
if (result.StartsWith(CommonReplies.NOAUTH)) bridge?.Multiplexer?.SetAuthSuspect();
var server = bridge.ServerEndPoint;
bool log = !message.IsInternalCall;
bool isMoved = result.StartsWith(CommonReplies.MOVED);
bool wasNoRedirect = (message.Flags & CommandFlags.NoRedirect) != 0;
string err = string.Empty;
bool unableToConnectError = false;
bool hashslotMigratedAndNoRedirectError = false;
int hashSlot = -1;
EndPoint endpoint = null;
if (isMoved || result.StartsWith(CommonReplies.ASK))
{
message.SetResponseReceived();
log = false;
string[] parts = result.GetString().Split(StringSplits.Space, 4);
if (Format.TryParseInt32(parts[1], out hashSlot)
&& (endpoint = Format.TryParseEndPoint(parts[2])) != null)
{
// no point sending back to same server, and no point sending to a dead server
if (!Equals(server.EndPoint, endpoint))
{
if (bridge == null)
{ } // already toast
else if (bridge.Multiplexer.TryResend(hashSlot, message, endpoint, isMoved))
{
bridge.Multiplexer.Trace(message.Command + " re-issued to " + endpoint, isMoved ? "MOVED" : "ASK");
return false;
}
else
{
if (isMoved && wasNoRedirect)
{
hashslotMigratedAndNoRedirectError = true;
err = $"Key has MOVED to Endpoint {endpoint} and hashslot {hashSlot} but CommandFlags.NoRedirect was specified - redirect not followed for {message.CommandAndKey}. ";
}
else
{
unableToConnectError = true;
err = $"Endpoint {endpoint} serving hashslot {hashSlot} is not reachable at this point of time. Please check connectTimeout value. If it is low, try increasing it to give the ConnectionMultiplexer a chance to recover from the network disconnect. "
+ PerfCounterHelper.GetThreadPoolAndCPUSummary(bridge.Multiplexer.IncludePerformanceCountersInExceptions);
}
}
}
}
}
if (string.IsNullOrWhiteSpace(err))
{
err = result.GetString();
}
if (log)
{
bridge.Multiplexer.OnErrorMessage(server.EndPoint, err);
}
bridge?.Multiplexer?.Trace("Completed with error: " + err + " (" + GetType().Name + ")", ToString());
if (unableToConnectError)
{
ConnectionFail(message, ConnectionFailureType.UnableToConnect, err);
}
// if this message has an error due to the hashslot being moved, and the command has been marked as NO REDIRECT.
else if(hashslotMigratedAndNoRedirectError && endpoint != null)
{
HashSlotMigratedAndNoRedirectAllowedFail(message, hashSlot, Format.ToString(endpoint), err);
}
else
{
ServerFail(message, err);
}
}
else
{
bool coreResult = SetResultCore(connection, message, result);
if (coreResult)
{
bridge?.Multiplexer?.Trace("Completed with success: " + result.ToString() + " (" + GetType().Name + ")", ToString());
}
else
{
UnexpectedResponse(message, result);
}
}
return true;
}
protected abstract bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result);
private void UnexpectedResponse(Message message, in RawResult result)
{
ConnectionMultiplexer.TraceWithoutContext("From " + GetType().Name, "Unexpected Response");
ConnectionFail(message, ConnectionFailureType.ProtocolFailure, "Unexpected response to " + (message?.Command.ToString() ?? "n/a") + ": " + result.ToString());
}
public sealed class TimeSpanProcessor : ResultProcessor<TimeSpan?>
{
private readonly bool isMilliseconds;
public TimeSpanProcessor(bool isMilliseconds)
{
this.isMilliseconds = isMilliseconds;
}
public bool TryParse(in RawResult result, out TimeSpan? expiry)
{
switch (result.Type)
{
case ResultType.Integer:
long time;
if (result.TryGetInt64(out time))
{
if (time < 0)
{
expiry = null;
}
else if (isMilliseconds)
{
expiry = TimeSpan.FromMilliseconds(time);
}
else
{
expiry = TimeSpan.FromSeconds(time);
}
return true;
}
break;
// e.g. OBJECT IDLETIME on a key that doesn't exist
case ResultType.BulkString when result.IsNull:
expiry = null;
return true;
}
expiry = null;
return false;
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (TryParse(result, out TimeSpan? expiry))
{
SetResult(message, expiry);
return true;
}
return false;
}
}
public sealed class TimingProcessor : ResultProcessor<TimeSpan>
{
private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
public static TimerMessage CreateMessage(int db, CommandFlags flags, RedisCommand command, RedisValue value = default(RedisValue))
{
return new TimerMessage(db, flags, command, value);
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (result.Type == ResultType.Error)
{
return false;
}
else
{ // don't check the actual reply; there are multiple ways of constructing
// a timing message, and we don't actually care about what approach was used
TimeSpan duration;
if (message is TimerMessage timingMessage)
{
var timestampDelta = Stopwatch.GetTimestamp() - timingMessage.StartedWritingTimestamp;
var ticks = (long)(TimestampToTicks * timestampDelta);
duration = new TimeSpan(ticks);
}
else
{
duration = TimeSpan.MaxValue;
}
SetResult(message, duration);
return true;
}
}
internal sealed class TimerMessage : Message
{
public long StartedWritingTimestamp;
private readonly RedisValue value;
public TimerMessage(int db, CommandFlags flags, RedisCommand command, RedisValue value)
: base(db, flags, command)
{
this.value = value;
}
protected override void WriteImpl(PhysicalConnection physical)
{
StartedWritingTimestamp = Stopwatch.GetTimestamp();
if (value.IsNull)
{
physical.WriteHeader(command, 0);
}
else
{
physical.WriteHeader(command, 1);
physical.WriteBulkString(value);
}
}
public override int ArgCount => value.IsNull ? 0 : 1;
}
}
public sealed class TrackSubscriptionsProcessor : ResultProcessor<bool>
{
private ConnectionMultiplexer.Subscription Subscription { get; }
public TrackSubscriptionsProcessor(ConnectionMultiplexer.Subscription sub) => Subscription = sub;
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (result.Type == ResultType.MultiBulk)
{
var items = result.GetItems();
if (items.Length >= 3 && items[2].TryGetInt64(out long count))
{
connection.SubscriptionCount = count;
SetResult(message, true);
var newServer = message.Command switch
{
RedisCommand.SUBSCRIBE or RedisCommand.PSUBSCRIBE => connection.BridgeCouldBeNull?.ServerEndPoint,
_ => null
};
Subscription?.SetCurrentServer(newServer);
return true;
}
}
SetResult(message, false);
return false;
}
}
internal sealed class DemandZeroOrOneProcessor : ResultProcessor<bool>
{
public static bool TryGet(in RawResult result, out bool value)
{
switch (result.Type)
{
case ResultType.Integer:
case ResultType.SimpleString:
case ResultType.BulkString:
if (result.IsEqual(CommonReplies.one)) { value = true; return true; }
else if (result.IsEqual(CommonReplies.zero)) { value = false; return true; }
break;
}
value = false;
return false;
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (TryGet(result, out bool value))
{
SetResult(message, value);
return true;
}
return false;
}
}
internal sealed class ScriptLoadProcessor : ResultProcessor<byte[]>
{
private static readonly Regex sha1 = new Regex("^[0-9a-f]{40}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
internal static bool IsSHA1(string script)
{
return script != null && sha1.IsMatch(script);
}
internal const int Sha1HashLength = 20;
internal static byte[] ParseSHA1(byte[] value)
{
if (value?.Length == Sha1HashLength * 2)
{
var tmp = new byte[Sha1HashLength];
int charIndex = 0;
for (int i = 0; i < tmp.Length; i++)
{
int x = FromHex((char)value[charIndex++]), y = FromHex((char)value[charIndex++]);
if (x < 0 || y < 0) return null;
tmp[i] = (byte)((x << 4) | y);
}
return tmp;
}
return null;
}
internal static byte[] ParseSHA1(string value)
{
if (value?.Length == (Sha1HashLength * 2) && sha1.IsMatch(value))
{
var tmp = new byte[Sha1HashLength];
int charIndex = 0;
for (int i = 0; i < tmp.Length; i++)
{
int x = FromHex(value[charIndex++]), y = FromHex(value[charIndex++]);
if (x < 0 || y < 0) return null;
tmp[i] = (byte)((x << 4) | y);
}
return tmp;
}
return null;
}
private static int FromHex(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
// note that top-level error messages still get handled by SetResult, but nested errors
// (is that a thing?) will be wrapped in the RedisResult
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Type)
{
case ResultType.BulkString:
var asciiHash = result.GetBlob();
if (asciiHash == null || asciiHash.Length != (Sha1HashLength * 2)) return false;
byte[] hash = null;
if (!message.IsInternalCall)
{
hash = ParseSHA1(asciiHash); // external caller wants the hex bytes, not the ASCII bytes
}
if (message is RedisDatabase.ScriptLoadMessage sl)
{
connection.BridgeCouldBeNull?.ServerEndPoint?.AddScript(sl.Script, asciiHash);
}
SetResult(message, hash);
return true;
}
return false;
}
}
internal sealed class SortedSetEntryProcessor : ResultProcessor<SortedSetEntry?>
{
public static bool TryParse(in RawResult result, out SortedSetEntry? entry)
{
switch (result.Type)
{
case ResultType.MultiBulk:
var arr = result.GetItems();
if (result.IsNull || arr.Length < 2)
{
entry = null;
}
else
{
entry = new SortedSetEntry(arr[0].AsRedisValue(), arr[1].TryGetDouble(out double val) ? val : double.NaN);
}
return true;
default:
entry = null;
return false;
}
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (TryParse(result, out SortedSetEntry? entry))
{
SetResult(message, entry);
return true;
}
return false;
}
}
internal sealed class SortedSetEntryArrayProcessor : ValuePairInterleavedProcessorBase<SortedSetEntry>
{
protected override SortedSetEntry Parse(in RawResult first, in RawResult second)
{
return new SortedSetEntry(first.AsRedisValue(), second.TryGetDouble(out double val) ? val : double.NaN);
}
}
internal sealed class HashEntryArrayProcessor : ValuePairInterleavedProcessorBase<HashEntry>
{
protected override HashEntry Parse(in RawResult first, in RawResult second)
{
return new HashEntry(first.AsRedisValue(), second.AsRedisValue());
}
}
internal abstract class ValuePairInterleavedProcessorBase<T> : ResultProcessor<T[]>
{
public bool TryParse(in RawResult result, out T[] pairs)
=> TryParse(result, out pairs, false, out _);
public bool TryParse(in RawResult result, out T[] pairs, bool allowOversized, out int count)
{
count = 0;
switch (result.Type)
{
case ResultType.MultiBulk:
var arr = result.GetItems();
if (result.IsNull)
{
pairs = null;
}
else
{
count = (int)arr.Length / 2;
if (count == 0)
{
pairs = Array.Empty<T>();
}
else
{
pairs = allowOversized ? ArrayPool<T>.Shared.Rent(count) : new T[count];
if (arr.IsSingleSegment)
{
var span = arr.FirstSpan;
int offset = 0;
for (int i = 0; i < count; i++)
{
pairs[i] = Parse(span[offset++], span[offset++]);
}
}
else
{
var iter = arr.GetEnumerator(); // simplest way of getting successive values
for (int i = 0; i < count; i++)
{
pairs[i] = Parse(iter.GetNext(), iter.GetNext());
}
}
}
}
return true;
default:
pairs = null;
return false;
}
}
protected abstract T Parse(in RawResult first, in RawResult second);
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (TryParse(result, out T[] arr))
{
SetResult(message, arr);
return true;
}
return false;
}
}
internal sealed class AutoConfigureProcessor : ResultProcessor<bool>
{
private LogProxy Log { get; }
public AutoConfigureProcessor(LogProxy log = null) => Log = log;
public override bool SetResult(PhysicalConnection connection, Message message, in RawResult result)
{
if (result.IsError && result.StartsWith(CommonReplies.READONLY))
{
var bridge = connection.BridgeCouldBeNull;
if (bridge != null)
{
var server = bridge.ServerEndPoint;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured role: replica");
server.IsReplica = true;
}
}
return base.SetResult(connection, message, result);
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
var server = connection.BridgeCouldBeNull?.ServerEndPoint;
if (server == null) return false;
switch (result.Type)
{
case ResultType.BulkString:
if (message?.Command == RedisCommand.INFO)
{
string info = result.GetString(), line;
if (string.IsNullOrWhiteSpace(info))
{
SetResult(message, true);
return true;
}
string primaryHost = null, primaryPort = null;
bool roleSeen = false;
using (var reader = new StringReader(info))
{
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("# ")) continue;
string val;
if ((val = Extract(line, "role:")) != null)
{
roleSeen = true;
switch (val)
{
case "master":
server.IsReplica = false;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) role: primary");
break;
case "replica":
case "slave":
server.IsReplica = true;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) role: replica");
break;
}
}
else if ((val = Extract(line, "master_host:")) != null)
{
primaryHost = val;
}
else if ((val = Extract(line, "master_port:")) != null)
{
primaryPort = val;
}
else if ((val = Extract(line, "redis_version:")) != null)
{
if (Version.TryParse(val, out Version version))
{
server.Version = version;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) version: " + version);
}
}
else if ((val = Extract(line, "redis_mode:")) != null)
{
switch (val)
{
case "standalone":
server.ServerType = ServerType.Standalone;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) server-type: standalone");
break;
case "cluster":
server.ServerType = ServerType.Cluster;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) server-type: cluster");
break;
case "sentinel":
server.ServerType = ServerType.Sentinel;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (INFO) server-type: sentinel");
break;
}
}
else if ((val = Extract(line, "run_id:")) != null)
{
server.RunId = val;
}
}
if (roleSeen)
{
// These are in the same section, if present
server.PrimaryEndPoint = Format.TryParseEndPoint(primaryHost, primaryPort);
}
}
}
else if (message?.Command == RedisCommand.SENTINEL)
{
server.ServerType = ServerType.Sentinel;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (SENTINEL) server-type: sentinel");
}
SetResult(message, true);
return true;
case ResultType.MultiBulk:
if (message?.Command == RedisCommand.CONFIG)
{
var iter = result.GetItems().GetEnumerator();
while(iter.MoveNext())
{
ref RawResult key = ref iter.Current;
if (!iter.MoveNext()) break;
ref RawResult val = ref iter.Current;
if (key.IsEqual(CommonReplies.timeout) && val.TryGetInt64(out long i64))
{
// note the configuration is in seconds
int timeoutSeconds = checked((int)i64), targetSeconds;
if (timeoutSeconds > 0)
{
if (timeoutSeconds >= 60)
{
targetSeconds = timeoutSeconds - 20; // time to spare...
}
else
{
targetSeconds = (timeoutSeconds * 3) / 4;
}
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (CONFIG) timeout: " + targetSeconds + "s");
server.WriteEverySeconds = targetSeconds;
}
}
else if (key.IsEqual(CommonReplies.databases) && val.TryGetInt64(out i64))
{
int dbCount = checked((int)i64);
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (CONFIG) databases: " + dbCount);
server.Databases = dbCount;
}
else if (key.IsEqual(CommonReplies.slave_read_only) || key.IsEqual(CommonReplies.replica_read_only))
{
if (val.IsEqual(CommonReplies.yes))
{
server.ReplicaReadOnly = true;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (CONFIG) read-only replica: true");
}
else if (val.IsEqual(CommonReplies.no))
{
server.ReplicaReadOnly = false;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (CONFIG) read-only replica: false");
}
}
}
}
else if (message?.Command == RedisCommand.SENTINEL)
{
server.ServerType = ServerType.Sentinel;
Log?.WriteLine($"{Format.ToString(server)}: Auto-configured (SENTINEL) server-type: sentinel");
}
SetResult(message, true);
return true;
}
return false;
}
private static string Extract(string line, string prefix)
{
if (line.StartsWith(prefix)) return line.Substring(prefix.Length).Trim();
return null;
}
}
private sealed class BooleanProcessor : ResultProcessor<bool>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
if (result.IsNull)
{
SetResult(message, false); // lots of ops return (nil) when they mean "no"
return true;
}
switch (result.Type)
{
case ResultType.SimpleString:
if (result.IsEqual(CommonReplies.OK))
{
SetResult(message, true);
}
else
{
SetResult(message, result.GetBoolean());
}
return true;
case ResultType.Integer:
case ResultType.BulkString:
SetResult(message, result.GetBoolean());
return true;
case ResultType.MultiBulk:
var items = result.GetItems();
if (items.Length == 1)
{ // treat an array of 1 like a single reply (for example, SCRIPT EXISTS)
SetResult(message, items[0].GetBoolean());
return true;
}
break;
}
return false;
}
}
private sealed class ByteArrayProcessor : ResultProcessor<byte[]>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Type)
{
case ResultType.BulkString:
SetResult(message, result.GetBlob());
return true;
}
return false;
}
}
private sealed class ClusterNodesProcessor : ResultProcessor<ClusterConfiguration>
{
internal static ClusterConfiguration Parse(PhysicalConnection connection, string nodes)
{
var bridge = connection.BridgeCouldBeNull;
if (bridge == null) throw new ObjectDisposedException(connection.ToString());
var server = bridge.ServerEndPoint;
var config = new ClusterConfiguration(bridge.Multiplexer.ServerSelectionStrategy, nodes, server.EndPoint);
server.SetClusterConfiguration(config);
return config;
}
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Type)
{
case ResultType.BulkString:
string nodes = result.GetString();
var bridge = connection.BridgeCouldBeNull;
if (bridge != null) bridge.ServerEndPoint.ServerType = ServerType.Cluster;
var config = Parse(connection, nodes);
SetResult(message, config);
return true;
}
return false;
}
}
private sealed class ClusterNodesRawProcessor : ResultProcessor<string>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Type)
{
case ResultType.Integer:
case ResultType.SimpleString:
case ResultType.BulkString:
string nodes = result.GetString();
try
{ ClusterNodesProcessor.Parse(connection, nodes); }
catch
{ /* tralalalala */}
SetResult(message, nodes);
return true;
}
return false;
}
}
private sealed class ConnectionIdentityProcessor : ResultProcessor<EndPoint>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
SetResult(message, connection.BridgeCouldBeNull?.ServerEndPoint?.EndPoint);
return true;
}
}
private sealed class DateTimeProcessor : ResultProcessor<DateTime>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
long unixTime;
switch (result.Type)
{
case ResultType.Integer:
if (result.TryGetInt64(out unixTime))
{
var time = RedisBase.UnixEpoch.AddSeconds(unixTime);
SetResult(message, time);
return true;
}
break;
case ResultType.MultiBulk:
var arr = result.GetItems();
switch (arr.Length)
{
case 1:
if (arr.FirstSpan[0].TryGetInt64(out unixTime))
{
var time = RedisBase.UnixEpoch.AddSeconds(unixTime);
SetResult(message, time);
return true;
}
break;
case 2:
if (arr[0].TryGetInt64(out unixTime) && arr[1].TryGetInt64(out long micros))
{
var time = RedisBase.UnixEpoch.AddSeconds(unixTime).AddTicks(micros * 10); // DateTime ticks are 100ns
SetResult(message, time);
return true;
}
break;
}
break;
}
return false;
}
}
private sealed class DoubleProcessor : ResultProcessor<double>
{
protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result)
{
switch (result.Type)
{