-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathConnectionFailoverTests.cs
More file actions
941 lines (829 loc) · 39 KB
/
Copy pathConnectionFailoverTests.cs
File metadata and controls
941 lines (829 loc) · 39 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient.Connection;
using Microsoft.Data.SqlClient.Tests.Common;
using Microsoft.SqlServer.TDS.Servers;
using Xunit;
namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests
{
// TODO: Do we need this collection? It serializes all tests within it, which we probably don't
// need since each test uses its own TDS Server with ephemeral listen port.
[Collection("SimulatedServerTests")]
public class ConnectionFailoverTests
{
//TODO parameterize for transient errors
[Trait("Category", "flaky")]
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public void TransientFault_NoFailover_DoesNotClearPool(uint errorCode)
{
// When connecting to a server with a configured failover partner,
// transient errors returned during the login ack should not clear the connection pool.
// Arrange
using TdsServer failoverServer = new(new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234"
});
failoverServer.Start();
var failoverDataSource = $"localhost,{failoverServer.EndPoint.Port}";
// Errors are off to start to allow the pool to warm up
using TransientTdsErrorTdsServer initialServer = new(new TransientTdsErrorTdsServerArguments
{
FailoverPartner = failoverDataSource
});
initialServer.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + initialServer.EndPoint.Port,
ConnectRetryInterval = 1,
ConnectTimeout = 30,
Encrypt = SqlConnectionEncryptOption.Optional,
InitialCatalog = "test"
};
using SqlConnection connection = new(builder.ConnectionString);
connection.Open();
// Act
initialServer.SetErrorBehavior(true, errorCode);
using SqlConnection secondConnection = new(builder.ConnectionString);
// Should not trigger a failover, will retry against the same server
secondConnection.Open();
// Request a new connection, should initiate a fresh connection attempt if the pool was cleared.
connection.Close();
connection.Open();
// Assert
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal(ConnectionState.Open, secondConnection.State);
Assert.Equal($"localhost,{initialServer.EndPoint.Port}", connection.DataSource);
Assert.Equal($"localhost,{initialServer.EndPoint.Port}", secondConnection.DataSource);
// 1 for the initial connection, 2 for the second connection
Assert.Equal(3, initialServer.PreLoginCount - initialServer.AbandonedPreLoginCount);
// A failover should not be triggered, so prelogin count to the failover server should be 0
Assert.Equal(0, failoverServer.PreLoginCount);
}
[Trait("Category", "flaky")]
[Fact]
public void NetworkError_TriggersFailover_ClearsPool()
{
// When connecting to a server with a configured failover partner,
// network errors returned during prelogin should clear the connection pool.
// Arrange
using TdsServer failoverServer = new(new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234"
});
failoverServer.Start();
var failoverDataSource = $"localhost,{failoverServer.EndPoint.Port}";
// Errors are off to start to allow the pool to warm up
using TdsServer initialServer = new(new TdsServerArguments
{
FailoverPartner = failoverDataSource
});
initialServer.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + initialServer.EndPoint.Port,
ConnectRetryInterval = 1,
ConnectTimeout = 30,
Encrypt = SqlConnectionEncryptOption.Optional,
InitialCatalog = "test",
MultiSubnetFailover = false,
#if NETFRAMEWORK
TransparentNetworkIPResolution = false,
#endif
};
// Open the initial connection to warm up the pool and populate failover partner information
// for the pool group.
using SqlConnection connection = new(builder.ConnectionString);
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{initialServer.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, initialServer.PreLoginCount);
Assert.Equal(0, failoverServer.PreLoginCount);
// Act
// Should trigger a failover because the initial server is unavailable
initialServer.Dispose();
using SqlConnection secondConnection = new(builder.ConnectionString);
secondConnection.Open();
// Assert
Assert.Equal(ConnectionState.Open, secondConnection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", secondConnection.DataSource);
Assert.Equal(1, initialServer.PreLoginCount);
Assert.Equal(1, failoverServer.PreLoginCount);
// Act
// Request a new connection, should initiate a fresh connection attempt if the pool was cleared.
connection.Close();
connection.Open();
// Assert
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, initialServer.PreLoginCount);
Assert.Equal(2, failoverServer.PreLoginCount);
}
[Fact]
public void NetworkTimeout_ShouldFail()
{
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
// Arrange
using TransientDelayTdsServer server = new(
new TransientDelayTdsServerArguments()
{
IsEnabledTransientDelay = true,
DelayDuration = TimeSpan.FromMilliseconds(2000),
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.EndPoint.Port,
InitialCatalog = "master",// Required for failover partner to work
ConnectTimeout = 1,
ConnectRetryInterval = 1,
ConnectRetryCount = 0, // Disable retry
Encrypt = false,
MultiSubnetFailover = false,
#if NETFRAMEWORK
TransparentNetworkIPResolution = false,
#endif
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
Action action = () => connection.Open();
// Assert
SqlException exception = Assert.Throws<SqlException>(action);
Assert.Contains("Connection Timeout Expired", exception.Message);
Assert.Equal(ConnectionState.Closed, connection.State);
Assert.Equal(1, server.PreLoginCount);
Assert.Equal(0, failoverServer.PreLoginCount);
}
[Fact]
public void NetworkDelay_ShouldConnectToPrimary()
{
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
// Arrange
using TransientDelayTdsServer server = new(
new TransientDelayTdsServerArguments()
{
IsEnabledTransientDelay = true,
DelayDuration = TimeSpan.FromMilliseconds(1000),
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.EndPoint.Port,
InitialCatalog = "master", // Required for failover partner to work
ConnectTimeout = 5,
Encrypt = false,
Pooling = false, // Disable pooling to ensure a fresh connection attempt is made
MultiSubnetFailover = false,
#if NETFRAMEWORK
TransparentNetworkIPResolution = false,
#endif
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
connection.Open();
// Assert
// On the first connection attempt, no failover partner information is available,
// so the connection will retry on the same server.
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, server.PreLoginCount);
Assert.Equal(0, failoverServer.PreLoginCount);
}
[Fact]
[Trait("Category", "flaky")]
public void NetworkError_WithUserProvidedPartner_RetryDisabled_ShouldConnectToFailoverPartner()
{
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
// Arrange
using TransientDelayTdsServer server = new(
new TransientDelayTdsServerArguments()
{
IsEnabledTransientDelay = true,
DelayDuration = TimeSpan.FromMilliseconds(10000),
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.EndPoint.Port,
InitialCatalog = "master", // Required for failover partner to work
ConnectTimeout = 5,
ConnectRetryInterval = 1,
ConnectRetryCount = 0, // Disable retry
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}", // User provided failover partner
Encrypt = false,
Pooling = false, // Disable pooling to ensure a fresh connection attempt is made on failover
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
connection.Open();
// Assert
// On the first connection attempt, failover partner information is available in the connection string,
// so the connection will retry on the failover server.
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, failoverServer.PreLoginCount);
Assert.Equal(1, server.PreLoginCount);
}
[Fact]
[Trait("Category", "flaky")]
public void NetworkError_WithUserProvidedPartner_RetryEnabled_ShouldConnectToFailoverPartner()
{
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
// Arrange
using TransientDelayTdsServer server = new(
new TransientDelayTdsServerArguments()
{
IsEnabledTransientDelay = true,
DelayDuration = TimeSpan.FromMilliseconds(10000),
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.EndPoint.Port,
InitialCatalog = "master", // Required for failover partner to work
ConnectTimeout = 5,
ConnectRetryInterval = 1,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}", // User provided failover partner
Encrypt = false,
#if NETFRAMEWORK
TransparentNetworkIPResolution = false,
#endif
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
connection.Open();
// Assert
// On the first connection attempt, failover partner information is available in the connection string,
// so the connection will retry on the failover server.
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, server.PreLoginCount);
Assert.Equal(0, server.Login7Count);
Assert.Equal(1, failoverServer.PreLoginCount - failoverServer.AbandonedPreLoginCount);
}
/// <summary>
/// Verifies login-phase transient SQL errors are retried on the primary endpoint and
/// do not trigger failover-partner alternation.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public void TransientFault_ShouldConnectToPrimary(uint errorCode)
{
// Arrange
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
Pooling = false, // Disable pooling to ensure a fresh connection attempt is made
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
// First login receives the transient token; outer connect retry opens a fresh parser
// and retries against the same primary endpoint.
connection.Open();
// Assert
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
// Failures should prompt the client to return to the original server, resulting in a login count of 2
Assert.Equal(2, server.PreLoginCount - server.AbandonedPreLoginCount);
// Login-phase errors must NOT trigger failover alternation
Assert.Equal(0, failoverServer.PreLoginCount);
}
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[Trait("Category", "flaky")]
public void TransientFault_RetryDisabled_ShouldFail(uint errorCode)
{
// Arrange
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost:1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost:{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
ConnectRetryCount = 0, // Disable retry
Encrypt = false
};
using SqlConnection connection = new(builder.ConnectionString);
try
{
// Act
connection.Open();
}
catch (SqlException e)
{
Assert.Equal((int)errorCode, e.Number);
return;
}
Assert.Fail();
}
/// <summary>
/// Verifies user-provided failover partner does not change behavior for login-phase
/// transient SQL errors; retries stay on primary.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[Trait("Category", "flaky")]
public void TransientFault_WithUserProvidedPartner_ShouldConnectToPrimary(uint errorCode)
{
// Arrange
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost:1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost:{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
FailoverPartner = $"localhost:{failoverServer.EndPoint.Port}", // User provided failover partner
};
using SqlConnection connection = new(builder.ConnectionString);
// Act
// Even with a configured partner, this path should use outer connect retry
// against primary rather than alternation inside LoginWithFailover.
connection.Open();
// Assert
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
// Failures should prompt the client to return to the original server, resulting in a login count of 2
Assert.Equal(2, server.PreLoginCount - server.AbandonedPreLoginCount);
// Login-phase errors must NOT trigger failover alternation
Assert.Equal(0, failoverServer.PreLoginCount);
}
[Trait("Category", "flaky")]
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[Trait("Category", "flaky")]
public void TransientFault_WithUserProvidedPartner_RetryDisabled_ShouldFail(uint errorCode)
{
// Arrange
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost:1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost:{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
ConnectRetryCount = 0, // Disable retry
Encrypt = false,
FailoverPartner = $"localhost:{failoverServer.EndPoint.Port}", // User provided failover partner
};
using SqlConnection connection = new(builder.ConnectionString);
try
{
// Act
connection.Open();
}
catch (SqlException e)
{
Assert.Equal((int)errorCode, e.Number);
return;
}
Assert.Fail();
}
[Fact]
[Trait("Category", "flaky")]
public void TransientFault_IgnoreServerProvidedFailoverPartner_ShouldConnectToUserProvidedPartner()
{
// Arrange
using LocalAppContextSwitchesHelper switchesHelper = new();
switchesHelper.IgnoreServerProvidedFailoverPartner = true;
using TdsServer failoverServer = new(
new TdsServerArguments
{
// Doesn't need to point to a real endpoint, just needs a value specified
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TdsServer server = new(
new TdsServerArguments()
{
// Set an invalid failover partner to ensure that the connection fails if the
// server provided failover partner is used.
FailoverPartner = $"invalidhost",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
Encrypt = false,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
// Ensure pooling is enabled so that the failover partner information
// is persisted in the pool group. If pooling is disabled, the server
// provided failover partner will never be used.
Pooling = true
};
SqlConnection connection = new(builder.ConnectionString);
// Connect once to the primary to trigger it to send the failover partner
connection.Open();
Assert.Equal("invalidhost", (connection.InnerConnection as SqlConnectionInternal)!.ServerProvidedFailoverPartner);
// Close the connection to return it to the pool
connection.Close();
// Act
// Dispose of the server to trigger a failover
server.Dispose();
// Clear the pool to ensure the next connection attempt doesn't reuse
// the pooled connection to the now-disposed primary server.
SqlConnection.ClearAllPools();
// Opening a new connection will use the failover partner stored in the pool group.
// This will fail if the server provided failover partner was stored to the pool group.
using SqlConnection failoverConnection = new(builder.ConnectionString);
failoverConnection.Open();
// Assert
Assert.Equal(ConnectionState.Open, failoverConnection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", failoverConnection.DataSource);
// 1 for the initial connection
Assert.Equal(1, server.PreLoginCount - server.AbandonedPreLoginCount);
// 1 for the failover connection
Assert.Equal(1, failoverServer.PreLoginCount - failoverServer.AbandonedPreLoginCount);
}
/// <summary>
/// Async parity for primary-only retry behavior on login-phase transient SQL errors.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public async Task TransientFault_Async_ShouldConnectToPrimary_NotFailover(uint errorCode)
{
// Async parity for TransientFault_ShouldConnectToPrimary.
// A transient login-token error must be retried against the primary;
// the failover partner must never be contacted.
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
Pooling = false,
};
using SqlConnection connection = new(builder.ConnectionString);
// Asserts async open follows the same retry and failover-selection rules as sync.
await connection.OpenAsync();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
Assert.Equal(2, server.PreLoginCount - server.AbandonedPreLoginCount);
// Login-phase errors must NOT trigger failover alternation
Assert.Equal(0, failoverServer.PreLoginCount);
}
/// <summary>
/// Async parity with user-provided partner: login-phase transient SQL errors should
/// still retry on primary without failover alternation.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public async Task TransientFault_WithUserProvidedPartner_Async_ShouldConnectToPrimary_NotFailover(uint errorCode)
{
// Async parity for TransientFault_WithUserProvidedPartner_ShouldConnectToPrimary.
// Even with a user-provided failover partner, a login-token error must not
// cause alternation to the failover server.
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
};
using SqlConnection connection = new(builder.ConnectionString);
// Asserts async open with explicit partner still avoids failover alternation.
await connection.OpenAsync();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
Assert.Equal(2, server.PreLoginCount - server.AbandonedPreLoginCount);
// Login-phase errors must NOT trigger failover alternation
Assert.Equal(0, failoverServer.PreLoginCount);
}
/// <summary>
/// Verifies pooled connections are not cleared and failover is not attempted when a
/// login-phase transient SQL error occurs with a user-provided failover partner.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public void TransientFault_WithUserProvidedPartner_Pooling_ShouldNotClearPool_NotFailover(uint errorCode)
{
// With pooling enabled and a user-provided failover partner, a transient
// login-token error must not clear the pool and must not contact the failover server.
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
// Start with errors disabled so the pool warms up successfully.
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = SqlConnectionEncryptOption.Optional,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
Pooling = true,
};
// Keep one connection open so the next Open() cannot reuse it and must perform login.
using SqlConnection warmup = new(builder.ConnectionString);
warmup.Open();
// Enable the transient error for the next login attempt.
server.SetErrorBehavior(true, errorCode);
// ConnectRetryCount > 0 (default 1) so the client retries and succeeds.
using SqlConnection connection = new(builder.ConnectionString);
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
connection.Close();
warmup.Close();
// If the pool is not cleared, this open should reuse a pooled connection without a new login.
using SqlConnection pooledConnection = new(builder.ConnectionString);
pooledConnection.Open();
Assert.Equal(ConnectionState.Open, pooledConnection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", pooledConnection.DataSource);
// 1 warmup login + 1 failed login + 1 retry login.
Assert.Equal(3, server.PreLoginCount - server.AbandonedPreLoginCount);
Assert.Equal(3, server.Login7Count);
// Failover server must never have been contacted.
Assert.Equal(0, failoverServer.PreLoginCount - failoverServer.AbandonedPreLoginCount);
Assert.Equal(0, failoverServer.Login7Count);
}
/// <summary>
/// Verifies ConnectRetryCount=0 propagates login-phase transient SQL errors immediately
/// and never attempts failover alternation.
/// </summary>
[Theory]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
public void TransientFault_RetryDisabled_WithUserProvidedPartner_ShouldFail_NotFailover(uint errorCode)
{
// When ConnectRetryCount = 0 and the server returns a login-phase token error,
// the exception must propagate immediately and the failover partner must not be
// contacted (parser state is not Closed, so the new guard must kick in).
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = errorCode,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
ConnectRetryCount = 0,
Encrypt = false,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
};
using SqlConnection connection = new(builder.ConnectionString);
// No outer connect retry is allowed, so the first transient error should surface.
SqlException ex = Assert.Throws<SqlException>(() => connection.Open());
Assert.Equal((int)errorCode, ex.Number);
Assert.Equal(ConnectionState.Closed, connection.State);
// The parser was not closed (login-phase error), so the failover alternation branch
// must not have been entered.
Assert.Equal(0, failoverServer.PreLoginCount);
}
/// <summary>
/// Isolates the parser-state guard by using a non-fatal login error token: without the
/// guard, LoginWithFailover alternates to partner; with the guard, retry stays on primary.
/// </summary>
[Fact]
public void NonFatalTransientLoginError_WithUserProvidedPartner_ShouldRetryPrimary_NotFailover()
{
// This test isolates the parser-state guard added to LoginWithFailover.
// We emit a transient login error with non-fatal severity so the connection
// is not automatically doomed/broken by existing breakConnection logic.
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = 40613,
// Use non-fatal severity so break/doom logic does not short-circuit the path.
ErrorClass = 16,
RepeatCount = 1,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
Pooling = false,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
};
using SqlConnection connection = new(builder.ConnectionString);
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{server.EndPoint.Port}", connection.DataSource);
Assert.Equal(2, server.PreLoginCount - server.AbandonedPreLoginCount);
Assert.Equal(0, failoverServer.PreLoginCount - failoverServer.AbandonedPreLoginCount);
}
/// <summary>
/// Verifies opt-in legacy behavior: login-phase SQL errors can alternate to the
/// failover partner when UseLegacyFailoverAlternationOnLoginSqlErrors is enabled.
/// </summary>
[Fact]
public void NonFatalTransientLoginError_WithLegacySwitch_ShouldAlternateToFailoverPartner()
{
using LocalAppContextSwitchesHelper switchesHelper = new();
switchesHelper.UseLegacyFailoverAlternationOnLoginSqlErrors = true;
using TdsServer failoverServer = new(
new TdsServerArguments
{
FailoverPartner = "localhost,1234",
});
failoverServer.Start();
using TransientTdsErrorTdsServer server = new(
new TransientTdsErrorTdsServerArguments()
{
IsEnabledTransientError = true,
Number = 40613,
// Keep the login token non-fatal so parser state, not break/doom behavior,
// drives this branch decision.
ErrorClass = 16,
RepeatCount = 1,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
});
server.Start();
SqlConnectionStringBuilder builder = new()
{
DataSource = $"localhost,{server.EndPoint.Port}",
InitialCatalog = "master",
ConnectTimeout = 30,
ConnectRetryInterval = 1,
Encrypt = false,
Pooling = false,
FailoverPartner = $"localhost,{failoverServer.EndPoint.Port}",
};
using SqlConnection connection = new(builder.ConnectionString);
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
Assert.Equal($"localhost,{failoverServer.EndPoint.Port}", connection.DataSource);
Assert.Equal(1, server.PreLoginCount - server.AbandonedPreLoginCount);
Assert.Equal(1, failoverServer.PreLoginCount - failoverServer.AbandonedPreLoginCount);
}
}
}