|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +#if NET |
| 6 | + |
| 7 | +#nullable enable |
| 8 | + |
| 9 | +using System; |
| 10 | +using System.Collections.Concurrent; |
| 11 | +using System.IO; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using Xunit; |
| 14 | + |
| 15 | +namespace Microsoft.Data.SqlClient.ManualTesting.Tests |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// Exercises GH#4679 with a streaming MARS session and a connection-terminating error |
| 19 | + /// on a second session. Requires a test SQL Server and a sysadmin login; each case |
| 20 | + /// writes a severity-20 error to the server log. |
| 21 | + /// </summary> |
| 22 | + [Trait("Set", "1")] |
| 23 | + public sealed class MarsReceiveTeardownTest |
| 24 | + { |
| 25 | + /// <summary> |
| 26 | + /// Physical teardown must report normal command errors rather than faulting an |
| 27 | + /// unobserved MARS receive continuation, with or without connection pooling. |
| 28 | + /// Each delay is a separate case rather than a long-running stress loop. |
| 29 | + /// </summary> |
| 30 | + [ConditionalTheory(typeof(MarsReceiveTeardownTest), nameof(CanRun))] |
| 31 | + [InlineData(false, false, 1)] |
| 32 | + [InlineData(false, true, 1)] |
| 33 | + [InlineData(true, false, 1)] |
| 34 | + [InlineData(true, true, 1)] |
| 35 | + [InlineData(false, false, 29)] |
| 36 | + [InlineData(false, true, 29)] |
| 37 | + [InlineData(true, false, 29)] |
| 38 | + [InlineData(true, true, 29)] |
| 39 | + public async Task FatalError_WhileMarsReaderStreams_DoesNotFaultReceivePump(bool async, bool pooling, int delay) |
| 40 | + { |
| 41 | + string connectionString = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) |
| 42 | + { |
| 43 | + MultipleActiveResultSets = true, |
| 44 | + Pooling = pooling, |
| 45 | + ConnectRetryCount = 0, |
| 46 | + ApplicationName = nameof(MarsReceiveTeardownTest), |
| 47 | + }.ConnectionString; |
| 48 | + ConcurrentQueue<Exception> unobserved = new(); |
| 49 | + EventHandler<UnobservedTaskExceptionEventArgs> handler = (_, args) => |
| 50 | + { |
| 51 | + foreach (Exception exception in args.Exception.Flatten().InnerExceptions) |
| 52 | + { |
| 53 | + if (exception.StackTrace?.Contains("ManagedSni.SniMarsConnection") == true) |
| 54 | + { |
| 55 | + unobserved.Enqueue(exception); |
| 56 | + args.SetObserved(); |
| 57 | + } |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + TaskScheduler.UnobservedTaskException += handler; |
| 62 | + try |
| 63 | + { |
| 64 | + await TerminateStreamingConnection(connectionString, async, delay); |
| 65 | + |
| 66 | + for (int attempt = 0; attempt < 10; attempt++) |
| 67 | + { |
| 68 | + CollectReceiveContinuations(); |
| 69 | + await Task.Delay(50); |
| 70 | + } |
| 71 | + |
| 72 | + Assert.Empty(unobserved); |
| 73 | + } |
| 74 | + finally |
| 75 | + { |
| 76 | + TaskScheduler.UnobservedTaskException -= handler; |
| 77 | + using SqlConnection poolKey = new(connectionString); |
| 78 | + SqlConnection.ClearPool(poolKey); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /// <summary> |
| 83 | + /// Requires managed SNI and a non-Azure SQL Server login allowed to raise fatal errors. |
| 84 | + /// </summary> |
| 85 | + /// <returns>Whether the configured login is a sysadmin on a supported test server.</returns> |
| 86 | + public static bool CanRun() |
| 87 | + { |
| 88 | + if (!DataTestUtility.AreConnStringsSetup() || |
| 89 | + !DataTestUtility.IsNotAzureServer() || !DataTestUtility.IsUsingManagedSNI()) |
| 90 | + { |
| 91 | + return false; |
| 92 | + } |
| 93 | + |
| 94 | + using SqlConnection connection = new(DataTestUtility.TCPConnectionString); |
| 95 | + using SqlCommand command = new("SELECT IS_SRVROLEMEMBER('sysadmin')", connection); |
| 96 | + connection.Open(); |
| 97 | + return command.ExecuteScalar() is int member && member == 1; |
| 98 | + } |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// Starts two MARS sessions, terminates only their connection, and observes all |
| 102 | + /// application tasks so any unobserved exception belongs to the driver's receive pump. |
| 103 | + /// </summary> |
| 104 | + /// <param name="connectionString">Connection string for the test server.</param> |
| 105 | + /// <param name="async">Whether to use asynchronous command and reader APIs.</param> |
| 106 | + /// <param name="delay">Delay before terminating the streaming connection, in milliseconds.</param> |
| 107 | + /// <returns>A task that completes after both sessions and the connection are cleaned up.</returns> |
| 108 | + private static async Task TerminateStreamingConnection(string connectionString, bool async, int delay) |
| 109 | + { |
| 110 | + SqlConnection connection = new(connectionString); |
| 111 | + SqlDataReader? reader = null; |
| 112 | + Task<Exception?>? consumer = null; |
| 113 | + using SqlCommand stream = new( |
| 114 | + "SELECT TOP (200000) a.object_id, b.name, REPLICATE('x', 200) AS pad " + |
| 115 | + "FROM sys.all_objects a CROSS JOIN sys.all_columns b", connection); |
| 116 | + stream.CommandTimeout = 60; |
| 117 | + try |
| 118 | + { |
| 119 | + if (async) |
| 120 | + { |
| 121 | + await connection.OpenAsync(); |
| 122 | + } |
| 123 | + else |
| 124 | + { |
| 125 | + connection.Open(); |
| 126 | + } |
| 127 | + |
| 128 | + reader = async ? await stream.ExecuteReaderAsync() : stream.ExecuteReader(); |
| 129 | + Assert.True(async ? await reader.ReadAsync() : reader.Read()); |
| 130 | + consumer = Task.Run(() => Record.ExceptionAsync(async () => |
| 131 | + { |
| 132 | + while (async ? await reader.ReadAsync() : reader.Read()) |
| 133 | + { |
| 134 | + } |
| 135 | + })); |
| 136 | + await Task.Delay(delay); |
| 137 | + |
| 138 | + using SqlCommand terminate = new( |
| 139 | + "RAISERROR('SqlClient MARS receive teardown regression', 20, 1) WITH LOG", connection); |
| 140 | + SqlException error; |
| 141 | + if (async) |
| 142 | + { |
| 143 | + error = await Assert.ThrowsAsync<SqlException>(() => terminate.ExecuteNonQueryAsync()); |
| 144 | + } |
| 145 | + else |
| 146 | + { |
| 147 | + error = Assert.Throws<SqlException>(() => terminate.ExecuteNonQuery()); |
| 148 | + } |
| 149 | + Assert.True(error.Class >= 20, "The second session must terminate the physical connection."); |
| 150 | + } |
| 151 | + finally |
| 152 | + { |
| 153 | + Exception? closeError; |
| 154 | + Exception? readerError; |
| 155 | + try |
| 156 | + { |
| 157 | + Exception? consumeError = consumer is null |
| 158 | + ? null |
| 159 | + : await consumer.WaitAsync(TimeSpan.FromSeconds(65)); |
| 160 | + AssertExpectedTeardownError(consumeError); |
| 161 | + } |
| 162 | + finally |
| 163 | + { |
| 164 | + closeError = Record.Exception(connection.Dispose); |
| 165 | + readerError = reader is null ? null : Record.Exception(reader.Dispose); |
| 166 | + } |
| 167 | + AssertExpectedTeardownError(closeError); |
| 168 | + AssertExpectedTeardownError(readerError); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + /// <summary> |
| 173 | + /// Allows expected failures of commands on a broken connection, but rejects programming errors. |
| 174 | + /// </summary> |
| 175 | + /// <param name="exception">The observed application-side teardown exception, if any.</param> |
| 176 | + private static void AssertExpectedTeardownError(Exception? exception) |
| 177 | + { |
| 178 | + Assert.True(exception is null or SqlException or InvalidOperationException or IOException, |
| 179 | + $"Unexpected application-side teardown error: {exception}"); |
| 180 | + } |
| 181 | + |
| 182 | + /// <summary> |
| 183 | + /// Finalizes abandoned continuation tasks so their failures reach the event handler. |
| 184 | + /// </summary> |
| 185 | + private static void CollectReceiveContinuations() |
| 186 | + { |
| 187 | + GC.Collect(); |
| 188 | + GC.WaitForPendingFinalizers(); |
| 189 | + GC.Collect(); |
| 190 | + } |
| 191 | + } |
| 192 | +} |
| 193 | + |
| 194 | +#endif |
0 commit comments