Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizing Eventsource memory allocations and removing an extra comment. #684

Merged
merged 14 commits into from
Aug 21, 2020
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
}
}
}
SqlClientEventSource.Log.PoolerTraceEvent("<prov.DbConnectionPool.CreateObject|RES|CPOOL> {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null");
SqlClientEventSource.Log.PoolerTraceEvent("<prov.DbConnectionPool.CreateObject|RES|CPOOL> {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID ?? 0 : -1);

// Reset the error wait:
_errorWait = ERROR_WAIT_DEFAULT;
Expand Down Expand Up @@ -1287,7 +1287,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj
}

// Do not use this pooled connection if access token is about to expire soon before we can connect.
if(null != obj && obj.IsAccessTokenExpired)
if (null != obj && obj.IsAccessTokenExpired)
{
DestroyObject(obj);
obj = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2202,16 +2202,16 @@ string endMethod
}

private void CreateLocalCompletionTask(
CommandBehavior behavior,
object stateObject,
int timeout,
CommandBehavior behavior,
object stateObject,
int timeout,
bool usedCache,
bool asyncWrite,
TaskCompletionSource<object> globalCompletion,
TaskCompletionSource<object> localCompletion,
bool asyncWrite,
TaskCompletionSource<object> globalCompletion,
TaskCompletionSource<object> localCompletion,
Func<SqlCommand, IAsyncResult, bool, string, object> endFunc,
Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> retryFunc,
string endMethod,
Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> retryFunc,
string endMethod,
long firstAttemptStart
)
{
Expand Down Expand Up @@ -2493,14 +2493,14 @@ protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior b
{
context = new ExecuteReaderAsyncCallContext();
}
context.Set(this, source, registration,behavior, operationId);
context.Set(this, source, registration, behavior, operationId);

Task<SqlDataReader>.Factory.FromAsync(
beginMethod: s_beginExecuteReaderAsync,
beginMethod: s_beginExecuteReaderAsync,
endMethod: s_endExecuteReaderAsync,
state: context
).ContinueWith(
continuationAction: s_cleanupExecuteReaderAsync,
continuationAction: s_cleanupExecuteReaderAsync,
TaskScheduler.Default
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1198,7 +1198,7 @@ private async Task ReconnectAsync(int timeout)
{
if (ctoken.IsCancellationRequested)
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString());
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId);
return;
}
try
Expand All @@ -1217,15 +1217,15 @@ private async Task ReconnectAsync(int timeout)
{
ForceNewConnection = false;
}
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString());
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId);
return;
}
catch (SqlException e)
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectAsyncINFO> Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message);
if (attempt == retryCount - 1)
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString());
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID {0} - give up reconnection", _originalConnectionId);
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
Expand Down Expand Up @@ -1298,7 +1298,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
// could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString());
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId);
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
Expand Down Expand Up @@ -1412,7 +1412,7 @@ public override Task OpenAsync(CancellationToken cancellationToken)
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection))
{
result.Task.ContinueWith(
continuationAction: s_openAsyncComplete,
continuationAction: s_openAsyncComplete,
state: operationId, // connection is passed in TaskCompletionSource async state
scheduler: TaskScheduler.Default
);
Expand Down Expand Up @@ -2013,7 +2013,7 @@ internal Task<T> RegisterForConnectionCloseNotification<T>(Task<T> outerTask, ob

connection.RemoveWeakReference(obj);
return task;
},
},
state: Tuple.Create(this, value),
scheduler: TaskScheduler.Default
).Unwrap();
Expand Down Expand Up @@ -2096,7 +2096,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError)
{
if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled())
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ResolveTypeAssembly> SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString());
SqlClientEventSource.Log.TraceEvent("<sc.SqlConnection.ResolveTypeAssembly> SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion);
}
asmRef.Version = TypeSystemAssemblyVersion;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@ private void ConnectionString_Set(DbConnectionPoolKey key)
{
throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State);
}
string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : "");
SqlClientEventSource.Log.TraceEvent("<prov.DbConnectionHelper.ConnectionString_Set|API> {0}, '{1}'", ObjectID, cstr);
if (SqlClientEventSource.Log.IsTraceEnabled())
{
SqlClientEventSource.Log.TraceEvent("<prov.DbConnectionHelper.ConnectionString_Set|API> {0}, '{1}'", ObjectID, (null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : "");
}
}

internal DbConnectionInternal InnerConnection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ private void ProcessNotificationResults(SqlDataReader reader)
{
for (int i = 0; i < reader.FieldCount; i++)
{
SqlClientEventSource.Log.NotificationTraceEvent("<sc.SqlConnectionContainer.ProcessNotificationResults|DEP> column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString());
SqlClientEventSource.Log.NotificationTraceEvent("<sc.SqlConnectionContainer.ProcessNotificationResults|DEP> column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i));
}
}
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2141,9 +2141,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
// And on successful login, try to update the cache with the new token.
if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan)
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, " +
"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." +
"The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
if (SqlClientEventSource.Log.IsTraceEnabled())
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, " +
"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." +
"The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
}
attemptRefreshTokenUnLocked = true;
}

Expand All @@ -2163,9 +2166,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
// If a thread is already doing the refresh, just use the existing token in the cache and proceed.
else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan)
{
SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo|ADV> {0}, " +
"The authentication context needs a refresh.The expiration time is {1}. " +
"Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
if (SqlClientEventSource.Log.IsAdvancedTraceOn())
{
SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo|ADV> {0}, " +
"The authentication context needs a refresh.The expiration time is {1}. " +
"Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
}

// Call the function which tries to acquire a lock over the authentication context before trying to update.
// If the lock could not be obtained, it will return false, without attempting to fetch a new token.
Expand Down Expand Up @@ -2243,9 +2249,12 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP
// Else some other thread is already updating it, so just proceed forward with the existing token in the cache.
if (dbConnectionPoolAuthenticationContext.LockToUpdate())
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.TryGetFedAuthTokenLocked> {0}, " +
"Acquired the lock to update the authentication context.The expiration time is {1}. " +
"Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
if (SqlClientEventSource.Log.IsTraceEnabled())
{
SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.TryGetFedAuthTokenLocked> {0}, " +
"Acquired the lock to update the authentication context.The expiration time is {1}. " +
"Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString());
}
authenticationContextLocked = true;
}
else
Expand Down
Loading