Skip to content

Require CancellationToken for client results (and fix cancel closing connection) #43249

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

Merged
merged 5 commits into from
Aug 20, 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
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
<Compile Include="$(RepoRoot)src\SignalR\common\Shared\BinaryMessageParser.cs" LinkBase="BlazorPack" />
<Compile Include="$(RepoRoot)src\SignalR\common\Shared\MemoryBufferWriter.cs" LinkBase="BlazorPack" />
<Compile Include="$(RepoRoot)src\SignalR\common\Protocols.MessagePack\src\Protocol\MessagePackHubProtocolWorker.cs" LinkBase="BlazorPack" />
<Compile Include="$(RepoRoot)src\SignalR\common\Shared\TryGetReturnType.cs" LinkBase="BlazorPack" />

<!-- MessagePack -->
<Compile Include="$(MessagePackRoot)BufferWriter.cs" LinkBase="BlazorPack\MessagePack" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Core components of ASP.NET Core Kestrel cross-platform web server.</Description>
Expand Down Expand Up @@ -29,6 +29,7 @@
<Compile Include="$(SharedSourceRoot)runtime\Http3\**\*.cs" Link="Shared\runtime\Http3\%(Filename)%(Extension)" />
<Compile Include="$(SharedSourceRoot)Hpack\**\*.cs" Link="Shared\Hpack\%(Filename)%(Extension)" />
<Compile Include="$(SharedSourceRoot)ServerInfrastructure\**\*.cs" />
<Compile Include="$(SharedSourceRoot)CancellationTokenSourcePool.cs" />
<Compile Include="$(RepoRoot)src\Shared\TaskToApm.cs" Link="Internal\TaskToApm.cs" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

using System.Collections.Concurrent;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
namespace Microsoft.AspNetCore.Internal;

internal sealed class CancellationTokenSourcePool
{
Expand Down
2 changes: 1 addition & 1 deletion src/SignalR/clients/ts/FunctionalTests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<
{
try
{
var result = await hubContext.Clients.Client(id).InvokeAsync<int>("Result");
var result = await hubContext.Clients.Client(id).InvokeAsync<int>("Result", cancellationToken: default);
return result.ToString(CultureInfo.InvariantCulture);
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<Compile Include="$(SignalRSharedSourceRoot)Utf8BufferTextReader.cs" Link="Utf8BufferTextReader.cs" />
<Compile Include="$(SignalRSharedSourceRoot)Utf8BufferTextWriter.cs" Link="Utf8BufferTextWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)ReusableUtf8JsonWriter.cs" Link="ReusableUtf8JsonWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)TryGetReturnType.cs" Link="TryGetReturnType.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
23 changes: 19 additions & 4 deletions src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,16 @@ public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)
else
{
// If we have an invocation id already we can parse the end result
var returnType = binder.GetReturnType(invocationId);
result = BindType(ref reader, input, returnType);
var returnType = ProtocolHelper.TryGetReturnType(binder, invocationId);
if (returnType is null)
{
reader.Skip();
result = null;
}
else
{
result = BindType(ref reader, input, returnType);
}
}
}
else if (reader.ValueTextEquals(ItemPropertyNameBytes.EncodedUtf8Bytes))
Expand Down Expand Up @@ -408,8 +416,15 @@ public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)

if (hasResultToken)
{
var returnType = binder.GetReturnType(invocationId);
result = BindType(ref resultToken, input, returnType);
var returnType = ProtocolHelper.TryGetReturnType(binder, invocationId);
if (returnType is null)
{
result = null;
}
else
{
result = BindType(ref resultToken, input, returnType);
}
}

message = BindCompletionMessage(invocationId, error, result, hasResult);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<Compile Include="$(SignalRSharedSourceRoot)BinaryMessageFormatter.cs" Link="BinaryMessageFormatter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)BinaryMessageParser.cs" Link="BinaryMessageParser.cs" />
<Compile Include="$(SignalRSharedSourceRoot)MemoryBufferWriter.cs" Link="Internal\MemoryBufferWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)TryGetReturnType.cs" Link="TryGetReturnType.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,21 @@ private CompletionMessage CreateCompletionMessage(ref MessagePackReader reader,
error = ReadString(ref reader, "error");
break;
case NonVoidResult:
var itemType = binder.GetReturnType(invocationId);
if (itemType == typeof(RawResult))
var itemType = ProtocolHelper.TryGetReturnType(binder, invocationId);
if (itemType is null)
{
result = new RawResult(reader.ReadRaw());
reader.Skip();
}
else
{
result = DeserializeObject(ref reader, itemType, "argument");
if (itemType == typeof(RawResult))
{
result = new RawResult(reader.ReadRaw());
}
else
{
result = DeserializeObject(ref reader, itemType, "argument");
}
}
hasResult = true;
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<Compile Include="$(SignalRSharedSourceRoot)Utf8BufferTextReader.cs" Link="Utf8BufferTextReader.cs" />
<Compile Include="$(SignalRSharedSourceRoot)Utf8BufferTextWriter.cs" Link="Utf8BufferTextWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)MemoryBufferWriter.cs" Link="MemoryBufferWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)TryGetReturnType.cs" Link="TryGetReturnType.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,21 +209,28 @@ public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)
else
{
// If we have an invocation id already we can parse the end result
var returnType = binder.GetReturnType(invocationId);

if (!JsonUtils.ReadForType(reader, returnType))
{
throw new JsonReaderException("Unexpected end when reading JSON");
}

if (returnType == typeof(RawResult))
var returnType = ProtocolHelper.TryGetReturnType(binder, invocationId);
if (returnType is null)
{
var token = JToken.Load(reader);
result = GetRawResult(token);
reader.Skip();
result = null;
}
else
{
result = PayloadSerializer.Deserialize(reader, returnType);
if (!JsonUtils.ReadForType(reader, returnType))
{
throw new JsonReaderException("Unexpected end when reading JSON");
}

if (returnType == typeof(RawResult))
{
var token = JToken.Load(reader);
result = GetRawResult(token);
}
else
{
result = PayloadSerializer.Deserialize(reader, returnType);
}
}
}
break;
Expand Down Expand Up @@ -397,14 +404,21 @@ public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)

if (resultToken != null)
{
var returnType = binder.GetReturnType(invocationId);
if (returnType == typeof(RawResult))
var returnType = ProtocolHelper.TryGetReturnType(binder, invocationId);
if (returnType is null)
{
result = GetRawResult(resultToken);
result = null;
}
else
{
result = resultToken.ToObject(returnType, PayloadSerializer);
if (returnType == typeof(RawResult))
{
result = GetRawResult(resultToken);
}
else
{
result = resultToken.ToObject(returnType, PayloadSerializer);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/SignalR/common/Shared/ClientResultsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public void RegisterCancellation()
{
// TODO: RedisHubLifetimeManager will want to notify the other server (if there is one) about the cancellation
// so it can clean up state and potentially forward that info to the connection
_clientResultsManager.TryCompleteResult(_connectionId, CompletionMessage.WithError(_invocationId, "Canceled"));
_clientResultsManager.TryCompleteResult(_connectionId, CompletionMessage.WithError(_invocationId, "Invocation canceled by the server."));
}

public new void SetResult(T result)
Expand Down
24 changes: 24 additions & 0 deletions src/SignalR/common/Shared/TryGetReturnType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;

namespace Microsoft.AspNetCore.SignalR.Protocol;

internal static class ProtocolHelper
{
internal static Type? TryGetReturnType(IInvocationBinder binder, string invocationId)
{
try
{
return binder.GetReturnType(invocationId);
}
// GetReturnType throws if invocationId not found, this can be caused by the server canceling a client-result but the client still sending a result
// For now let's ignore the failure and skip parsing the result, server will log that the result wasn't expected anymore and ignore the message
// In the future we may want a CompletionBindingFailureMessage that we can flow to the dispatcher for handling
catch (Exception)
{
return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Xunit;

namespace Microsoft.AspNetCore.SignalR.Common.Tests.Internal.Protocol;

Expand Down Expand Up @@ -460,6 +455,19 @@ public void RawResultRoundTripsProperly(string testDataName)
}
}

[Fact]
public void UnexpectedClientResultGivesEmptyCompletionMessage()
{
var binder = new TestBinder();
var message = Frame("{\"type\":3,\"result\":1,\"invocationId\":\"1\"}");
var data = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(message));
Assert.True(JsonHubProtocol.TryParseMessage(ref data, binder, out var hubMessage));

var completion = Assert.IsType<CompletionMessage>(hubMessage);
Assert.Null(completion.Result);
Assert.Equal("1", completion.InvocationId);
}

public static string Frame(string input)
{
var data = Encoding.UTF8.GetBytes(input);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Xunit;

namespace Microsoft.AspNetCore.SignalR.Common.Tests.Internal.Protocol;

Expand Down Expand Up @@ -249,6 +243,19 @@ public void RawResultRoundTripsProperly(string testDataName)
}
}

[Fact]
public void UnexpectedClientResultGivesEmptyCompletionMessage()
{
var binder = new TestBinder();
var input = Frame(Convert.FromBase64String("lQOAo3h5egPA"));
var data = new ReadOnlySequence<byte>(input);
Assert.True(HubProtocol.TryParseMessage(ref data, binder, out var hubMessage));

var completion = Assert.IsType<CompletionMessage>(hubMessage);
Assert.Null(completion.Result);
Assert.Equal("xyz", completion.InvocationId);
}

public class ClientResultTestData
{
public string Name { get; }
Expand Down
Loading