Skip to content

Add CancelInvocation support to MsgPack in TS client #7224

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 6 commits into from
Feb 8, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
21 changes: 21 additions & 0 deletions src/SignalR/clients/ts/FunctionalTests/TestHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Connections;
Expand All @@ -21,6 +22,13 @@ public class CustomObject

public class TestHub : Hub
{
private readonly IHubContext<TestHub> _context;

public TestHub(IHubContext<TestHub> context)
{
_context = context;
}

public string Echo(string message)
{
return message;
Expand Down Expand Up @@ -51,6 +59,19 @@ public ChannelReader<string> Stream()
return channel.Reader;
}

public ChannelReader<string> InfiniteStream(CancellationToken token)
{
var channel = Channel.CreateUnbounded<string>();
var connectionId = Context.ConnectionId;

token.Register(async (state) =>
{
await ((IHubContext<TestHub>)state).Clients.Client(connectionId).SendAsync("StreamCanceled");
}, _context);

return channel.Reader;
}

public async Task<string> StreamingConcat(ChannelReader<string> stream)
{
var sb = new StringBuilder();
Expand Down
33 changes: 33 additions & 0 deletions src/SignalR/clients/ts/FunctionalTests/ts/HubConnectionTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,39 @@ describe("hubConnection", () => {
});
});

it("can stream server method and cancel stream", (done) => {
const hubConnection = getConnectionBuilder(transportType)
.withHubProtocol(protocol)
.build();

hubConnection.onclose((error) => {
expect(error).toBe(undefined);
done();
});

hubConnection.on("StreamCanceled", () => {
hubConnection.stop();
});

hubConnection.start().then(() => {
const subscription = hubConnection.stream<string>("InfiniteStream").subscribe({
complete() {
},
error(err) {
fail(err);
hubConnection.stop();
},
next() {
},
});

subscription.dispose();
}).catch((e) => {
fail(e);
done();
});
});

it("rethrows an exception from the server when invoking", (done) => {
const errorMessage = "An unexpected error occurred invoking 'ThrowException' on the server. InvalidOperationException: An error occurred.";
const hubConnection = getConnectionBuilder(transportType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import { Buffer } from "buffer";
import * as msgpack5 from "msgpack5";

import { CompletionMessage, HubMessage, IHubProtocol, ILogger, InvocationMessage, LogLevel, MessageHeaders, MessageType, NullLogger, StreamInvocationMessage, StreamItemMessage, TransferFormat } from "@aspnet/signalr";
import { CancelInvocationMessage, CompletionMessage, HubMessage, IHubProtocol, ILogger, InvocationMessage,
LogLevel, MessageHeaders, MessageType, NullLogger, StreamInvocationMessage, StreamItemMessage, TransferFormat } from "@aspnet/signalr";

import { BinaryMessageFormat } from "./BinaryMessageFormat";
import { isArrayBuffer } from "./Utils";
Expand Down Expand Up @@ -75,6 +76,8 @@ export class MessagePackHubProtocol implements IHubProtocol {
return this.writeCompletion(message as CompletionMessage);
case MessageType.Ping:
return BinaryMessageFormat.write(SERIALIZED_PING_MESSAGE);
case MessageType.CancelInvocation:
return this.writeCancelInvocation(message as CancelInvocationMessage);
default:
throw new Error("Invalid message type.");
}
Expand Down Expand Up @@ -257,6 +260,13 @@ export class MessagePackHubProtocol implements IHubProtocol {
return BinaryMessageFormat.write(payload.slice());
}

private writeCancelInvocation(cancelInvocationMessage: CancelInvocationMessage): ArrayBuffer {
const msgpack = msgpack5();
const payload = msgpack.encode([MessageType.CancelInvocation, cancelInvocationMessage.headers || {}, cancelInvocationMessage.invocationId]);

return BinaryMessageFormat.write(payload.slice());
}

private readHeaders(properties: any): MessageHeaders {
const headers: MessageHeaders = properties[1] as MessageHeaders;
if (typeof headers !== "object") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,19 @@ describe("MessagePackHubProtocol", () => {
const buffer = new MessagePackHubProtocol().writeMessage({ type: MessageType.Ping });
expect(new Uint8Array(buffer)).toEqual(payload);
});

it("can write cancel message", () => {
const payload = new Uint8Array([
0x07, // length prefix
0x93, // message array length = 1 (fixarray)
0x05, // type = 5 = CancelInvocation (fixnum)
0x80, // headers
0xa3, // invocationID = string length 3
0x61, // a
0x62, // b
0x63, // c
]);
const buffer = new MessagePackHubProtocol().writeMessage({ type: MessageType.CancelInvocation, invocationId: "abc" });
expect(new Uint8Array(buffer)).toEqual(payload);
});
});
7 changes: 5 additions & 2 deletions src/SignalR/clients/ts/signalr/src/HubConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,16 @@ export class HubConnection {
const [streams, streamIds] = this.replaceStreamingParams(args);
const invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds);

let promiseQueue: Promise<void>;
const subject = new Subject<T>();
subject.cancelCallback = () => {
const cancelInvocation: CancelInvocationMessage = this.createCancelInvocation(invocationDescriptor.invocationId);

delete this.callbacks[invocationDescriptor.invocationId];

return this.sendWithProtocol(cancelInvocation);
return promiseQueue.then(() => {
return this.sendWithProtocol(cancelInvocation);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this failed before if you canceled the stream too early. Do we have any regression tests the promiseQueue part of this change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The promiseQueue doesn't change with this PR, I just use it somewhere I didn't before.
The test change needed was https://github.com/aspnet/AspNetCore/pull/7224/files#diff-e53c0bba1752f4416da08f9f40b4ac92R1078 to wait for a message since it now goes async.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know that the promiseQueue existed before. Are you saying that without this change, the "automatically sends multiple pings" would fail? Do you think that's a reliable regression test for this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "stream can be canceled" test would fail because TS isn't threaded, so the cancel message wouldn't be sent before getting to the expect(connection.sentData.length).toBe(3); check. Now the cancel callback waits until the stream has finished being started before allowing the cancel to be sent.

I think the test is good.

});
};

this.callbacks[invocationDescriptor.invocationId] = (invocationEvent: CompletionMessage | StreamItemMessage | null, error?: Error) => {
Expand All @@ -183,7 +186,7 @@ export class HubConnection {
}
};

const promiseQueue = this.sendWithProtocol(invocationDescriptor)
promiseQueue = this.sendWithProtocol(invocationDescriptor)
.catch((e) => {
subject.error(e);
delete this.callbacks[invocationDescriptor.invocationId];
Expand Down
2 changes: 2 additions & 0 deletions src/SignalR/clients/ts/signalr/tests/HubConnection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,8 @@ describe("HubConnection", () => {
// Observer should no longer receive messages
expect(observer.itemsReceived).toEqual([1]);

// Close message sent asynchronously so we need to wait
await delay(50);
// Verify the cancel is sent (+ handshake)
expect(connection.sentData.length).toBe(3);
expect(JSON.parse(connection.sentData[2])).toEqual({
Expand Down