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

Fix activity tracing to track entire execution time of inbound calls #763

Merged
merged 1 commit into from
Jan 29, 2022
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
25 changes: 12 additions & 13 deletions src/StreamJsonRpc/JsonRpc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1555,20 +1555,19 @@ protected virtual void OnRequestTransmissionAborted(JsonRpcRequest request)
protected virtual async ValueTask<JsonRpcMessage> DispatchRequestAsync(JsonRpcRequest request, TargetMethod targetMethod, CancellationToken cancellationToken)
{
object? result;
using (IDisposable? activityTracingState = this.ActivityTracingStrategy?.ApplyInboundActivity(request))
using IDisposable? activityTracingState = this.ActivityTracingStrategy?.ApplyInboundActivity(request);

try
{
try
{
// IMPORTANT: This should be the first await in this async method,
// and no other await should be between this one and actually invoking the target method.
// This is crucial to the guarantee that method invocation order is preserved from client to server
// when a single-threaded SynchronizationContext is applied.
result = await targetMethod.InvokeAsync(cancellationToken).ConfigureAwait(false);
}
catch (TargetInvocationException ex) when (ex.InnerException is OperationCanceledException)
{
return this.CreateCancellationResponse(request);
}
// IMPORTANT: This should be the first await in this async method,
// and no other await should be between this one and actually invoking the target method.
// This is crucial to the guarantee that method invocation order is preserved from client to server
// when a single-threaded SynchronizationContext is applied.
result = await targetMethod.InvokeAsync(cancellationToken).ConfigureAwait(false);
}
catch (TargetInvocationException ex) when (ex.InnerException is OperationCanceledException)
{
return this.CreateCancellationResponse(request);
}

// Convert ValueTask to Task or ValueTask<T> to Task<T>
Expand Down
36 changes: 36 additions & 0 deletions test/StreamJsonRpc.Tests/JsonRpcTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2664,6 +2664,31 @@ static void ConfigureTracing(JsonRpc jsonRpc, string name, XmlWriterTraceListene
}
#endif

/// <summary>
/// Verifies that an activity representing an incoming RPC request lasts the full duration of the async server method
/// rather than just till its first yield.
/// </summary>
[Fact]
public async Task IncomingActivityStopsAfterAsyncTargetMethodCompletes()
{
this.serverRpc.AllowModificationWhileListening = true;
TaskCompletionSource<object?> started = new();
TaskCompletionSource<object?> stopped = new();
this.serverRpc.ActivityTracingStrategy = new MockActivityTracingStrategy
{
Inbound = req =>
{
started.SetResult(null);
return new DisposableAction(() => stopped.SetResult(null));
},
};
Task task = this.clientRpc.InvokeWithCancellationAsync<string>(nameof(Server.AsyncMethodWithCancellation), new object?[] { "arg" }, this.TimeoutToken);
await started.Task.WithCancellation(this.TimeoutToken);
await Assert.ThrowsAsync<TimeoutException>(() => stopped.Task.WithTimeout(ExpectedTimeout));
this.server.AllowServerMethodToReturn.Set();
await stopped.Task.WithCancellation(this.TimeoutToken);
}

protected static Exception CreateExceptionToBeThrownByDeserializer() => new Exception("This exception is meant to be thrown.");

protected override void Dispose(bool disposing)
Expand Down Expand Up @@ -3483,6 +3508,17 @@ internal class InternalClass
{
}

protected class MockActivityTracingStrategy : IActivityTracingStrategy
{
internal Func<JsonRpcRequest, IDisposable>? Inbound { get; set; }

internal Action<JsonRpcRequest>? Outbound { get; set; }

public IDisposable? ApplyInboundActivity(JsonRpcRequest request) => this.Inbound?.Invoke(request);

public void ApplyOutboundActivity(JsonRpcRequest request) => this.Outbound?.Invoke(request);
}

/// <summary>
/// This emulates what .NET Core 2.1 does where async <see cref="Task{T}"/> methods actually return an instance of a private derived type.
/// </summary>
Expand Down