-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
PhysicalConnection.cs
1875 lines (1678 loc) · 77.8 KB
/
PhysicalConnection.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.Buffers.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Pipelines.Sockets.Unofficial;
using Pipelines.Sockets.Unofficial.Arenas;
namespace StackExchange.Redis
{
internal sealed partial class PhysicalConnection : IDisposable
{
internal readonly byte[] ChannelPrefix;
private const int DefaultRedisDatabaseCount = 16;
private static readonly CommandBytes message = "message", pmessage = "pmessage";
private static readonly Message[] ReusableChangeDatabaseCommands = Enumerable.Range(0, DefaultRedisDatabaseCount).Select(
i => Message.Create(i, CommandFlags.FireAndForget, RedisCommand.SELECT)).ToArray();
private static readonly Message
ReusableReadOnlyCommand = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.READONLY),
ReusableReadWriteCommand = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.READWRITE);
private static int totalCount;
private readonly ConnectionType connectionType;
// things sent to this physical, but not yet received
private readonly Queue<Message> _writtenAwaitingResponse = new Queue<Message>();
private readonly string _physicalName;
private volatile int currentDatabase = 0;
private ReadMode currentReadMode = ReadMode.NotSpecified;
private int failureReported;
private int lastWriteTickCount, lastReadTickCount, lastBeatTickCount;
internal void GetBytes(out long sent, out long received)
{
if (_ioPipe is IMeasuredDuplexPipe sc)
{
sent = sc.TotalBytesSent;
received = sc.TotalBytesReceived;
}
else
{
sent = received = -1;
}
}
private IDuplexPipe _ioPipe;
internal bool HasOutputPipe => _ioPipe?.Output != null;
private Socket _socket;
internal Socket VolatileSocket => Volatile.Read(ref _socket);
public PhysicalConnection(PhysicalBridge bridge)
{
lastWriteTickCount = lastReadTickCount = Environment.TickCount;
lastBeatTickCount = 0;
connectionType = bridge.ConnectionType;
_bridge = new WeakReference(bridge);
ChannelPrefix = bridge.Multiplexer.RawConfig.ChannelPrefix;
if (ChannelPrefix?.Length == 0) ChannelPrefix = null; // null tests are easier than null+empty
var endpoint = bridge.ServerEndPoint.EndPoint;
_physicalName = connectionType + "#" + Interlocked.Increment(ref totalCount) + "@" + Format.ToString(endpoint);
OnCreateEcho();
}
internal async Task BeginConnectAsync(LogProxy log)
{
var bridge = BridgeCouldBeNull;
var endpoint = bridge?.ServerEndPoint?.EndPoint;
if (endpoint == null)
{
log?.LogError(new ArgumentNullException(nameof(endpoint)), "No endpoint");
return;
}
Trace("Connecting...");
_socket = SocketManager.CreateSocket(endpoint);
bridge.Multiplexer.RawConfig.BeforeSocketConnect?.Invoke(endpoint, bridge.ConnectionType, _socket);
bridge.Multiplexer.OnConnecting(endpoint, bridge.ConnectionType);
log?.LogInfo($"{Format.ToString(endpoint)}: BeginConnectAsync");
CancellationTokenSource timeoutSource = null;
try
{
using (var args = new SocketAwaitableEventArgs
{
RemoteEndPoint = endpoint,
})
{
var x = VolatileSocket;
if (x == null)
{
args.Abort();
}
else if (x.ConnectAsync(args))
{ // asynchronous operation is pending
timeoutSource = ConfigureTimeout(args, bridge.Multiplexer.RawConfig.ConnectTimeout);
}
else
{ // completed synchronously
args.Complete();
}
// Complete connection
try
{
// If we're told to ignore connect, abort here
if (BridgeCouldBeNull?.Multiplexer?.IgnoreConnect ?? false) return;
await args; // wait for the connect to complete or fail (will throw)
if (timeoutSource != null)
{
timeoutSource.Cancel();
timeoutSource.Dispose();
}
x = VolatileSocket;
if (x == null)
{
ConnectionMultiplexer.TraceWithoutContext("Socket was already aborted");
}
else if (await ConnectedAsync(x, log, bridge.Multiplexer.SocketManager).ForAwait())
{
log?.LogInfo($"{Format.ToString(endpoint)}: Starting read");
try
{
StartReading();
// Normal return
}
catch (Exception ex)
{
ConnectionMultiplexer.TraceWithoutContext(ex.Message);
Shutdown();
}
}
else
{
ConnectionMultiplexer.TraceWithoutContext("Aborting socket");
Shutdown();
}
}
catch (ObjectDisposedException ex)
{
log?.LogError(ex, $"{Format.ToString(endpoint)}: (socket shutdown)");
try { RecordConnectionFailed(ConnectionFailureType.UnableToConnect, isInitialConnect: true); }
catch (Exception inner)
{
ConnectionMultiplexer.TraceWithoutContext(inner.Message);
}
}
catch (Exception outer)
{
ConnectionMultiplexer.TraceWithoutContext(outer.Message);
try { RecordConnectionFailed(ConnectionFailureType.UnableToConnect, isInitialConnect: true); }
catch (Exception inner)
{
ConnectionMultiplexer.TraceWithoutContext(inner.Message);
}
}
}
}
catch (NotImplementedException ex) when (endpoint is not IPEndPoint)
{
throw new InvalidOperationException("BeginConnect failed with NotImplementedException; consider using IP endpoints, or enable ResolveDns in the configuration", ex);
}
finally
{
if (timeoutSource != null) try { timeoutSource.Dispose(); } catch { }
}
}
private static CancellationTokenSource ConfigureTimeout(SocketAwaitableEventArgs args, int timeoutMilliseconds)
{
var cts = new CancellationTokenSource();
var timeout = Task.Delay(timeoutMilliseconds, cts.Token);
timeout.ContinueWith((_, state) =>
{
try
{
var a = (SocketAwaitableEventArgs)state;
a.Abort(SocketError.TimedOut);
Socket.CancelConnectAsync(a);
}
catch { }
}, args);
return cts;
}
private enum ReadMode : byte
{
NotSpecified,
ReadOnly,
ReadWrite,
}
private readonly WeakReference _bridge;
public PhysicalBridge BridgeCouldBeNull => (PhysicalBridge)_bridge.Target;
public long LastWriteSecondsAgo => unchecked(Environment.TickCount - Thread.VolatileRead(ref lastWriteTickCount)) / 1000;
private bool IncludeDetailInExceptions => BridgeCouldBeNull?.Multiplexer.RawConfig.IncludeDetailInExceptions ?? false;
[Conditional("VERBOSE")]
internal void Trace(string message) => BridgeCouldBeNull?.Multiplexer?.Trace(message, ToString());
public long SubscriptionCount { get; set; }
public bool TransactionActive { get; internal set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal void Shutdown()
{
var ioPipe = Interlocked.Exchange(ref _ioPipe, null); // compare to the critical read
var socket = Interlocked.Exchange(ref _socket, null);
if (ioPipe != null)
{
Trace("Disconnecting...");
try { BridgeCouldBeNull?.OnDisconnected(ConnectionFailureType.ConnectionDisposed, this, out _, out _); } catch { }
try { ioPipe.Input?.CancelPendingRead(); } catch { }
try { ioPipe.Input?.Complete(); } catch { }
try { ioPipe.Output?.CancelPendingFlush(); } catch { }
try { ioPipe.Output?.Complete(); } catch { }
try { using (ioPipe as IDisposable) { } } catch { }
}
if (socket != null)
{
try { socket.Shutdown(SocketShutdown.Both); } catch { }
try { socket.Close(); } catch { }
try { socket.Dispose(); } catch { }
}
}
public void Dispose()
{
bool markDisposed = VolatileSocket != null;
Shutdown();
if (markDisposed)
{
Trace("Disconnected");
RecordConnectionFailed(ConnectionFailureType.ConnectionDisposed);
}
OnCloseEcho();
_arena.Dispose();
_reusableFlushSyncTokenSource?.Dispose();
GC.SuppressFinalize(this);
}
private async Task AwaitedFlush(ValueTask<FlushResult> flush)
{
await flush.ForAwait();
_writeStatus = WriteStatus.Flushed;
UpdateLastWriteTime();
}
internal void UpdateLastWriteTime() => Interlocked.Exchange(ref lastWriteTickCount, Environment.TickCount);
public Task FlushAsync()
{
var tmp = _ioPipe?.Output;
if (tmp != null)
{
_writeStatus = WriteStatus.Flushing;
var flush = tmp.FlushAsync();
if (!flush.IsCompletedSuccessfully)
{
return AwaitedFlush(flush);
}
_writeStatus = WriteStatus.Flushed;
UpdateLastWriteTime();
}
return Task.CompletedTask;
}
internal void SimulateConnectionFailure(SimulatedFailureType failureType)
{
var raiseFailed = false;
if (connectionType == ConnectionType.Interactive)
{
if (failureType.HasFlag(SimulatedFailureType.InteractiveInbound))
{
_ioPipe?.Input.Complete(new Exception("Simulating interactive input failure"));
raiseFailed = true;
}
if (failureType.HasFlag(SimulatedFailureType.InteractiveOutbound))
{
_ioPipe?.Output.Complete(new Exception("Simulating interactive output failure"));
raiseFailed = true;
}
}
else if (connectionType == ConnectionType.Subscription)
{
if (failureType.HasFlag(SimulatedFailureType.SubscriptionInbound))
{
_ioPipe?.Input.Complete(new Exception("Simulating subscription input failure"));
raiseFailed = true;
}
if (failureType.HasFlag(SimulatedFailureType.SubscriptionOutbound))
{
_ioPipe?.Output.Complete(new Exception("Simulating subscription output failure"));
raiseFailed = true;
}
}
if (raiseFailed)
{
RecordConnectionFailed(ConnectionFailureType.SocketFailure);
}
}
public void RecordConnectionFailed(
ConnectionFailureType failureType,
Exception innerException = null,
[CallerMemberName] string origin = null,
bool isInitialConnect = false,
IDuplexPipe connectingPipe = null
)
{
Exception outerException = innerException;
IdentifyFailureType(innerException, ref failureType);
var bridge = BridgeCouldBeNull;
if (_ioPipe != null || isInitialConnect) // if *we* didn't burn the pipe: flag it
{
if (failureType == ConnectionFailureType.InternalFailure) OnInternalError(innerException, origin);
// stop anything new coming in...
bridge?.Trace("Failed: " + failureType);
ConnectionStatus connStatus = ConnectionStatus.Default;
PhysicalBridge.State oldState = PhysicalBridge.State.Disconnected;
bool isCurrent = false;
bridge?.OnDisconnected(failureType, this, out isCurrent, out oldState);
if (oldState == PhysicalBridge.State.ConnectedEstablished)
{
try
{
connStatus = GetStatus();
}
catch { /* best effort only */ }
}
if (isCurrent && Interlocked.CompareExchange(ref failureReported, 1, 0) == 0)
{
int now = Environment.TickCount, lastRead = Thread.VolatileRead(ref lastReadTickCount), lastWrite = Thread.VolatileRead(ref lastWriteTickCount),
lastBeat = Thread.VolatileRead(ref lastBeatTickCount);
int unansweredWriteTime = 0;
lock (_writtenAwaitingResponse)
{
// find oldest message awaiting a response
if (_writtenAwaitingResponse.Count != 0)
{
var next = _writtenAwaitingResponse.Peek();
unansweredWriteTime = next.GetWriteTime();
}
}
var exMessage = new StringBuilder(failureType.ToString());
var pipe = connectingPipe ?? _ioPipe;
if (pipe is SocketConnection sc)
{
exMessage.Append(" (").Append(sc.ShutdownKind);
if (sc.SocketError != SocketError.Success)
{
exMessage.Append('/').Append(sc.SocketError);
}
if (sc.BytesRead == 0) exMessage.Append(", 0-read");
if (sc.BytesSent == 0) exMessage.Append(", 0-sent");
exMessage.Append(", last-recv: ").Append(sc.LastReceived).Append(')');
}
else if (pipe is IMeasuredDuplexPipe mdp)
{
long sent = mdp.TotalBytesSent, recd = mdp.TotalBytesReceived;
if (sent == 0) { exMessage.Append(recd == 0 ? " (0-read, 0-sent)" : " (0-sent)"); }
else if (recd == 0) { exMessage.Append(" (0-read)"); }
}
var data = new List<Tuple<string, string>>();
void add(string lk, string sk, string v)
{
if (lk != null) data.Add(Tuple.Create(lk, v));
if (sk != null) exMessage.Append(", ").Append(sk).Append(": ").Append(v);
}
if (IncludeDetailInExceptions)
{
if (bridge != null)
{
exMessage.Append(" on ").Append(Format.ToString(bridge.ServerEndPoint?.EndPoint)).Append('/').Append(connectionType)
.Append(", ").Append(_writeStatus).Append('/').Append(_readStatus)
.Append(", last: ").Append(bridge.LastCommand);
data.Add(Tuple.Create("FailureType", failureType.ToString()));
data.Add(Tuple.Create("EndPoint", Format.ToString(bridge.ServerEndPoint?.EndPoint)));
add("Origin", "origin", origin);
// add("Input-Buffer", "input-buffer", _ioPipe.Input);
add("Outstanding-Responses", "outstanding", GetSentAwaitingResponseCount().ToString());
add("Last-Read", "last-read", (unchecked(now - lastRead) / 1000) + "s ago");
add("Last-Write", "last-write", (unchecked(now - lastWrite) / 1000) + "s ago");
if(unansweredWriteTime != 0) add("Unanswered-Write", "unanswered-write", (unchecked(now - unansweredWriteTime) / 1000) + "s ago");
add("Keep-Alive", "keep-alive", bridge.ServerEndPoint?.WriteEverySeconds + "s");
add("Previous-Physical-State", "state", oldState.ToString());
add("Manager", "mgr", bridge.Multiplexer.SocketManager?.GetState());
if (connStatus.BytesAvailableOnSocket >= 0) add("Inbound-Bytes", "in", connStatus.BytesAvailableOnSocket.ToString());
if (connStatus.BytesInReadPipe >= 0) add("Inbound-Pipe-Bytes", "in-pipe", connStatus.BytesInReadPipe.ToString());
if (connStatus.BytesInWritePipe >= 0) add("Outbound-Pipe-Bytes", "out-pipe", connStatus.BytesInWritePipe.ToString());
add("Last-Heartbeat", "last-heartbeat", (lastBeat == 0 ? "never" : ((unchecked(now - lastBeat) / 1000) + "s ago")) + (BridgeCouldBeNull.IsBeating ? " (mid-beat)" : ""));
var mbeat = bridge.Multiplexer.LastHeartbeatSecondsAgo;
if (mbeat >= 0)
{
add("Last-Multiplexer-Heartbeat", "last-mbeat", mbeat + "s ago");
}
add("Last-Global-Heartbeat", "global", ConnectionMultiplexer.LastGlobalHeartbeatSecondsAgo + "s ago");
}
}
add("Version", "v", Utils.GetLibVersion());
outerException = new RedisConnectionException(failureType, exMessage.ToString(), innerException);
foreach (var kv in data)
{
outerException.Data["Redis-" + kv.Item1] = kv.Item2;
}
bridge?.OnConnectionFailed(this, failureType, outerException);
}
}
// cleanup
lock (_writtenAwaitingResponse)
{
bridge?.Trace(_writtenAwaitingResponse.Count != 0, "Failing outstanding messages: " + _writtenAwaitingResponse.Count);
while (_writtenAwaitingResponse.Count != 0)
{
var next = _writtenAwaitingResponse.Dequeue();
if (next.Command == RedisCommand.QUIT && next.TrySetResult(true))
{
// fine, death of a socket is close enough
next.Complete();
}
else
{
var ex = innerException is RedisException ? innerException : outerException;
if (bridge != null)
{
bridge.Trace("Failing: " + next);
bridge.Multiplexer?.OnMessageFaulted(next, ex, origin);
}
next.SetExceptionAndComplete(ex, bridge);
}
}
}
// burn the socket
Shutdown();
}
internal bool IsIdle() => _writeStatus == WriteStatus.Idle;
internal void SetIdle() => _writeStatus = WriteStatus.Idle;
internal void SetWriting() => _writeStatus = WriteStatus.Writing;
private volatile WriteStatus _writeStatus;
internal WriteStatus GetWriteStatus() => _writeStatus;
internal enum WriteStatus
{
Initializing,
Idle,
Writing,
Flushing,
Flushed,
NA = -1,
}
/// <summary>Returns a string that represents the current object.</summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString() => $"{_physicalName} ({_writeStatus})";
internal static void IdentifyFailureType(Exception exception, ref ConnectionFailureType failureType)
{
if (exception != null && failureType == ConnectionFailureType.InternalFailure)
{
if (exception is AggregateException)
{
exception = exception.InnerException ?? exception;
}
failureType = exception switch
{
AuthenticationException => ConnectionFailureType.AuthenticationFailure,
EndOfStreamException or ObjectDisposedException => ConnectionFailureType.SocketClosed,
SocketException or IOException => ConnectionFailureType.SocketFailure,
_ => failureType
};
}
}
internal void EnqueueInsideWriteLock(Message next)
{
lock (_writtenAwaitingResponse)
{
_writtenAwaitingResponse.Enqueue(next);
}
}
internal void GetCounters(ConnectionCounters counters)
{
lock (_writtenAwaitingResponse)
{
counters.SentItemsAwaitingResponse = _writtenAwaitingResponse.Count;
}
counters.Subscriptions = SubscriptionCount;
}
internal Message GetReadModeCommand(bool isPrimaryOnly)
{
if (BridgeCouldBeNull?.ServerEndPoint?.RequiresReadMode == true)
{
ReadMode requiredReadMode = isPrimaryOnly ? ReadMode.ReadWrite : ReadMode.ReadOnly;
if (requiredReadMode != currentReadMode)
{
currentReadMode = requiredReadMode;
switch (requiredReadMode)
{
case ReadMode.ReadOnly: return ReusableReadOnlyCommand;
case ReadMode.ReadWrite: return ReusableReadWriteCommand;
}
}
}
else if (currentReadMode == ReadMode.ReadOnly)
{
// we don't need it (because we're not a cluster, or not a replica),
// but we are in read-only mode; switch to read-write
currentReadMode = ReadMode.ReadWrite;
return ReusableReadWriteCommand;
}
return null;
}
internal Message GetSelectDatabaseCommand(int targetDatabase, Message message)
{
if (targetDatabase < 0 || targetDatabase == currentDatabase)
{
return null;
}
if (BridgeCouldBeNull?.ServerEndPoint is not ServerEndPoint serverEndpoint)
{
return null;
}
int available = serverEndpoint.Databases;
// Only db0 is available on cluster/twemproxy/envoyproxy
if (!serverEndpoint.SupportsDatabases)
{
if (targetDatabase != 0)
{
// We should never see this, since the API doesn't allow it; thus not too worried about ExceptionFactory
throw new RedisCommandException("Multiple databases are not supported on this server; cannot switch to database: " + targetDatabase);
}
return null;
}
if (message.Command == RedisCommand.SELECT)
{
// This could come from an EVAL/EVALSHA inside a transaction, for example; we'll accept it
BridgeCouldBeNull?.Trace("Switching database: " + targetDatabase);
currentDatabase = targetDatabase;
return null;
}
if (TransactionActive)
{
// Should never see this, since the API doesn't allow it, thus not too worried about ExceptionFactory
throw new RedisCommandException("Multiple databases inside a transaction are not currently supported: " + targetDatabase);
}
// We positively know it is out of range
if (available != 0 && targetDatabase >= available)
{
throw ExceptionFactory.DatabaseOutfRange(IncludeDetailInExceptions, targetDatabase, message, serverEndpoint);
}
BridgeCouldBeNull?.Trace("Switching database: " + targetDatabase);
currentDatabase = targetDatabase;
return GetSelectDatabaseCommand(targetDatabase);
}
internal static Message GetSelectDatabaseCommand(int targetDatabase)
{
return targetDatabase < DefaultRedisDatabaseCount
? ReusableChangeDatabaseCommands[targetDatabase] // 0-15 by default
: Message.Create(targetDatabase, CommandFlags.FireAndForget, RedisCommand.SELECT);
}
internal int GetSentAwaitingResponseCount()
{
lock (_writtenAwaitingResponse)
{
return _writtenAwaitingResponse.Count;
}
}
internal void GetStormLog(StringBuilder sb)
{
lock (_writtenAwaitingResponse)
{
if (_writtenAwaitingResponse.Count == 0) return;
sb.Append("Sent, awaiting response from server: ").Append(_writtenAwaitingResponse.Count).AppendLine();
int total = 0;
foreach (var item in _writtenAwaitingResponse)
{
if (++total >= 500) break;
item.AppendStormLog(sb);
sb.AppendLine();
}
}
}
internal void OnBridgeHeartbeat()
{
var now = Environment.TickCount;
Interlocked.Exchange(ref lastBeatTickCount, now);
lock (_writtenAwaitingResponse)
{
if (_writtenAwaitingResponse.Count != 0 && BridgeCouldBeNull is PhysicalBridge bridge)
{
var server = bridge?.ServerEndPoint;
var timeout = bridge.Multiplexer.AsyncTimeoutMilliseconds;
foreach (var msg in _writtenAwaitingResponse)
{
// We only handle async timeouts here, synchronous timeouts are handled upstream.
// Those sync timeouts happen in ConnectionMultiplexer.ExecuteSyncImpl() via Monitor.Wait.
if (msg.ResultBoxIsAsync && msg.HasTimedOut(now, timeout, out var elapsed))
{
bool haveDeltas = msg.TryGetPhysicalState(out _, out _, out long sentDelta, out var receivedDelta) && sentDelta >= 0 && receivedDelta >= 0;
var timeoutEx = ExceptionFactory.Timeout(bridge.Multiplexer, haveDeltas
? $"Timeout awaiting response (outbound={sentDelta >> 10}KiB, inbound={receivedDelta >> 10}KiB, {elapsed}ms elapsed, timeout is {timeout}ms)"
: $"Timeout awaiting response ({elapsed}ms elapsed, timeout is {timeout}ms)", msg, server);
bridge.Multiplexer?.OnMessageFaulted(msg, timeoutEx);
msg.SetExceptionAndComplete(timeoutEx, bridge); // tell the message that it is doomed
bridge.Multiplexer.OnAsyncTimeout();
}
// Note: it is important that we **do not** remove the message unless we're tearing down the socket; that
// would disrupt the chain for MatchResult; we just preemptively abort the message from the caller's
// perspective, and set a flag on the message so we don't keep doing it
}
}
}
}
internal void OnInternalError(Exception exception, [CallerMemberName] string origin = null)
{
if (BridgeCouldBeNull is PhysicalBridge bridge)
{
bridge.Multiplexer.OnInternalError(exception, bridge.ServerEndPoint.EndPoint, connectionType, origin);
}
}
internal void SetUnknownDatabase()
{
// forces next db-specific command to issue a select
currentDatabase = -1;
}
internal void Write(in RedisKey key)
{
var val = key.KeyValue;
if (val is string s)
{
WriteUnifiedPrefixedString(_ioPipe.Output, key.KeyPrefix, s);
}
else
{
WriteUnifiedPrefixedBlob(_ioPipe.Output, key.KeyPrefix, (byte[])val);
}
}
internal void Write(in RedisChannel channel)
=> WriteUnifiedPrefixedBlob(_ioPipe.Output, ChannelPrefix, channel.Value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void WriteBulkString(in RedisValue value)
=> WriteBulkString(value, _ioPipe.Output);
internal static void WriteBulkString(in RedisValue value, PipeWriter output)
{
switch (value.Type)
{
case RedisValue.StorageType.Null:
WriteUnifiedBlob(output, (byte[])null);
break;
case RedisValue.StorageType.Int64:
WriteUnifiedInt64(output, value.OverlappedValueInt64);
break;
case RedisValue.StorageType.UInt64:
WriteUnifiedUInt64(output, value.OverlappedValueUInt64);
break;
case RedisValue.StorageType.Double: // use string
case RedisValue.StorageType.String:
WriteUnifiedPrefixedString(output, null, (string)value);
break;
case RedisValue.StorageType.Raw:
WriteUnifiedSpan(output, ((ReadOnlyMemory<byte>)value).Span);
break;
default:
throw new InvalidOperationException($"Unexpected {value.Type} value: '{value}'");
}
}
internal const int REDIS_MAX_ARGS = 1024 * 1024; // there is a <= 1024*1024 max constraint inside redis itself: https://github.com/antirez/redis/blob/6c60526db91e23fb2d666fc52facc9a11780a2a3/src/networking.c#L1024
internal void WriteHeader(RedisCommand command, int arguments, CommandBytes commandBytes = default)
{
var bridge = BridgeCouldBeNull;
if (bridge == null) throw new ObjectDisposedException(ToString());
if (command == RedisCommand.UNKNOWN)
{
// using >= here because we will be adding 1 for the command itself (which is an arg for the purposes of the multi-bulk protocol)
if (arguments >= REDIS_MAX_ARGS) throw ExceptionFactory.TooManyArgs(commandBytes.ToString(), arguments);
}
else
{
// using >= here because we will be adding 1 for the command itself (which is an arg for the purposes of the multi-bulk protocol)
if (arguments >= REDIS_MAX_ARGS) throw ExceptionFactory.TooManyArgs(command.ToString(), arguments);
// for everything that isn't custom commands: ask the muxer for the actual bytes
commandBytes = bridge.Multiplexer.CommandMap.GetBytes(command);
}
// in theory we should never see this; CheckMessage dealt with "regular" messages, and
// ExecuteMessage should have dealt with everything else
if (commandBytes.IsEmpty) throw ExceptionFactory.CommandDisabled(command);
// *{argCount}\r\n = 3 + MaxInt32TextLen
// ${cmd-len}\r\n = 3 + MaxInt32TextLen
// {cmd}\r\n = 2 + commandBytes.Length
var span = _ioPipe.Output.GetSpan(commandBytes.Length + 8 + MaxInt32TextLen + MaxInt32TextLen);
span[0] = (byte)'*';
int offset = WriteRaw(span, arguments + 1, offset: 1);
offset = AppendToSpanCommand(span, commandBytes, offset: offset);
_ioPipe.Output.Advance(offset);
}
internal void RecordQuit() // don't blame redis if we fired the first shot
=> (_ioPipe as SocketConnection)?.TrySetProtocolShutdown(PipeShutdownKind.ProtocolExitClient);
internal static void WriteMultiBulkHeader(PipeWriter output, long count)
{
// *{count}\r\n = 3 + MaxInt32TextLen
var span = output.GetSpan(3 + MaxInt32TextLen);
span[0] = (byte)'*';
int offset = WriteRaw(span, count, offset: 1);
output.Advance(offset);
}
internal const int
MaxInt32TextLen = 11, // -2,147,483,648 (not including the commas)
MaxInt64TextLen = 20; // -9,223,372,036,854,775,808 (not including the commas)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int WriteCrlf(Span<byte> span, int offset)
{
span[offset++] = (byte)'\r';
span[offset++] = (byte)'\n';
return offset;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void WriteCrlf(PipeWriter writer)
{
var span = writer.GetSpan(2);
span[0] = (byte)'\r';
span[1] = (byte)'\n';
writer.Advance(2);
}
internal static int WriteRaw(Span<byte> span, long value, bool withLengthPrefix = false, int offset = 0)
{
if (value >= 0 && value <= 9)
{
if (withLengthPrefix)
{
span[offset++] = (byte)'1';
offset = WriteCrlf(span, offset);
}
span[offset++] = (byte)((int)'0' + (int)value);
}
else if (value >= 10 && value < 100)
{
if (withLengthPrefix)
{
span[offset++] = (byte)'2';
offset = WriteCrlf(span, offset);
}
span[offset++] = (byte)((int)'0' + ((int)value / 10));
span[offset++] = (byte)((int)'0' + ((int)value % 10));
}
else if (value >= 100 && value < 1000)
{
int v = (int)value;
int units = v % 10;
v /= 10;
int tens = v % 10, hundreds = v / 10;
if (withLengthPrefix)
{
span[offset++] = (byte)'3';
offset = WriteCrlf(span, offset);
}
span[offset++] = (byte)((int)'0' + hundreds);
span[offset++] = (byte)((int)'0' + tens);
span[offset++] = (byte)((int)'0' + units);
}
else if (value < 0 && value >= -9)
{
if (withLengthPrefix)
{
span[offset++] = (byte)'2';
offset = WriteCrlf(span, offset);
}
span[offset++] = (byte)'-';
span[offset++] = (byte)((int)'0' - (int)value);
}
else if (value <= -10 && value > -100)
{
if (withLengthPrefix)
{
span[offset++] = (byte)'3';
offset = WriteCrlf(span, offset);
}
value = -value;
span[offset++] = (byte)'-';
span[offset++] = (byte)((int)'0' + ((int)value / 10));
span[offset++] = (byte)((int)'0' + ((int)value % 10));
}
else
{
// we're going to write it, but *to the wrong place*
var availableChunk = span.Slice(offset);
if (!Utf8Formatter.TryFormat(value, availableChunk, out int formattedLength))
{
throw new InvalidOperationException("TryFormat failed");
}
if (withLengthPrefix)
{
// now we know how large the prefix is: write the prefix, then write the value
if (!Utf8Formatter.TryFormat(formattedLength, availableChunk, out int prefixLength))
{
throw new InvalidOperationException("TryFormat failed");
}
offset += prefixLength;
offset = WriteCrlf(span, offset);
availableChunk = span.Slice(offset);
if (!Utf8Formatter.TryFormat(value, availableChunk, out int finalLength))
{
throw new InvalidOperationException("TryFormat failed");
}
offset += finalLength;
Debug.Assert(finalLength == formattedLength);
}
else
{
offset += formattedLength;
}
}
return WriteCrlf(span, offset);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "DEBUG uses instance data")]
private async ValueTask<WriteResult> FlushAsync_Awaited(PhysicalConnection connection, ValueTask<FlushResult> flush, bool throwOnFailure)
{
try
{
await flush.ForAwait();
connection._writeStatus = WriteStatus.Flushed;
connection.UpdateLastWriteTime();
return WriteResult.Success;
}
catch (ConnectionResetException ex) when (!throwOnFailure)
{
connection.RecordConnectionFailed(ConnectionFailureType.SocketClosed, ex);
return WriteResult.WriteFailure;
}
}
CancellationTokenSource _reusableFlushSyncTokenSource;
[Obsolete("this is an anti-pattern; work to reduce reliance on this is in progress")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0062:Make local function 'static'", Justification = "DEBUG uses instance data")]
internal WriteResult FlushSync(bool throwOnFailure, int millisecondsTimeout)
{
var cts = _reusableFlushSyncTokenSource ??= new CancellationTokenSource();
var flush = FlushAsync(throwOnFailure, cts.Token);
if (!flush.IsCompletedSuccessfully)
{
// only schedule cancellation if it doesn't complete synchronously; at this point, it is doomed
_reusableFlushSyncTokenSource = null;
cts.CancelAfter(TimeSpan.FromMilliseconds(millisecondsTimeout));
try
{
// here lies the evil
flush.AsTask().Wait();
}
catch (AggregateException ex) when (ex.InnerExceptions.Any(e => e is TaskCanceledException))
{
ThrowTimeout();
}
finally
{
cts.Dispose();
}
}
return flush.Result;
void ThrowTimeout()
{
throw new TimeoutException("timeout while synchronously flushing");
}
}
internal ValueTask<WriteResult> FlushAsync(bool throwOnFailure, CancellationToken cancellationToken = default)
{
var tmp = _ioPipe?.Output;
if (tmp == null) return new ValueTask<WriteResult>(WriteResult.NoConnectionAvailable);
try
{
_writeStatus = WriteStatus.Flushing;
var flush = tmp.FlushAsync(cancellationToken);
if (!flush.IsCompletedSuccessfully) return FlushAsync_Awaited(this, flush, throwOnFailure);
_writeStatus = WriteStatus.Flushed;
UpdateLastWriteTime();
return new ValueTask<WriteResult>(WriteResult.Success);
}
catch (ConnectionResetException ex) when (!throwOnFailure)
{
RecordConnectionFailed(ConnectionFailureType.SocketClosed, ex);
return new ValueTask<WriteResult>(WriteResult.WriteFailure);
}
}
private static readonly ReadOnlyMemory<byte> NullBulkString = Encoding.ASCII.GetBytes("$-1\r\n"), EmptyBulkString = Encoding.ASCII.GetBytes("$0\r\n\r\n");
private static void WriteUnifiedBlob(PipeWriter writer, byte[] value)
{
if (value == null)
{
// special case:
writer.Write(NullBulkString.Span);
}
else
{
WriteUnifiedSpan(writer, new ReadOnlySpan<byte>(value));
}
}
private static void WriteUnifiedSpan(PipeWriter writer, ReadOnlySpan<byte> value)
{
// ${len}\r\n = 3 + MaxInt32TextLen
// {value}\r\n = 2 + value.Length
const int MaxQuickSpanSize = 512;
if (value.Length == 0)
{
// special case:
writer.Write(EmptyBulkString.Span);
}
else if (value.Length <= MaxQuickSpanSize)
{
var span = writer.GetSpan(5 + MaxInt32TextLen + value.Length);
span[0] = (byte)'$';