Skip to content
Merged
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 @@ -320,19 +320,19 @@ private IAsyncResult BeginExecuteXmlReaderInternal(
endMethod: nameof(EndExecuteXmlReader),
cancellationToken))
{
// @TODO: globalCompletion isn't being used past here! Why are we doing this??
globalCompletion = localCompletion;
}

// Add callback after work is done to avoid overlapping Begin/End methods
// Add callback after work is done to avoid overlapping Begin/End methods.
// Callers must observe the retry's outcome, not a retried first attempt.
if (callback is not null)
{
localCompletion.Task.ContinueWith(
globalCompletion.Task.ContinueWith(
static (task, state) => ((AsyncCallback)state)(task),
state: callback);
}

return localCompletion.Task;
return globalCompletion.Task;
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2498,6 +2498,8 @@ private void CreateLocalCompletionTask(
}

object result = await retryTask.ConfigureAwait(false);
// The retry holds its own reservation for End, so release the original one.
retryConnection?.DecrementAsyncCount();
globalCompletion.TrySetResult(result);
}
catch (Exception e2)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using Microsoft.SqlServer.TDS;
using Microsoft.SqlServer.TDS.Done;
using Microsoft.SqlServer.TDS.EndPoint;
using Microsoft.SqlServer.TDS.Error;
using Microsoft.SqlServer.TDS.Servers;
using Microsoft.SqlServer.TDS.SQLBatch;
using Xunit;
Expand Down Expand Up @@ -640,6 +641,60 @@ public async Task ExecuteReaderAsync_InlineEnclaveRetry_AbortsCleanly(bool retry
Assert.Equal(0, GetAsyncCount(inner));
}

/// <summary>
/// An XML execution whose first response reports an invalid enclave session stays
/// pending until the internal retry finishes, and then reports the retry's outcome.
/// </summary>
[Fact]
public async Task BeginExecuteXmlReader_InvalidEnclaveSession_CompletesWithRetry()
{
// Arrange
// The first query reports an invalid enclave session, which the internal End retries.
// The retried query waits on a gate, then fails with a distinct error.
using ManualResetEventSlim retryGate = new ManualResetEventSlim(false);
TdsServerArguments arguments = new TdsServerArguments();
RetryQueryEngine engine = new RetryQueryEngine(arguments, retryGate);
using TdsServer server = new TdsServer(engine, arguments);
server.Start();
using Fixture fixture = new Fixture(server);
using SqlCommand command = fixture.CreateCommand();
fixture.Provider.CacheHit = true;
SqlConnectionInternal inner = (SqlConnectionInternal)fixture.Connection.InnerConnection;

// Act
IAsyncResult result;
bool completedDuringRetry;
try
{
result = command.BeginExecuteXmlReader();
Assert.True(engine.RetryEntered.Wait(TimeSpan.FromSeconds(30)));
completedDuringRetry = result.IsCompleted;
}
finally
{
retryGate.Set();
}

// Assert
// The caller observes only the retry's outcome. The retry skips the internal End,
// so its task completes when the response arrives and End reports the error.
Assert.False(completedDuringRetry);
await (Task)result;
Assert.Equal(
RetryQueryEngine.RetryErrorNumber,
Assert.Throws<SqlException>(() => command.EndExecuteXmlReader(result)).Number);

// Command and connection state are released, so both remain usable.
Assert.Null(GetField(command, "_stateObj"));
Assert.Null(GetField(command, "_enclaveRetryConnection"));
Assert.False((bool)GetField(command, "_internalEndExecuteInitiated"));
Assert.Equal(0, GetAsyncCount(inner));
using SqlCommand reusable =
new SqlCommand("/* reuse after XML enclave retry */", fixture.Connection);
Assert.Equal(-1, await reusable.ExecuteNonQueryAsync());
Assert.Equal(0, GetAsyncCount(inner));
}

/// <summary>
/// The command retry cannot start before invalidation completes, and must not start after failure or cancellation.
/// </summary>
Expand All @@ -666,7 +721,9 @@ public async Task Retry_AwaitsInvalidationBeforeRestarting(int outcome)
Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> retry =
(cmd, behavior, callback, state, timeout, isRetry, asyncWrite) =>
{
// Like a real retry, take a reservation for End.
retries++;
inner.IncrementAsyncCount();
return Task.FromResult<object>(null);
};
typeof(SqlCommand).GetMethod("CreateLocalCompletionTask", BindingFlags.NonPublic | BindingFlags.Instance)
Expand All @@ -685,6 +742,8 @@ public async Task Retry_AwaitsInvalidationBeforeRestarting(int outcome)
fixture.Provider.CompleteSessionOperation();
await global.Task;
Assert.Equal(1, retries);
// Only the retry's reservation remains for End.
Assert.Equal(1, GetAsyncCount(inner));
inner.DecrementAsyncCount();
}
else if (outcome == 1)
Expand Down Expand Up @@ -863,6 +922,62 @@ protected override TDSMessageCollection CreateQueryResponse(
}
}

/// <summary>Fails the first query with a retryable enclave error and gates the retry.</summary>
private sealed class RetryQueryEngine : QueryEngine
{
internal const int RetryErrorNumber = 50000;
private readonly ManualResetEventSlim _retryGate;
private int _queries;

internal RetryQueryEngine(TdsServerArguments arguments, ManualResetEventSlim retryGate)
: base(arguments)
{
_retryGate = retryGate;
}

/// <summary>Signaled when the retried query reaches the server.</summary>
internal ManualResetEventSlim RetryEntered { get; } = new ManualResetEventSlim(false);

/// <summary>
/// Answers sp_describe_parameter_encryption with no result sets, so the command needs no enclave computations.
/// </summary>
/// <param name="session">The connected test session.</param>
/// <param name="request">The RPC request.</param>
/// <returns>An empty response.</returns>
public override TDSMessageCollection ExecuteRPC(ITDSServerSession session, TDSMessage request)
{
TDSMessage response = new TDSMessage(TDSMessageType.Response);
response.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final));
return new TDSMessageCollection { response };
}

/// <summary>Returns an invalid enclave session error, then a gated distinct error.</summary>
/// <param name="session">The connected test session.</param>
/// <param name="batchRequest">The batch to execute.</param>
/// <returns>An error response.</returns>
protected override TDSMessageCollection CreateQueryResponse(
ITDSServerSession session, TDSSQLBatchToken batchRequest)
{
uint number = (uint)TdsEnums.TCE_ENCLAVE_INVALID_SESSION_HANDLE;
int query = Interlocked.Increment(ref _queries);
if (query == 2)
{
RetryEntered.Set();
_retryGate.Wait();
number = RetryErrorNumber;
}
else if (query > 2)
{
return base.CreateQueryResponse(session, batchRequest);
}

TDSMessage response = new TDSMessage(TDSMessageType.Response);
response.Add(new TDSErrorToken(number, 1, 16, "Query failure", ServerArguments.ServerName));
response.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error));
return new TDSMessageCollection { response };
}
}

/// <summary>
/// Uses an in-process SQL connection with isolated provider registration and negotiated capabilities.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ public interface ITDSServer
/// <returns>TDS message to respond with</returns>
TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage message);

/// <summary>
/// It is called when RPC request arrives
/// </summary>
/// <param name="message">TDS message received</param>
/// <returns>TDS message to respond with</returns>
TDSMessageCollection OnRPCRequest(ITDSServerSession session, TDSMessage message);

/// <summary>
/// It is called when attention arrives
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ public void Run()
responseMessages = Server.OnSQLBatchRequest(Session, MessageBeingReceived);
break;
}
case TDSMessageType.RPC:
{
// Call into the subscriber to process the packet
responseMessages = Server.OnRPCRequest(Session, MessageBeingReceived);
break;
}
case TDSMessageType.Attention:
{
// Call into the subscriber to process the packet
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,15 @@ public virtual TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session,
return responseMessage;
}

/// <summary>
/// It is called when RPC request arrives
/// </summary>
public virtual TDSMessageCollection OnRPCRequest(ITDSServerSession session, TDSMessage message)
{
// Delegate to the query engine
return Engine.ExecuteRPC(session, message);
}

/// <summary>
/// It is called when attention arrives
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ public TDSMessageCollection ExecuteBatch(ITDSServerSession session, TDSMessage r
return CreateQueryResponse(session, batchRequest);
}

/// <summary>
/// Handle an RPC request. RPC payloads are not parsed, so engines that expect RPCs must override this.
/// </summary>
public virtual TDSMessageCollection ExecuteRPC(ITDSServerSession session, TDSMessage request)
{
throw new NotImplementedException("RPC requests are not implemented by this query engine");
}

/// <summary>
/// Create a response for the query
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,9 @@ private void _InflateClientTokens()
break;
}
case TDSMessageType.Attention:
case TDSMessageType.RPC:
{
// Do nothing
// Do nothing; RPC payloads are not parsed
break;
}
case TDSMessageType.FederatedAuthenticationToken:
Expand Down
Loading