Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1101,7 +1101,11 @@ public override uint CheckConnection()
// Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
// combination with _socket.Poll method and _socket.Available == 0 check. When both of them
// return true we can safely determine that the connection is no longer active.
if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
//
// The poll does not wait: a closed connection is already readable, so waiting adds nothing.
// Any positive timeout is rounded up to the system timer tick on Windows (15.6 ms by default),
// which this check would cost on every connection taken from the pool.
if (!_socket.Connected || (_socket.Poll(0, SelectMode.SelectRead) && _socket.Available == 0))
{
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Socket not usable.", args0: _connectionId);
return TdsEnums.SNI_ERROR;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// 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.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;

namespace Microsoft.Data.SqlClient.PerformanceTests
{
/// <summary>
/// Measures one checkout of a connection that has sat idle in the pool long enough to be
/// probed for liveness before it is handed out.
///
/// The pool skips the liveness probe for a connection that did I/O or passed a probe within
/// the last 5 ms (<c>TdsParserStateObject.CheckConnectionWindow</c>). In the rapid open/close
/// loop of <see cref="ConnectionPoolChurnRunner"/> at most one checkout in every 5 ms is
/// probed, and its cost is averaged over the rest. Here every iteration waits past that window
/// outside the measurement, then times a single open, so every measured checkout pays for the
/// probe. Under managed SNI the probe is
/// <c>SniTcpHandle.CheckConnection</c>, whose socket poll must not wait: Windows rounds any
/// positive poll timeout up to the timer tick, about 15 ms by default.
///
/// The pool holds a single connection, so every iteration probes the same idle socket. Set
/// <c>UseManagedSniOnWindows</c> to measure the managed probe on Windows; on other operating
/// systems the managed implementation is the only one.
///
/// Related issue: #5070
/// </summary>
public class ConnectionPoolIdleCheckoutRunner : BaseRunner
{
/// <summary>
/// How long the connection sits idle before each measured checkout: twice the 5 ms window,
/// so clock granularity cannot leave it inside the window.
/// </summary>
private static readonly TimeSpan s_idleTime = TimeSpan.FromMilliseconds(10);

private string _connectionString;

[GlobalSetup]
public void Setup()
{
var builder = new SqlConnectionStringBuilder(s_config.ConnectionString)
{
Pooling = true,
// One connection, kept open, so each checkout probes the same idle socket rather
// than opening a new physical connection.
MinPoolSize = 1,
MaxPoolSize = 1
};
_connectionString = builder.ConnectionString;

// Opened and released before measurement, so no measured open is a physical connect.
using var conn = new SqlConnection(_connectionString);
conn.Open();
}

/// <summary>
/// Leaves the pooled connection idle past the liveness window, outside the measurement.
/// </summary>
[IterationSetup]
public void IterationSetup()
{
Thread.Sleep(s_idleTime);
}

[GlobalCleanup]
public void Cleanup()
{
using var conn = new SqlConnection(_connectionString);
SqlConnection.ClearPool(conn);
}

[Benchmark]
public void OpenIdlePooledConnection()
{
using var conn = new SqlConnection(_connectionString);
conn.Open();
// Dispose returns the connection to the pool.
}

[Benchmark]
public async Task OpenIdlePooledConnectionAsync()
{
await using var conn = new SqlConnection(_connectionString);
await conn.OpenAsync();
// Dispose returns the connection to the pool.
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public class Benchmarks
public RunnerJob ConnectionPoolStressRunnerConfig;
public RunnerJob ConnectionPoolContentionRunnerConfig;
public RunnerJob ConnectionPoolChurnRunnerConfig;
public RunnerJob ConnectionPoolIdleCheckoutRunnerConfig;
public RunnerJob ConnectionPoolRampRunnerConfig;
public RunnerJob ConnectionPoolThreadPoolPressureRunnerConfig;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public BenchmarkUnit(string name, Func<Benchmarks, RunnerJob> selector, Type run
new BenchmarkUnit("ConnectionPoolStress", b => b.ConnectionPoolStressRunnerConfig, typeof(ConnectionPoolStressRunner)),
new BenchmarkUnit("ConnectionPoolContention", b => b.ConnectionPoolContentionRunnerConfig, typeof(ConnectionPoolContentionRunner)),
new BenchmarkUnit("ConnectionPoolChurn", b => b.ConnectionPoolChurnRunnerConfig, typeof(ConnectionPoolChurnRunner)),
new BenchmarkUnit("ConnectionPoolIdleCheckout", b => b.ConnectionPoolIdleCheckoutRunnerConfig, typeof(ConnectionPoolIdleCheckoutRunner)),
new BenchmarkUnit("ConnectionPoolRamp", b => b.ConnectionPoolRampRunnerConfig, typeof(ConnectionPoolRampRunner)),
new BenchmarkUnit("ConnectionPoolThreadPoolPressure", b => b.ConnectionPoolThreadPoolPressureRunnerConfig, typeof(ConnectionPoolThreadPoolPressureRunner)),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,16 @@
"WarmupCount": 1,
"RowCount": 0
},
// Each iteration times a single checkout, so it needs more iterations than the others
// for a stable median.
"ConnectionPoolIdleCheckoutRunnerConfig": {
"Enabled": true,
"LaunchCount": 1,
"IterationCount": 50,
"InvocationCount": 1,
"WarmupCount": 1,
"RowCount": 0
},
"ConnectionPoolRampRunnerConfig": {
"Enabled": true,
"LaunchCount": 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#if NET

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
Expand Down Expand Up @@ -85,6 +86,74 @@ public async Task EnableSsl_PeerNeverAnswersHandshake_ReturnsTimeoutErrorWhenTok
handle.Dispose();
}
}

/// <summary>
/// The liveness check reports a connection the peer has closed, so the pool discards it
/// instead of handing it out. The peer's close reaches the client asynchronously, so the
/// check is repeated until it fails or a deadline passes.
/// </summary>
[Fact]
public void CheckConnection_PeerClosed_ReturnsError()
{
// Arrange
using LocalConnection connection = new();
connection.Peer.Close();

// Act
uint result = TdsEnums.SNI_SUCCESS;
Stopwatch deadline = Stopwatch.StartNew();
while (result == TdsEnums.SNI_SUCCESS && deadline.Elapsed < TimeSpan.FromSeconds(5))
{
result = connection.Handle.CheckConnection();
if (result == TdsEnums.SNI_SUCCESS)
{
Thread.Sleep(10);
}
}

// Assert
Assert.Equal(TdsEnums.SNI_ERROR, result);
}

/// <summary>
/// Opens a managed TCP handle to a local listener and owns both ends.
/// </summary>
private sealed class LocalConnection : IDisposable
{
public SniTcpHandle Handle { get; }

public Socket Peer { get; }

public LocalConnection()
{
using TcpListener listener = new(IPAddress.Loopback, 0);
listener.Start();
SQLDNSInfo? pendingDnsInfo = null;
Handle = new SniTcpHandle(
IPAddress.Loopback.ToString(),
((IPEndPoint)listener.LocalEndpoint).Port,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(5)),
parallel: false,
SqlConnectionIPAddressPreference.IPv4First,
cachedFQDN: nameof(SniTcpHandleTests),
ref pendingDnsInfo,
tlsFirst: false,
hostNameInCertificate: null,
serverCertificateFilename: null);
using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(5));
Peer = listener.AcceptSocketAsync(timeout.Token).AsTask().GetAwaiter().GetResult();
Assert.Equal(TdsEnums.SNI_SUCCESS, Handle.Status);
}

/// <summary>
/// Closes the client handle and the accepted socket.
/// </summary>
public void Dispose()
{
Handle.Dispose();
Peer.Dispose();
}
}
}
}

Expand Down
Loading